Why MySQL OR is slower than IN percona.com · 10 points · 1 comments · HN thread ...

@best

Why MySQL OR is slower than IN percona.com · 10 points · 1 comments · HN thread

TL;DR A Percona blog post explains why a MySQL query with a long chain of OR equality conditions (id = 1 OR id = 2 ...) ran for thousands of seconds while the equivalent IN query was fast. The author attributes the gap to MySQL evaluating OR as a nested loop, costing roughly O(N²) with range access and O(T×N) with a full index scan, versus a binary search for IN. The post is tested on MySQL 8.4 with a sbtest table of up to 1M rows.

  • A query with OR across 1M rows ran for about 67,254 seconds with 99% of CPU time in Item_cond_or::val_int() on MySQL 8.4.
  • MySQL builds one Item_cond_or holding N equality items and checks each term in turn per row, a nested loop.
  • With range access the cost is about O(p×N²); with an index scan it is O(T×N), where T is table size.
  • At N = 40,000 an OR query went from 37 s to 2,907 s when the list grew by one value past the range_optimizer_max_mem_size limit of 8 MB.
  • IN lookups use a binary search (O(log N) per row), so the author concludes the IN form scales much better.
  • The range optimizer can also be skipped because of cost estimates, as shown in an optimizer trace.

Discussion The thread has only one comment, a question about whether consecutive OR conditions on the same column can be rewritten as IN. It raises the case where other conditions are mixed in, such as id = 1 OR name = 'John' OR id = 2, and asks whether that can become id IN (1,2) OR name = 'John'. The tone is neutral and curious, with no reply from the author or others.

  • Rewriting same-column ORs as IN is a natural question (most): The single commenter assumes consecutive ORs on a common column should collapse into an IN list. They also ask whether the rewrite still works when ORs on other columns are interleaved, since order may matter.

#MySQL #queryoptimization #databases #performance #Percona