← Back to SQL, page 7

sql-0132 · Medium mid

In what order are UNION, INTERSECT and EXCEPT evaluated when combined in one query?

In the SQL standard and PostgreSQL, INTERSECT binds tighter than UNION and EXCEPT, which are evaluated left to right. SQLite gives all three equal precedence and evaluates strictly left to right. The same query can therefore return different results, so use parentheses or CTEs to make intent explicit.

Full answer
sql
CREATE TABLE a (x INTEGER); CREATE TABLE b (x INTEGER); CREATE TABLE c (x INTEGER);
INSERT INTO a VALUES (1),(2); INSERT INTO b VALUES (2),(3); INSERT INTO c VALUES (3);

The query is {1,2} UNION {2,3} INTERSECT {3}.

sql
SELECT x FROM a UNION SELECT x FROM b INTERSECT SELECT x FROM c ORDER BY x;
x
3
sql
SELECT x FROM a UNION SELECT x FROM b INTERSECT SELECT x FROM c ORDER BY x;
x
1
2
3

SQLite reads it left to right: ({1,2} UNION {2,3}) INTERSECT {3} = {3}. PostgreSQL follows the standard and evaluates the INTERSECT first: {1,2} UNION ({2,3} INTERSECT {3}) = {1,2,3}.

SQLite does not allow parentheses around compound SELECT branches, so the portable way to fix the order is a CTE or subquery for the part that should run first:

sql
WITH bc AS (SELECT x FROM b INTERSECT SELECT x FROM c)
SELECT x FROM a UNION SELECT x FROM bc ORDER BY x;
x
1
2
3
sql
CREATE TABLE a (x INTEGER); CREATE TABLE b (x INTEGER); CREATE TABLE c (x INTEGER);
INSERT INTO a VALUES (1),(2); INSERT INTO b VALUES (2),(3); INSERT INTO c VALUES (3);

SELECT x FROM a UNION SELECT x FROM b INTERSECT SELECT x FROM c ORDER BY x;

WITH bc AS (SELECT x FROM b INTERSECT SELECT x FROM c)
SELECT x FROM a UNION SELECT x FROM bc ORDER BY x;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Standard: INTERSECT binds tighter than UNION and EXCEPT
  • SQLite: all set operators have equal precedence, left to right
  • The same text can give different results on different engines
  • Use CTEs or subqueries to fix the order

Common mistakes

  • Mixing set operators without making the order explicit
  • Assuming parentheses around branches work in SQLite

Follow-ups

  • How would you rewrite the query to force left-to-right order in PostgreSQL?
  • Are UNION and EXCEPT associative?

Tips

  • Give a concrete three-set example