Databases 3 min read

Why UNION Queries Outperform OR Conditions in MySQL: A Deep Dive

This article explains why replacing OR conditions with UNION queries in MySQL often yields faster execution, using a concrete users table example, EXPLAIN analysis, and a comparison of type and ref values to illustrate the performance advantage of UNION over OR.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Why UNION Queries Outperform OR Conditions in MySQL: A Deep Dive

In many SQL‑optimization guides it is suggested to replace an OR condition with a UNION query.

Example

Using OR: SELECT * FROM a, b WHERE a.p = b.q OR a.x = b.y; Using UNION (producing the same result but faster):

SELECT * FROM a, b WHERE a.p = b.q
UNION
SELECT * FROM a, b WHERE a.x = b.y;

Although UNION executes two separate SELECT statements, the OR version performs a single scan and can be slower. Why?

Test case

We query the users table, which has an index on user_id, looking for rows with user_id='IjPEBWuEQZ' or user_id='FwYEz8Bzp'.

OR query:

SELECT * FROM users WHERE user_id='IjPEBWuEQZ' OR user_id='FwYEz8Bzp';

UNION query:

SELECT * FROM users WHERE user_id='IjPEBWuEQZ'
UNION
SELECT * FROM users WHERE user_id='FwYEz8Bzp';

Running EXPLAIN on both statements shows the following differences:

The key differences are the type and ref columns in the EXPLAIN output. UNION yields type =ref and ref =const, while OR yields type =range and ref =null. Since ref =const is a direct constant lookup, UNION is clearly faster.

In short, UNION uses a precise index lookup for each constant value, whereas OR forces the optimizer to compare multiple values, resulting in a less efficient range scan.

SQLQuery OptimizationMySQLIndexesUNIONor
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.