MySQL's OR clause is slower than IN because of a hidden O(N²) cost

Why MySQL OR is slower than IN

MySQL's OR clause is slower than IN because of a hidden O(N²) cost

A Percona analysis shows why MySQL queries with many OR conditions can take hours: the server evaluates each OR term linearly, and when the optimizer picks range access, the cost grows with the square of the number of values. A query with 34,754 OR conditions jumped from 37 seconds to 2,907 seconds after crossing the range optimizer's memory limit. Rewriting with IN uses binary search, cutting the cost to O(R log N).

Going from 34,753 OR conditions to 34,754 OR conditions pushed the ranges past the limit. The OR query went from 37 s to 2,907 s, which is 79 times longer.

More from this day

2026-11-30