MySQL index_merge, or why two indexes lose to one

2026-11-28

In Efficient MySQL Performance (which I highly recommend), Daniel Nichter writes that “indexes provide the most and the best leverage for MySQL performance.” So when an endpoint that lists a person’s assignments got slow, an index was the first thing I reached for. Every assignment belongs to a tenant and to a person:

CREATE TABLE assignments (
  id         BIGINT PRIMARY KEY,
  account_id BIGINT NOT NULL,  -- tenant
  person_id  BIGINT NOT NULL,  -- belongs to the *same* tenant
  ...
  KEY index_assignments_on_account_id (account_id)
);

Notice that only the account_id column is indexed. The endpoint runs this query:

SELECT * FROM assignments
WHERE account_id = 1 AND person_id = 101

With the only existing index, MySQL reads every row in the tenant and checks person_id on each one. That gets slow in big tenants, so I added an index on person_id:

CREATE INDEX index_assignments_on_person_id ON assignments (person_id);

I left account_id out of it on purpose. A person lives in a single tenant, which is the same tenant the assignment belongs to. The account_id prefix would only make the index wider. Also, the query isn’t covered either way.

With the new index, MySQL can find the person’s rows directly and check the tenant on each one. We know that even the tenant check is redundant, but MySQL doesn’t, because it knows nothing about how our columns relate, about the nature of our data. That gap is the point of this post. In production the person_id index was highly selective, yet the query wasn’t equally fast for every tenant, and the slow ones weren’t the biggest.

Leaving the prefix out is fine as long as MySQL sticks to one index. In this post I’ll show you the optimization MySQL uses to combine two indexes, and why it can end up slower than using just one.

The data

I will run the queries on MySQL 8.4. There are eight tenants in the assignments table. The smallest has 50,000 rows and the biggest 400,000 rows. For every query, the person has exactly 2,500 rows in their tenant, spread across the whole tenant, and two other people share the rest. Altogether, the table has 1.8 million rows.

The plan kept changing between runs of the same query, depending on what was already in the buffer pool. I wanted the script to give me the same plans every time, so every query below starts with a cold buffer pool.

Full schema and seed
CREATE TABLE assignments (
  id         BIGINT AUTO_INCREMENT PRIMARY KEY,
  account_id BIGINT NOT NULL,   -- tenant
  person_id  BIGINT NOT NULL,   -- belongs to the *same* tenant
  role       VARCHAR(64) NOT NULL DEFAULT ''
) ENGINE=InnoDB;

CREATE INDEX index_assignments_on_account_id ON assignments (account_id);
CREATE INDEX index_assignments_on_person_id  ON assignments (person_id);

DELIMITER $$

CREATE PROCEDURE seed_assignments()
BEGIN
  DECLARE t INT DEFAULT 1;
  DECLARE i INT;

  WHILE t <= 8 DO
    SET i = 1;

    START TRANSACTION;
    WHILE i <= t * 50000 DO
      INSERT INTO assignments (account_id, person_id)
      VALUES (t, t * 100 + CASE WHEN i % (t * 20) = 0 THEN 1
                                WHEN i <= 2500       THEN 3
                                ELSE 2 END);
      SET i = i + 1;
    END WHILE;
    COMMIT;

    SET t = t + 1;
  END WHILE;
END$$

DELIMITER ;

CALL seed_assignments();

What it does as the tenant grows

Let’s run the same query against each tenant and see what happens. Each time, we get 2,500 rows back. Times are medians over 25 runs:

0 10 20 30 40 50 ms 50k rows: 9.2 ms 9.2 50k 100k rows: 16.4 ms 16.4 100k 150k rows: 23.1 ms 23.1 150k 200k rows: 30.3 ms 30.3 200k 250k rows: 36.9 ms 36.9 250k 300k rows: 43.9 ms 43.9 300k 350k rows: 2.4 ms 2.4 350k 400k rows: 2.9 ms 2.9 400k tenant rows

The first six bars grow in a straight line, about 7 ms per 50,000 rows in the tenant. It seems like MySQL is reading every row in the tenant instead of using only the super selective person_id index.

Then, at 350,000 rows, the query suddenly gets eighteen times faster than at 300,000. It stays fast at 400,000 too. Now, MySQL surely uses the index we were hoping it would, the person_id one.

The plans

Here are the first six. It’s the same plan on every slide, so as you click through, watch the rows= count on each of the two branches:

MySQL reads the person_id index for the person and the account_id index for the tenant, keeping only the rows that show up in both. That’s called an index merge, more specifically an intersection of two indexes. Here’s a cute little animation showing how it exactly works:

The person branch reads 2,500 rows on every slide, but the account branch reads the whole tenant every time. That explains the first six bars of the chart. Even on the smallest tenant, that’s 52,500 index rows read to return 2,500. As expected, the account scan takes up almost all of the runtime.

Now let’s look at the last two:

Here the second branch is gone: MySQL does one index lookup on person_id, reads 2,500 rows and checks the tenant on each row as it comes back. That’s exactly the optimal plan we described earlier and MySQL found it on its own.

Why it picks the merge

So why doesn’t MySQL find the same plan for the first six tenants? In MySQL’s cost model, fetching full rows from the clustered index is more expensive than reading entries in a secondary index.

In this case, the person index alone finds 2,500 rows, and each of them needs a trip to the clustered index. If MySQL thinks the two indexes overlap on far fewer rows than that, it expects the merge to cut those trips down dramatically, which makes it worth it.

How MySQL estimates the overlap

As I said, MySQL doesn’t know the two columns are related. It assumes they’re independent and multiplies:

2,500 × 100,346 / 1,795,256 ≈ 140 rows

2,500       rows for person 101, from an index dive
100,346     rows for tenant 1, from an index dive
1,795,256   rows in the table, from table statistics

MySQL got the first two numbers using an index dive. The name is quite descriptive on its own: it counts the rows in an index range by looking inside the index. As we can see, for a small range like the person’s, it’s exact, but for a big one like the tenant’s, InnoDB samples a few pages and extrapolates. That’s how tenant 1’s 50,000 rows became 100,346. The table’s row count is also an approximation.

So MySQL expects to fetch only 140 rows from the clustered index when using the merge, vs 2,500 with the person index alone. In reality, a person lives in the same tenant as the assignment, so the overlap is all 2,500 rows, instead of the expected 140.

MySQL isn’t stupid, it only adds the account index to the intersection if that lowers the cost compared to the person index alone. So as the tenant grows, the account scan gets more expensive and the estimated overlap grows with it, so there’s less left to save. Somewhere between 300,000 and 350,000 rows it stops paying off and MySQL falls back to the plain lookup.

The fix

I tried three things before I got to the one I’d actually recommend, which is fixing the database schema with a composite (account_id, person_id) index.

Turning it off everywhere

Since this optimization is useless in this case, the first thing I tried was turning intersections off altogether. Setting optimizer_switch='index_merge_intersection=off' stops MySQL from using it. Interestingly, there is a union variant, which this switch doesn’t touch. A query can merge two indexes over an OR and speed up the execution.

I wanted it off for every query the app sends. Rails has ActiveRecord.query_transformers, a list of objects that get every SQL string right before it’s sent to the database. I added one that put the switch on every query as a hint:

module IndexMergeIntersectionHint
  HINT = "/*+ SET_VAR(optimizer_switch='index_merge_intersection=off') */"

  def self.call(sql, _connection)
    sql.sub(/\A(\s*)(SELECT|UPDATE|DELETE)\b/i, "\\1\\2 #{HINT}")
  end
end

ActiveRecord.query_transformers << IndexMergeIntersectionHint

This is, of course, just a simplified version.

It fixed the problematic queries I was looking at and broke a couple I wasn’t. It turns out an intersection of two indexes that aren’t the tenant’s can be the better plan, so I only wanted it gone for the tenant index.

Turning it off for the tenant index

MySQL has a narrower hint for exactly that. NO_INDEX_MERGE takes index names and blocks merges using those indexes:

SELECT /*+ NO_INDEX_MERGE(assignments index_assignments_on_account_id) */ *
FROM assignments
WHERE account_id = 1 AND person_id = 101
-> Filter: (account_id = 1)
   (rows=140) (actual time=0.343..3.57 rows=2500)
  -> Index lookup using index_assignments_on_person_id (person_id=101)
     (rows=2500) (actual time=0.343..3.4 rows=2500)

This is the optimal plan we’ve already discussed, 2,500 person rows with the tenant checked on each. The idea was to name just the tenant index and keep it out of every intersection, while every other query still uses it as usual.

Unfortunately, that’s not what happens. The hint also stops MySQL from using the named index for a plain range scan. Say we put it on a query that reads one tenant, but only the rows after a certain id (any range condition triggers it):

SELECT /*+ NO_INDEX_MERGE(assignments index_assignments_on_account_id) */ COUNT(*)
FROM assignments
WHERE account_id = 1 AND id > 1000

Without the hint, this is a range scan over the tenant index, 49,000 entries in about 8 ms. With the hint, MySQL can’t use the tenant index for the range anymore, so it scans the primary key from id > 1000 instead:

-> Aggregate: count(0) (actual time=225..225 rows=1)
  -> Filter: ((account_id = 1) and (id > 1000))
     (rows=128233) (actual time=0.737..224 rows=49000)
    -> Index range scan using PRIMARY over (1000 < id)
       (rows=897628) (actual time=0.736..188 rows=1.8e+6)

That’s obviously not how the hint is supposed to work. I reported it to MySQL as bug #121576. They verified it the next day on 8.0, 8.4 and 9.7. This forced me to try the next solution.

Forcing the index

In the end I forced the selective index on the few queries that desperately needed it:

SELECT * FROM assignments FORCE INDEX (index_assignments_on_person_id)
WHERE account_id = 1 AND person_id = 101
-> Filter: (account_id = 1)
   (rows=11151) (actual time=0.268..1.85 rows=2500)
  -> Index lookup using index_assignments_on_person_id (person_id=101)
     (rows=78054) (actual time=0.267..1.75 rows=2500)

It worked, but I didn’t really like it. I feel this is really overcomplicating things. First, you add an index without the account_id prefix to optimize the size, but then you have to watch every query the app sends and add the optimizer hint. Not just you, but every other developer using the table.

A composite index

I would argue the better option is to fix the schema instead. The merge only happens because there are two separate indexes for MySQL to combine and neither of them covers the whole filter. In this case we can replace both with a single composite index, tenant first:

CREATE INDEX index_assignments_on_account_person
  ON assignments (account_id, person_id);
-> Index lookup using index_assignments_on_account_person
   (account_id=1, person_id=101)
     (rows=2500) (actual time=0.145..1.77 rows=2500)

Let’s run the same eight tenants again with the composite in place:

0 10 20 30 40 50 ms before with composite 50k rows, before: 9.2 ms 50k rows, with composite: 1.7 ms 9.2 1.7 50k 100k rows, before: 16.4 ms 100k rows, with composite: 1.8 ms 16.4 1.8 100k 150k rows, before: 23.1 ms 150k rows, with composite: 2.1 ms 23.1 2.1 150k 200k rows, before: 30.3 ms 200k rows, with composite: 2.3 ms 30.3 2.3 200k 250k rows, before: 36.9 ms 250k rows, with composite: 2.2 ms 36.9 2.2 250k 300k rows, before: 43.9 ms 300k rows, with composite: 2.5 ms 43.9 2.5 300k 350k rows, before: 2.4 ms 350k rows, with composite: 2.5 ms 2.4 2.5 350k 400k rows, before: 2.9 ms 400k rows, with composite: 3.0 ms 2.9 3.0 400k tenant rows

Every tenant now reads 2,500 rows in 1.7 to 3.0 ms. There’s still a slight increase as the tenant grows, but that’s not the plan’s fault anymore. Every tenant reads the same 2,500 index entries, but in a 400,000-row tenant the person’s rows are spread over a much wider range of the primary key, so they end up on more pages.

Takeaway

I think the index merge intersection is a really smart and useful optimization. But it can obviously hurt in a multi-tenanted setup. I believe a practical piece of advice we can all learn from this is to prefix every index with account_id, otherwise there’s a risk of a harmful, failed optimization like I’ve shown. In Postgres you can define the relationship between two columns via CREATE STATISTICS, but for MySQL, this general rule is the best I came up with.

So in practice: find tables where account_id and a foreign key each have their own index, and check with EXPLAIN ANALYZE whether MySQL intersects them (Intersect rows sorted by row ID). If it does, a FORCE INDEX on the foreign key index stops it right away. The better long-term fix is to replace that index with one prefixed with account_id, so you make the optimizer’s job easier.