hn.today

Why MySQL OR is slower than IN

percona.com21 points12 comments
Screenshot of Why MySQL OR is slower than IN

MySQL can make a long chain of equality checks joined by OR dramatically slower than an equivalent IN condition. In the example, a COUNT query with roughly a million rows examined took about 67,254 seconds, and profiling showed nearly all CPU time was spent evaluating the OR expression - not reading the index. MySQL represents the OR list as individual equality tests and checks them sequentially until it finds a match. By contrast, its implementation of IN searches a sorted list with binary search, reducing the work per lookup from linear to logarithmic in the number of values.

The overall cost of OR depends on the table access plan. With range access, the index retrieves matching rows, but MySQL still tests each against the OR terms; when the list’s values all exist, this can mean roughly N²/2 checks for N values. In the example, execution time stayed similar as the table grew from 100,000 to one million rows, because the work was driven mainly by the list size. With a full index scan, every table row is tested against the list, producing cost proportional to T × N, where T is the number of rows. For a million-row table and 40,000 values, that amounts to about 40 billion checks, compared with roughly 800 million under range access. Thus, both the predicate form and the optimizer’s access type matter; a full scan can make a long OR list especially expensive.

Read on percona.com12 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

Personal Computing

Personal Computing

Cory Doctorow recalls Vernor Vinge’s visionary novel *Rainbows End* and the friendship and encouragement he shared with its author. He connects its vision of personal computing to vibe coding, while asking who will build and maintain the free and open-source software it depends on. (pluralistic.net)

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.