Ask HN: Can you explain how a database index works in an interview?
Over the course of the past year or so I've been doing a fair number of interviews for web developers (full-stack and back-end) and have asked this question nearly every time. Across a wide range of experience levels, not one has been able to answer this question well. About half just honestly say they can't, a quarter know a little bit, but can't explain it well, and the other quarter come up with some wild response. It is not my intent for this to be a "gotcha" question, I ask because I was once asked it and the learning I did after that interview really stuck with me.
How would you explain how an index works?
67 comments
[ 356 ms ] story [ 3176 ms ] threadMaybe then your question here is not so much about an eventual interviewee answer but more about how to set your own expectations.
I have seen quite a few projects where they thought they need more hardware and sharding only because they didn't have even a basic idea of database tuning.
If I was a database administrator, then it's a fair question. But if I was asked this for a full-stack web engineering role, I'd consider it a little unfair.
When I want to test database knowledge, I usually give the candidate a simple database schema and ask them to write progressively harder SQL queries. Database modeling questions are also good for teasing out the seniority of a candidate as well.
Secondly it doesn't really give any signal positive or negative wrt to full stack developers.
I mean if someone does't know how an index works it doesn't mean they can't use them effectively.
And if they can answer it, it also doesn't mean they can use them effectively.
Maybe turn the question on its head and ask....What possible info do you expect to get out of a candidate when asking this question?
How important is it to be something of a generalist, who could answer questions like this at least in broad terms, as opposed to being purely a specialist who has little knowledge outside of their domain of expertise?
Would it be significantly helpful to understand more about the things that happen under the hood, as it were, of technologies that we use?
Would a developer who could at least kind of answer this question show an aptitude for broader thought and a deeper interest in technology, and be a potentially more valuable hire as a consequence?
EDIT: To attempt to answer your question, any collection of structured data, whether objects in a memory-based data structure, delimited text fields, or a DBMS file, could be considered a database.
In many data structures, such as hash tables or primitive key/value stores, there is only one key. If you want to find data based on a field that is not the key, you either have to search sequentially through all the records, finding matches on that field, or create an index on that field.
If the number of records is small and the storage medium is fast, a sequential search may be adequate. If not, an index is needed.
Creating an index generally involves scanning all the records in the database and extracting the field required for searching, together with the location of the record within the database. The location would preferably be a direct record number to avoid unnecessary indirection, but it could also be the primary key of the database.
The list of key values and locations is put into a suitable lookup data structure. This could be something as simple as a sorted list in memory, a hash table, or a disk-based structure like a B-tree, B+-tree, or one of many others.
In the most simplistic case, looking up a record using the index means searchng the index for the matching record locator, then using that to retrieve the actual record in a separate step.
Obviously this is a bit more complex for non-unique keys, but that's the general idea.
Finally, the choice of index structure has tradeoffs, because once the index is added, it must be maintained when records are added, deleted, or modified in a way that affects the index. If the db has 100 million records, having to add a new one to a simple sorted index and re-sort it could be a performance disaster.
"Index helps you locate information quicker than usual in a database. If database is similar to a Book, then think of index as a Table Of Contents with page numbers for specific topics. Imaging if I gave you a book with 1000 pages and ask you to find a specific topic but there is no table of contents. You will have to look through many pages before you find it. If it had a table of contents, you could flip to that page much faster.
Will this answer be good enough for you ?
But then, I have no technical knowledge of how index is implemented within various databases and that is where I will say "Sorry I can't tell you the technical details".
EDIT: I will also add that it is difficult to list EVERY possible topic in a book in the table of contents. It will then defeat the purpose of the TOC. So you have to pick and choose the topics that you want to show with page numbers. Same for database index. You cannot index everything.
It gives you mappings that don't align with the primary ordering (ToC/page num).
All in all though, I'd personally be pretty happy with that answer (I'm not the OP, though...)
FWIW, books frequently also have indexes, which are a better analog to DB indexes than tables of contents are.
Someone interviewing has no idea which of the two of us they are talking to. That's why the technical interview process is so fraught.
For instance if I were an auto repair shop owner asking a technician candidate "do you know how a small block ford work" I meant how the manifold, heads, rotary etc. fit together rather than how to drive a kick ass street rod (which is cool but not the skill I'm interviewing you for)
My point was really that a major reason interviews are so daunting is that candidates don't know whether they're talking to someone like you or someone like me.
I think your answer is a great one, but that an important thing to point out (which also fits into the analogy) is that an index is a trade off between lookup efficiency vs. storage size (the more words included in a book's index, the more pages it requires) and write efficiency (every time you write a word that is included in the index, you need to go update that word's entry).
Understanding the point of indexes and their implicit trade-offs seems like fair game to me. This sort of read / write / storage size trade-off is relevant to basically all software. Having a sense for the different kinds of indexes and how they are implemented seems like bonus.
That being said I mostly agree with the other commenters that while a senior developer should know the answer, it isn't disqualifying if they don't. And if that's the case what is the point in asking it?
If I wasn't prepared I could probably say something about these schemes but database indexes are kind of specialized knowledge since they combine some attributed of in-memory data structures with the performance characteristics and limitations of storage.
Let's turn the tables here, explain in detail how a B+ tree works and what's the difference between that and a "standard" B-tree? What do you know about sstables? LSMs?
Much more interesting, IMO, and only for the certain type of dev that actually hits the database, is whether they understand that there are different index types, which to use when, and how this know-how translates to them being able to anticipate what the query plan for this or that query will look like based on the available indexes and some pointers on how the data is distributed in disk pages.
If anything you want the candidate that, given a set of assumptions, will tell you "a new index is needed here" or "a new index isn't useful for this query" because reasons and is able to explain why in sensible terms.
If you're trying to test SQL skill level, take a cursory look at the Postgres tag in StackOverflow and scan for performance-related questions. You'll find plenty of concrete "exercise" types of interview questions that, for the most part, will be straightforward for anyone with the relevant know-how to answer.
When there is no index, the database is stored in a list. You look for something, you have to go through every item.
When there is an index, the databases uses a hash table to reference the locations of items. You look for something, you get the location instantly.
It's really simple.
There are more types of structures: trees, hash tables, bimap, arrays, etc... with different performance characteristics.
So simple, in fact, that if someone tells you they don't know how a DB index works, you could easily walk them through it and, in doing so, get a much better evaluation of how they think than merely how well they can recite a bit of memorized text-book knowledge.
In fact, the only time I ever ask "Can you explain how X works?" type questions in interviews is so that I can specifically exclude asking an interviewee how to walk through the derivation of a concept with which they are already familiar. By that metric, I think your "how a DB index works" question is a great interview question!
Your mistake is stopping when they say "no".
I would imagine you either know what data-structures to use for a given data type or you do not... it's a fairly prescriptive question.
However if someone could reason by what they do know about how it might work given enough information then it'd be interesting to know what you could learn from them by walking them through the problem.
First, obviously if they take a try at it then it shows the person can reason about problems they haven't encountered by using concepts.
How much walking do you do for them and what does it tell you about their problem solving capabilities?
To give a concrete example of what that would look like with this question (let's call "A" the interviewer and "B" the interviewee):
...(this post has been truncated for your scrolling enjoyment, full version at: https://gist.github.com/jballanc/82cbe551b2b667a1ab72acabc71...)...
if you give us the answer you are expecting, it will help us evaluate the fairness of the question
My layman's understanding is that indexes are separated data structures with generally fixed size copies of one or more specific fields from the main record sorted to allow efficient searching, that contain offsets into the main record store. That is, it allows you to use that field to find records and index into the main set of data. That said, this is how I have inferred it works, and how I would initially attempt to create a database, given little or no knowledge of the field and not allowed to research.
1) All RDBMS vendors work differently. 2) It's an abstraction that's best handled by the RDBMS implementation, and is bound to change over time as versions change.
With the wording you used, some interviewees' minds will race to the limits of what they know and then panic as they think about all the things beyond that.
A "what can you tell me" question is more likely to prompt them to start with the basics and then expand more comfortably to the limits of their knowledge.
- On the 2nd year of education I knew that "index is something in database, which helps to locate data faster. Like an index at the end of a book, it helps to find the right page w/o whole scan of a book".
- Later, probably at 4th or 5th year I got the idea how these are implemented using B+-trees.
- And even later have seen some alternative implementations.
But anyways, IMO even for a senior web developer it's enough to know that index is SOME fast data structure on disc, which trades duplication and (usually) slower writes for faster lookup. And optimizer sometimes will chose index scan, sometimes won't. And to know some basic optimization techniques (like throwing ORDER BY away when data is already sorted by index).
On the other hand, if the first column isn't unique, such as employee's city or state, then the DB can use the next column as a "skip" index. So an index on "state, name" will still usually improve the query time of queries against "name" (but not as much improvement as if you had a separate index beginning with "name").
You don't need to know O notation or know what kind of trees they are (much less how they're implemented) to understand that. But if you only think of a database as an Excel table and not as trees sitting on top, you'll tend to make inefficient design decisions. And at the rate that data structures are moving into the frontend, arguably everyone in the stack should know how to think in this way.
More details on covering indexes here: https://www.simple-talk.com/sql/learn-sql-server/using-cover...
I very much prefer application-level problems that have a hundred different possible solutions. For example, for a US developer, I might ask the following question: "Given the address 123 Main St, Boston, MA 00215, write an algorithm that will break it apart into its components of number, street, city, state, and ZIP." The reason I like this is that A) everyone who lives in the US can identify those parts on sight, requiring no special domain knowledge, and B) there are a hundred ways to do it.
I often get solutions like "I'll write a regex" (Okay, write one!) or "I'd use some sort of machine learning" (Okay, write something!). Most people will start off and say "Ok, I'll split on commas and wind up with [123, 'Main St', 'Boston', 'MA 00215'], and then..." and work there way from there.
So then I can throw in any number of wrinkles.
* What if there are no commas? (this breaks the regex solution)
* What if it's "San Francisco" instead of "Boston"? How might you decide you've gotten the whole city name and not just part of it? What about "Palm Beach" vs "West Palm Beach"?
* What if we have "123 St Francis Street"? Or "12A Main St"?
* What if it's "123 Main St West Palm Beach FL"? Is it "Main St West" or is it "West Palm Beach"? How might you tell?
And so on. The possible ways to write an address are endless, and there are no correct answers right out of the box to parse the address. This gives me a glimpse into the developer's mindset: how do they initially scope the problem? do they existing solutions or do they reinvent the wheel all the problem? Do they know how to write a regex? Are they bluster or not? Can they adapt when you throw curveballs at them? Do they start thinking ahead of you and say "ok, if Boston could be San Francisco, then this problem could also happen in the street name..."? And so on.
This becomes much more of a dialogue and a discussion of the problem and possible solutions than sitting there watching someone write code under pressure and tut-tutting when they do something wrong.
(This is an actual issue I ran into on the job, so it's not just a hypothetical one.)
My two cents. Good luck.
But anyways, IMO even for a senior web developer it's enough to know that index is SOME fast data structure on disc, which trades duplication and (usually) slower writes for faster lookup. And optimizer sometimes will chose index scan, sometimes won't. And to know some basic optimization techniques (like throwing ORDER BY away when data is already sorted by index).