Holiday prices end in 25d 12h 14m — See the sale

Performance Tuning

Database Animations: The Interview Question Everybody Gets Wrong

No no, I’m not just talking about the people answering the interview question.

I’m talking about the people asking the question.

Over and over, I see confident interviewers asking, “How can you tell which column should go first in an index?”

Then I see a confident candidate saying, “Check to see which column has the most distinct values, meaning it’s the most selective, and that column should go first.”

Those two people high-five each other, hug, kiss on the lips, and enter into a lasting, forever relationship, smug in the knowledge that they share the same values, when in fact those values are simply wrong. I mean, I’m not gonna judge what you’re into – I’m not here to kink-shame anybody – but even the furries know this is the wrong question and the wrong answer. (Furries out there, shout out, I love y’all.)

Let’s take the Users table from the Stack Overflow database, which has two string columns where people can type in whatever they want, and duplicates are allowed: DisplayName and Location. (Neither of those columns are unique – after all, there are a lot of people in the real world with the same fursonas.)

If we have this query:

Then which column should go first: DisplayName or Location? Right about now, some of the audience is scurrying off to query the number of distinct values in each column to see which one is more selective, but here’s the kicker:

They perform exactly the same. When you have two EQUALITY searches – that’s the key here – it doesn’t matter which column goes first. SQL Server can seek into the first value, and then seek into the second value, regardless of which column we put first.

Right about now, those same audience members who were checking unique values are screaming at the screen saying, “BUT BRENT, your example doesn’t include how the b-tree works! Surely the b-tree makes things different, right?!?” Nope, and here’s an illustration of that, too, going one index at a time since the b-tree pages take up a lot of screen resolution real estate:

When all you have is equality searches, it doesn’t really matter which column goes first in the index.

But when you have INequality searches…

Let’s change our query. Instead of looking for the Alexes who live in Seattle, let’s look for the Alexes who live anywhere OTHER than Seattle:

Now, suddenly column order matters a lot, as our next animation shall illustrate:

If we lead with DisplayName, then our query turns into two seeks:

  • Seek to Alex, then the last Seattle value, and read forwards. The instant we hit a non-Alex DisplayName, our work is done.
  • Seek to Alex, then the first Seattle value, and read backwards (everyone < Seattle.) Again, the instant we hit a non-Alex DisplayName, we’ve read too far backwards, we stop, and our work is done.

We only read the Alexes, of which there are a relatively limited number.

However, if we lead with Location, then we:

  • Seek to the last Seattle, then read forwards. We read everyone who lives > Seattle, regardless of their name. That’s gonna be a lot of people.
  • Seek to the first Seattle, then read backwards. We read everyone who lives < Seattle, regardless of name – again, a lot of people.

Bizarrely, SQL Server still calls this an index seek on the query plan because technically we know what values we’re jumping to. However, human beings like you and me (and the furries, they count as humans too, trust me) would call that a scan because of the sheer amount of data we’re reading.

So What’s the Right Question – and the Right Answer?

First off, the question can’t be about the two columns in the table – it has to be about the filters in the query. The filtering operators and the comparison values are what drives the answer.

Second, you would be forgiven for thinking that the takeaway is, “Equality searches should go first in the index, followed by the inequality searches.” After all, that’s how SQL Server’s missing index recommendations are generated. However, that isn’t the right answer either: it’s really about which searches reduce your search space as quickly as possible.

If you learned something in this post, read the rest of my free Database Animations first, and when you’ve absorbed those, check out my Fundamentals of Index Tuning class. I know you’ve been doing this stuff for years, but as you can see here, you never quite picked up the real fundamentals. It’s not your fault! Your old boss was too cheap to send you to a real training class, so you leaned on those free training videos you found on that MySpace archive. It’s time to level up, quit faking it, and stop hiding behind that awful distinct-values answer. (You can keep the furry mask on though.)

Note: I generated the animations in this post with Claude Code, but all of the text & demos are completely written by me.

Free, 3× a week

Get my new posts by email

Three posts a week, plus a Monday roundup of the best database news from around the web.

20 comments

  1. But what about statistics? If my first equality field only has one unique value, stats are significantly less useful in estimating how many rows will be returned for queries that also include the second equality field in the where clause.

  2. Unfortunately, when asked questions like this in interviews, I warn them that they’re about to get the most infuriating answer you can get from a DBA — that you often get from a DBA — when not in an outage situation (in that case, it’ll be “I dunno…” or “I quit!” or “…if the users know so much about how to do everything, why am I here and not them???”)

    “It depends…”

  3. SQL Server could become more faster, when they would improve the logic a bit (the product is ~40 years old but not to old to learn some new tricks).

    Lets use your example but with states. You are looking for all Alex in a state > Maine and have an index on state + first_name (this was the bad example).

    It could do a first seek for the last entry in Maine, and read the next entry which would be Maryland (one seek plus one additional row).
    With Maryland in the buffer it could do the second seek for Maryland + Alex and read forward until it hits something > Alex.

    Then it does a third seek for Maryland and < ZZZZZZZ to get the last entry of Maryland and reads the following row, which would bee Massachusetts, fourth seek would be for an Alex there, then the fifth to find Michigan …

    This would be way less effective when you have not just 50 distinct entries but a large number of distinct values as for location or the last_name, but hey – we have statistics that could help the SQL server engine to decide if it is more effective to do a bunch of seeks (could even go parallel) or just an initial seek plus scanning the rest of the whole table.

    And of course it could go backwards in the index too, when you would have used <> or <

    1. That makes it a more efficient use of existing indexes, but usually not more efficient in terms of reads. This is the way the postgres optimizer works primarily. Performing each of those separate reads means that the server has to read all the matching rows for each predicate when a multi column index built the right way can possibly read only the required rows. Obviously you can’t always perfectly index everything and sometimes need to make compromises, but doing separate single column seeks for every predicate is a compromise in every single multi-predicate query instead of only some of them, and you can usually create an index to be only a partial compromise for multiple queries.

      1. You misunderstood me, the index is still multi-column (over [state] + [first_name]).

        With WHERE [state] > @state AND [first_name] = ‘Alex’, it would need to do two seeks per state and wouldn’t even need to touch the leaf pages:
        1. seek for the last entry for @state + read the state in the next row to @tmp_state (not really a variable, used this for just illustration)
        2. seek for the fist Alex in @tmp_state + read forward until you find someone > Alex

        Repeat step 1 and two until there are no more states. With 50 possible states you would need to do up to 100 seeks (when you start with @state > ‘AAA’) plus a dynamic number of forward reads, depending on the number of Alexes in all those states in your user base.

        In the worst case (each state starts on a new page) you would read 50 pages too much (pages with no Alex on it).

        With the current logic it would – as Brent wrote – read the first state > @state (index seek) and ALL pages after that (although maybe just 2 percent have Alexes on it). This would be fine and fast for small tables with just 60 pages in total but on really large tables with millions of rows it reads maybe 200k rows instead of just 150 in my worst case scenario.

  4. Thanks, Brent!

    I enjoyed reading this post, and I agree with almost everything you wrote.

    I have two comments:

    You wrote near the end that “Equality searches should go first in the index, followed by the inequality searches” isn’t the right answer, and that it’s really about which searches reduce your search space as quickly as possible. I don’t see how the opposite index (first inequality searches and then equality searches) can perform better. In your example, the index on DisplayName and then Location reads exactly the rows it needs. The opposite index can be either the same or worse. It can’t be better. Can you think of a use case that doesn’t behave like that?
    The selectivity issue is still relevant for designing composite indexes, but in a different way. If the query has 4 predicates on 4 different columns, then a composite index on all 4 columns would probably be the optimal choice for reads. Still, it’s a heavy index, and you pay for storage space, DML statements, and index maintenance. If the most selective column is selective enough, you may get the same read performance with an index only on that column and save some of the costs mentioned above. Maybe you need the two most selective columns out of the 4, but you don’t necessarily need all 4 of them.

    1. Guy – great question! Like I said in the last paragraph, I know you’ve been doing this stuff for years, but as you can see here, you never quite picked up the real fundamentals. It’s not your fault! Your old boss was too cheap to send you to a real training class, so you leaned on those free training videos you found on that MySpace archive. It’s time to level up, quit faking it, and stop hiding behind that awful distinct-values answer.

      HEE HEE

      Okay, okay, because it’s you, I’mma cut you some slack. I grabbed one of the queries from the class labs as an example:

      SELECT TOP 100 Reputation, DisplayName, Location
      FROM dbo.Users
      WHERE DisplayName <> N”
      AND Location <> N”
      ORDER BY Reputation DESC;

      Without running it, guess what index SQL Server recommends in the missing index DMVs? And then guess what index really reduces your search space the most quickly, and is the right one to add?

      1. Yeah, those free training videos on that MySpace archive weren’t very good. But I have learned a few things from the field since then.

        Your example has two inequality predicates.

        I’m asking something else:
        When a query has equality and inequality predicates, and the goal is to reduce the search space as much as possible, is there any index other than all equality predicates first, then all inequality predicates – that will yield better results?

  5. Index IX_DisplayName_Location is useful also to queries like:
    Select … From … Where DisplayName=’John’

    And IX_Location_DisplayName is useful also to queries like:
    Select … From …. Where Location=’Seattle’

    If DisplayName is very selective and Location non selective, and we have to opt for one of those two,
    IX_DisplayName_Location will save us a lot of resources when we filter by Display name (in comparison to the alternative which will cause a full index scan)
    While IX_Location_DisplayName will save us a little bit in comparison to the alternative (eg: instead of full index scan, to scan just 20% using index seek).

    1. Just so I’m clear – you’re saying you would select all the rows from a table with an equality search on a non-selective field, without a top or a join to narrow down the results? How many rows would you be expecting to bring back in that case, out of how many rows in total in the table? (Genuine question.)

Leave a comment

Email me: