Full answer
sql
SELECT COUNT(*) AS n FROM (SELECT 1 UNION SELECT 1 UNION ALL SELECT 1);| n |
|---|
| 2 |
Read the chain as (SELECT 1 UNION SELECT 1) UNION ALL SELECT 1. The first UNION removes the duplicate, leaving one row, and UNION ALL adds the third row as it is. Reordering the same three branches as SELECT 1 UNION ALL SELECT 1 UNION SELECT 1 gives 1, because the final UNION deduplicates everything before it. In PostgreSQL INTERSECT binds tighter than UNION and EXCEPT, while SQLite treats all compound operators with equal precedence, left to right, so parentheses are the safe way to make intent clear (PostgreSQL behaviour stated, not run here).
sql
SELECT COUNT(*) AS n FROM (SELECT 1 UNION SELECT 1 UNION ALL SELECT 1);Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Compound operators apply left to right in SQLite
- A later UNION deduplicates everything before it
- PostgreSQL gives INTERSECT higher precedence
Common mistakes
- Assuming UNION ALL anywhere keeps all duplicates
Follow-ups
- What does SELECT 1 UNION ALL SELECT 1 UNION SELECT 1 return?
- How would you write the query to make the grouping explicit?
Tips
- Bracket the first pair mentally