SQL - OR vs UNION
This post references Leetcode SQL Question 595. Big Countries.
Question
Write a query to report the name, population, and area of the big countries. A country is big if:
- it has an area of at least three million (i.e., 3000000 km2), or
- it has a population of at least twenty-five million (i.e., 25000000).
SQL Schema
If you have your own database set up, insert the following:
Using OR
Using UNION
Why is UNION faster than OR?
In this context, we are scanning two different colums - area and population and MySQL usually uses one index per table to scan the table.
Using OR will result in a rescan to find rows that fit the 2nd index.
Using UNION, we are separaing the scan into two separate query, each with one index to scan, before combing the result together.
So, in this simple query UNION is faster because it is faster to scan separately with one index and combining the rows compared to scanning two indexes in one query.
But UNION is not always faster than OR. The speed at which union operation executes depend on the size of the sets being combined.