30,000 ORs took MySQL 12 minutes. The same list as IN took 0.2 seconds
Is SQL IN faster than OR? On MySQL 8.4, 30,000 OR terms took 725 s and the same IN list 0.21 s. Postgres 18 rewrites OR into ANY. Tested, with fixes.
By Meet ModiSame table, same 30,000 ids, same plan in EXPLAIN: a full scan of a secondary index, about 986,000 rows. Written as id IN (...), MySQL 8.4 counted them in 0.21 seconds. Written as id = 1 OR id = 2 OR ..., it took 725 seconds. Nothing in the plan tells you which of the two you are about to get.
So, SQL IN vs OR: are they the same? Logically yes, and for a handful of values the speed is the same too. For long lists, IN is faster in MySQL, because MySQL sorts a constant IN list once and binary searches it for every row, while a chain of ORs is checked one term at a time. Postgres 18 sidesteps most of it by rewriting the ORs into an array before planning. Here is what that looks like with real numbers, and where the cliff is.
Why is OR slower than IN in MySQL
This started with a Percona post by Jinyou Ma, dated November 19 and on the Hacker News front page on November 28. A count over about a million rows with a long OR list ran for a very long time, and a CPU profile put 98.96% of it in one function, Item_cond_or::val_int. That is the code that evaluates an OR condition against a row. It walks the terms in order until one matches.
IN gets a shortcut that OR does not. The MySQL 8.4 manual says that when the IN list is all constants of the same type, "The values the list are sorted and the search for expr is done using a binary search, which makes the IN() operation very quick." So checking one row against 30,000 values is about 15 comparisons for IN and up to 30,000 for OR.
That alone does not hurt much when the optimizer uses range access, because range access jumps straight to the matching rows in the index. The catch is that MySQL still re-checks the WHERE clause on every row the range returns. N rows come back, each one gets compared against an N-term OR, and you have N squared comparisons. With IN, it is N times log N.
IN vs OR performance in MySQL 8.4, measured
I built a sysbench-shaped table on MySQL 8.4.13 with default settings: one million rows, an integer primary key id, an indexed integer k, and two padding columns. Then I generated both versions of SELECT COUNT(*) FROM sbtest1 WHERE ... with ids 1 to N, and timed them from the client on a 2 vCPU runner. One run each, so the small numbers are rough.
N plan (both) IN OR
1,000 range on PRIMARY 0.029 s 0.037 s
5,000 range on PRIMARY 0.045 s 0.276 s
10,000 range on PRIMARY 0.055 s 1.013 s
20,000 range on PRIMARY 0.080 s 3.890 s
30,000 index scan on k_1 0.211 s 725.067 sBetween 5,000 and 10,000 the OR time grows by 3.7x for twice the values, and from 10,000 to 20,000 by 3.8x. That is the quadratic re-check. IN barely notices the list getting longer. Under a thousand values, which is most real queries, the difference is a few milliseconds and not worth a code change.
Then the last row. At 30,000 values, EXPLAIN stops saying range and starts saying index, with 986,400 rows, and MySQL raises a warning:
explain: type=index key=k_1 rows=986400
warning: 3170 Memory capacity of 8388608 bytes for 'range_optimizer_max_mem_size' exceeded.
Range optimization was not done for this query.
in N=30000 count=30000 time=0.211s
or N=30000 count=30000 time=725.067sBoth versions fell off the same cliff, and both now read every row. IN binary searches 30,000 sorted values for each of a million rows and finishes in a fifth of a second. OR compares each of a million rows against up to 30,000 terms, about 30 billion comparisons in the worst case, and took just over 12 minutes. The Percona post saw a 40,000-term version of this take 3,406 seconds on its machine.
What is range_optimizer_max_mem_size
It caps the memory the optimizer may spend working out range access. The range optimization chapter says that when the limit is about to be exceeded, "the range access method is abandoned and other methods, including a full table scan, are considered instead". The default on 8.4.13 is 8,388,608 bytes. A value of 0 means no limit.
The same page gives an estimate: each predicate combined with OR on one candidate key uses "approximately 230 bytes", and each literal in an IN list counts as one OR predicate. That puts the default cliff at around 36,000 values. Percona hit it between 34,753 and 34,754. I bisected with EXPLAIN alone, which is fast because it plans without running:
table last range first scan
sbtest1, 1M rows, with k_1 22,396 22,397 (IN and OR identical)
t100k, 100k rows, with k_1 22,396 22,397
nok, 100k rows, no k_1 28,251 28,252
sbtest1, limit set to 1 MB 1,945 1,946Table size did not matter. The second index did: dropping it moved the cliff by almost 6,000 values, even though the query never filters on k. The docs' figure is for a table with one candidate key, so treat 230 bytes as the optimistic case and do not do arithmetic with it in production.
And the cliff is a cliff. On the 100,000-row table, one more OR term changed the plan and the time:
or N=22396 type=range key=PRIMARY rows=22396 time=4.932s
or N=22397 type=index key=k_1 rows=98712 time=39.602s (warning 3170)
in N=22397 type=index key=k_1 rows=98712 time=0.070s (warning 3170)8x slower for one extra value on 100,000 rows. Percona's 1M-row table went from 37 s to 2,907 s for the same step, 79x. The penalty scales with the table, since the scan reads every row.
Does Postgres have the same IN vs OR problem
Much less, since version 18. The PostgreSQL 18 release notes (18.0 shipped on September 25, 2025) include "Allow transforming OR-clauses to arrays for faster index processing". Same table shape on PostgreSQL 18.7, five ORs:
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)
SELECT COUNT(*) FROM sbtest1 WHERE id = 1 OR id = 2 OR id = 3 OR id = 4 OR id = 5;
Aggregate (actual rows=1.00 loops=1)
-> Index Only Scan using sbtest1_pkey on sbtest1 (actual rows=5.00 loops=1)
Index Cond: (id = ANY ('{1,2,3,4,5}'::integer[]))The ORs are gone before the executor sees them. It even works inside a mixed condition: id = 1 OR id = 2 OR k = 3 became a BitmapOr of id = ANY('{1,2}') and k = 3. The cost moved to the planner instead:
N form planning execution total
30,000 IN 19.9 ms 7.7 ms 43.9 ms
30,000 OR 172.1 ms 8.0 ms 236.4 ms
100,000 IN 65.9 ms 26.8 ms 145.6 ms
100,000 OR 1,266.3 ms 26.6 ms 1,469.9 msExecution is identical, as it should be, since it is the same plan. Planning 100,000 ORs costs 19x what planning the IN list does, and it grows faster than the list: 3.3x more terms, 7.4x more planning time. That is a second and a bit on a query nobody should be sending, so it is a curiosity rather than an incident. I only had Postgres 18 here, so the before on 17 comes from the release note, not a run.
How to fix a slow OR query in MySQL
Long OR chains are rarely typed by hand. More often a loop or a query builder appends one term per element, and nobody reads the SQL until it is slow. Query builders doing something nobody asked for is a recurring theme, a shorthand parameter only one layer understood being another flavour of it. In order of how much I would reach for them:
- Rewrite the OR chain as IN. Same result for equality on one column, and it gets the binary search. For lists under a few thousand values this is all you need.
- Past ten thousand or so, stop sending a list. Join against the ids instead, either a VALUES table constructor or a temporary table. Both stay on primary key lookups and never touch the range optimizer.
- Batch. Splitting 30,000 ids into chunks of 1,000 keeps every query far from the cliff and keeps each statement small enough to read in a slow log.
- Raise range_optimizer_max_mem_size for one session, not the server. It works, but it only moves the cliff, and the docs give no reliable way to know where the new one is.
The join versions, with the same 30,000 ids and default settings:
-- VALUES as a derived table
SELECT COUNT(*) FROM sbtest1 s
JOIN (VALUES ROW(1), ROW(2), /* ... */ ROW(30000)) AS v(id) ON s.id = v.id;
-- 1 row in set (0.12 sec)
-- plan: <derived2> ALL 30000, then s eq_ref PRIMARY
-- Temporary table
CREATE TEMPORARY TABLE ids (id INT PRIMARY KEY);
INSERT INTO ids VALUES (1), (2), /* ... */ (30000); -- 0.13 sec
SELECT COUNT(*) FROM sbtest1 s JOIN ids USING (id);
-- 1 row in set (0.08 sec)
-- plan: ids index PRIMARY, then s eq_ref PRIMARYAnd the knob, for completeness. With the limit turned off for the session, the 30,000-term OR went back to range access and finished in 9.04 seconds. Better than 725, still 81x slower than IN on the same plan, which landed at 0.111 s:
SET SESSION range_optimizer_max_mem_size = 0;
-- or N=30000 type=range key=PRIMARY rows=30000 time=9.040s
-- in N=30000 type=range key=PRIMARY rows=30000 time=0.111sRaising it fixes the plan and leaves the quadratic re-check in place. Rewriting to IN fixes both.
How to tell if a query fell off the cliff
- Run EXPLAIN, then SHOW WARNINGS in the same session. Warning 3170 is the only direct signal that range optimization was skipped.
- Watch the type column. A query on an indexed id with type index or ALL and rows close to the table size is a scan, whatever the WHERE clause looks like.
- Check the slow log for Rows_examined equal to the table size on a query that should touch a few thousand rows.
- For UPDATE and DELETE with sql_safe_updates on, the manual says the fallback becomes an error instead of a warning, which is the louder and better outcome.
The catch: these numbers are one machine and one table shape
- The 725 seconds is a worst case I built on purpose: 30,000 sequential ids on a 2 vCPU runner with a 128 MB buffer pool. Your OR query with 40 values is fine. The point is the shape of the curve, not the headline.
- The cliff moved by 6,000 values when one unrelated index was dropped. Your schema will put it somewhere else. Measure with EXPLAIN on your own table instead of trusting my numbers or the manual's estimate.
- I only ran MySQL 8.4.13. I did not test 9.x and found nothing saying it rewrites OR into IN, so I am not claiming it does or does not.
- Postgres 18 removes the execution penalty, not the planning cost, and I could not measure 17 here. Huge parameter lists are also a problem in their own right: the statement still has to travel, parse and sit in your logs.
- IN is only interchangeable with OR for equality on one column. id = 1 OR status = 'x' is a different query, and no rewrite in this post applies to it.
Is IN faster than OR in SQL?
In MySQL, yes for long lists. MySQL sorts a constant IN list and binary searches it for each row, while OR checks terms one by one. On 1M rows, 20,000 values took 0.08 s as IN and 3.9 s as OR. For a few dozen values the difference is negligible. PostgreSQL 18 rewrites same-column ORs into an array, so execution matches.
Is there a limit on the number of values in a MySQL IN clause?
No hard limit on count. The manual says the number of values in IN() is only limited by max_allowed_packet. The practical limit is range_optimizer_max_mem_size, 8 MB by default: past it, MySQL abandons range access and scans. On my test table that happened at 22,397 values, for IN and OR alike.
What is range_optimizer_max_mem_size in MySQL?
It is the memory cap for the range optimizer, 8,388,608 bytes by default in MySQL 8.4. When a query's range analysis would exceed it, MySQL gives up on range access, raises warning 3170, and picks another plan, often a full scan. Setting it to 0 removes the limit. Raise it per session, not globally.
Does PostgreSQL convert OR to IN?
Yes, since PostgreSQL 18. The release notes describe it as transforming OR clauses to arrays for faster index processing. A chain like id = 1 OR id = 2 shows up in EXPLAIN as id = ANY('{1,2}'). In my test, execution time then matched IN exactly, but planning 100,000 ORs took 1.27 seconds against 66 ms.
How do I speed up a MySQL query with thousands of OR conditions?
Rewrite it as a single IN list first, which gets a binary search instead of a term-by-term check. For tens of thousands of values, join against a VALUES table constructor or a temporary table with a primary key. Both ran in about a tenth of a second for 30,000 ids on a 1M-row table.
Why did my MySQL query switch to a full table scan with a big IN list?
Most likely the range optimizer ran out of memory. Run EXPLAIN and then SHOW WARNINGS: warning 3170 says range_optimizer_max_mem_size was exceeded and range optimization was not done. The fix is a shorter list, batching, or a join. Raising the limit for the session also works but only moves the threshold.
- Why MySQL OR is slower than IN, Percona
- MySQL 8.4 Reference Manual: Range Optimization, MySQL
- MySQL 8.4 Reference Manual: Comparison Functions and Operators, MySQL
- MySQL 8.4 Reference Manual: VALUES Statement, MySQL
- PostgreSQL 18.0 release notes, PostgreSQL Global Development Group
More Posts
Next.js 16.5 compiles 4.2x faster. This blog got 1.35x
Next.js 16.5 on a 92-page static site with 2 cores: cold Turbopack compile went from 7.0 s to 5.2 s with 21% less memory. Not 4x. Warm builds didn't move.
I made a post-quantum SSH key. GitHub never answered it
A post-quantum SSH key is one ssh-keygen command in OpenSSH 10.6. GitHub, GitLab, Bitbucket, Codeberg and sourcehut can't use it, and GitHub just hangs.
I painted over a 4-digit code and read it back from the pixels outside the box
Can you unredact an image? From lossy WebP, yes: I got a hidden 4-digit code back from pixels 96 px outside the box. JPEG with a 16 px margin leaked nothing.