Sub topic 9
Precedence and parentheses with several operators
This chapter assumes you can already write UNION, UNION ALL, INTERSECT, and EXCEPT queries with two branches. It also assumes you know that each branch must have compatible columns. Here you will chain three or more branches. When you do, the database has to decide which operator runs first, and a wrong guess silently changes your result.
Why order matters
A query with one set operator has only one possible meaning. With two operators, there are two ways to group the branches:
SELECT n FROM s1
UNION
SELECT n FROM s2
INTERSECT
SELECT n FROM s3;You could read this as (s1 UNION s2) INTERSECT s3 or as s1 UNION (s2 INTERSECT s3). These can return different rows. The database does not ask you which one you meant. It applies its own precedence rules.
The standard rules
The SQL standard sets these rules:
INTERSECTbinds more tightly thanUNIONandEXCEPT. It is evaluated first, like multiplication before addition.UNIONandEXCEPThave equal precedence. When they appear together, they are evaluated left to right.- Parentheses override everything.
Not every database follows the standard. The section on dialects below lists the main differences.
A runnable example
Create three small tables and fill them. The column n stands in for something like an email address.
CREATE TABLE s1 (n integer);
CREATE TABLE s2 (n integer);
CREATE TABLE s3 (n integer);
INSERT INTO s1 VALUES (1), (2);
INSERT INTO s2 VALUES (2), (3);
INSERT INTO s3 VALUES (3), (4);So s1 = {1, 2}, s2 = {2, 3}, and s3 = {3, 4}.
UNION with INTERSECT
SELECT n FROM s1
UNION
SELECT n FROM s2
INTERSECT
SELECT n FROM s3
ORDER BY n;Under standard precedence, the database first computes s2 INTERSECT s3, which is {3}. It then computes s1 UNION {3}, which is {1, 2, 3}.
Under strict left-to-right evaluation, it first computes s1 UNION s2, which is {1, 2, 3}. It then intersects that with s3, which gives {3}.
The same text produces three rows in one system and one row in another.
EXCEPT with INTERSECT
SELECT n FROM s1
EXCEPT
SELECT n FROM s2
INTERSECT
SELECT n FROM s3
ORDER BY n;Under standard precedence, this is s1 EXCEPT (s2 INTERSECT s3), which is {1, 2} − {3} = {1, 2}.
Under left-to-right evaluation, this is (s1 EXCEPT s2) INTERSECT s3, which is {1} ∩ {3, 4} = {}. The result is empty.
UNION with EXCEPT
SELECT n FROM s1
EXCEPT
SELECT n FROM s2
UNION
SELECT n FROM s3
ORDER BY n;EXCEPT and UNION have equal precedence in every system listed below, so this is (s1 EXCEPT s2) UNION s3. That is {1} ∪ {3, 4} = {1, 3, 4}. It is not s1 EXCEPT (s2 UNION s3), which would be {1}.
The order of the branches is part of the meaning. With EXCEPT, you cannot reorder the operands the way you can with UNION.
Using parentheses
Parentheses make the grouping explicit, and they work the same way in every system that accepts them. This is the example from the earlier chapters:
(SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers)
EXCEPT
SELECT email FROM unsubscribed;It returns every address in either customers or newsletter_subscribers, minus anyone who has unsubscribed. Without parentheses, the standard rules would give the same grouping here, because UNION and EXCEPT have equal precedence. The parentheses still help the reader.
Now suppose you want to remove unsubscribed addresses from the subscribers only, and then add all customers:
SELECT email FROM customers
UNION
(SELECT email FROM newsletter_subscribers
EXCEPT
SELECT email FROM unsubscribed);Without the parentheses, this would be (customers UNION subscribers) EXCEPT unsubscribed, which also removes unsubscribed customers. The two queries answer different business questions.
Mixing ALL and distinct operators
UNION ALL and UNION have the same precedence as each other, so a chain of them is evaluated left to right. The duplicate handling of each step applies only to the rows produced so far.
SELECT n FROM s1
UNION ALL
SELECT n FROM s2
UNION
SELECT n FROM s3;This is (s1 UNION ALL s2) UNION s3. The final UNION removes duplicates from the whole accumulated result, so the output is {1, 2, 3, 4} with each value once.
Reverse the operators and the result changes:
SELECT n FROM s1
UNION
SELECT n FROM s2
UNION ALL
SELECT n FROM s3;This is (s1 UNION s2) UNION ALL s3. The first step produces {1, 2, 3}, and the second step appends 3, 4 without removing anything. The output has five rows: 1, 2, 3, 3, 4.
A single plain UNION anywhere in a chain removes duplicates only from the rows to its left. Rows added by a later UNION ALL are not checked.
Differences between database systems
Precedence is one of the least portable parts of set operators. The table summarizes the behavior of common systems at the time of writing. Check your version's documentation before relying on it.
| System | INTERSECT vs. UNION and EXCEPT | UNION vs. EXCEPT |
|---|---|---|
| PostgreSQL | INTERSECT binds tighter | Equal, left to right |
| SQL Server | INTERSECT binds tighter | Equal, left to right |
| MySQL 8.0.31 and later | INTERSECT binds tighter | Equal, left to right |
| Oracle | All operators equal, left to right | Equal, left to right |
| SQLite | All operators equal, left to right | Equal, left to right |
Two further points matter in practice:
- Oracle calls
EXCEPTby the nameMINUS. Newer Oracle releases also acceptEXCEPT. Either way, the precedence rule in the table applies. - MySQL versions before 8.0.31 have no
INTERSECTorEXCEPTat all, so only theUNIONrows of this chapter apply there.
Parentheses around individual branches
Parentheses can also wrap a single branch. This is the only way, in most systems, to give one branch its own ORDER BY and row limit:
(SELECT email FROM customers ORDER BY created_at DESC LIMIT 100)
UNION
(SELECT email FROM newsletter_subscribers ORDER BY subscribed_at DESC LIMIT 100);This returns the 100 newest customers and the 100 newest subscribers, merged and deduplicated. Without the parentheses, an ORDER BY can appear only once, after the last branch, and applies to the whole result.
Support for this form varies:
- PostgreSQL and MySQL accept it, as shown above.
- SQL Server does not allow
ORDER BYinside a parenthesized branch unless you also useTOP. A common workaround is to put each branch in a subquery in theFROMclause. - SQLite does not accept parentheses around a branch of a compound query. Use a subquery in
FROMinstead, as inSELECT email FROM (SELECT ... LIMIT 100).
This also means that the earlier example starting with (SELECT ... UNION ...) EXCEPT ... needs a subquery rewrite in SQLite:
SELECT email FROM (
SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers
)
EXCEPT
SELECT email FROM unsubscribed;Checking your own grouping
When you are unsure how a system groups a query, test it with the three small tables from this chapter. Run the EXCEPT ... INTERSECT query:
- An empty result means the system evaluates left to right, so it treats all operators equally.
- A result of
1and2meansINTERSECTbinds tighter.
This is faster than reading documentation and tells you what your installed version does.
Common errors
- Assuming left to right everywhere. In PostgreSQL, SQL Server, and recent MySQL,
INTERSECTruns first. - Assuming INTERSECT first everywhere. In Oracle and SQLite, it does not.
- Forgetting that EXCEPT is not symmetric.
A EXCEPT B UNION CandA EXCEPT (B UNION C)are different queries. - Placing ORDER BY in the middle of a chain. A bare
ORDER BYis allowed only after the last branch. Parenthesize a branch if it needs its own ordering. - Expecting UNION ALL after UNION to keep deduplicating. The
ALLstep appends rows without checking them.
Exercise
Using the tables s1 = {1, 2}, s2 = {2, 3}, s3 = {3, 4}, what does this query return in PostgreSQL? What would it return in SQLite? Add parentheses so that the result is the same in both. SELECT n FROM s1 UNION SELECT n FROM s2 INTERSECT SELECT n FROM s3;
Show answer
In PostgreSQL, INTERSECT runs first. s2 INTERSECT s3 is {3}, and s1 UNION {3} is {1, 2, 3}. In SQLite, evaluation is left to right. s1 UNION s2 is {1, 2, 3}, and intersecting that with s3 gives {3}. To get {1, 2, 3} in both, write s1 UNION (s2 INTERSECT s3), using parentheses around the two branches or a subquery in FROM for SQLite. To get {3} in both, write (s1 UNION s2) INTERSECT s3, again with a subquery in SQLite.
Exercise
What does this query return with the same tables, and why does it differ from s1 EXCEPT (s2 UNION s3)? SELECT n FROM s1 EXCEPT SELECT n FROM s2 UNION SELECT n FROM s3;
Show answer
EXCEPT and UNION have equal precedence, so the query is (s1 EXCEPT s2) UNION s3. s1 EXCEPT s2 is {1}, and the union with {3, 4} gives {1, 3, 4}. The query s1 EXCEPT (s2 UNION s3) would remove 2, 3, and 4 from s1, leaving only {1}.
Exercise
What does (s1 UNION s2) UNION ALL s3 return, and how many rows does it have? How does that differ from (s1 UNION ALL s2) UNION s3?
Show answer
The first query returns 1, 2, 3, 3, 4, which is five rows, because UNION ALL appends s3 without removing the repeated 3. The second query returns 1, 2, 3, 4, which is four rows. The final UNION deduplicates everything produced so far, including the extra 2 from the UNION ALL step.