Full answer
sql
SELECT 5 AS v UNION ALL SELECT 1 UNION ALL SELECT 9 ORDER BY 1 DESC LIMIT 2;| v |
|---|
| 9 |
| 5 |
The three branches produce 5, 1 and 9. The trailing ORDER BY sorts all of them, and LIMIT 2 keeps 9 and 5. SQLite does not allow ORDER BY or LIMIT inside an individual branch of a compound select without a subquery, so SELECT * FROM (SELECT ... ORDER BY ... LIMIT 1) UNION ALL ... is the way to cap one branch. PostgreSQL accepts parenthesised branches with their own LIMIT instead (PostgreSQL behaviour stated, not run here). Positional ORDER BY 1 refers to the first output column.
sql
SELECT 5 AS v UNION ALL SELECT 1 UNION ALL SELECT 9 ORDER BY 1 DESC LIMIT 2;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Final ORDER BY and LIMIT apply to the compound
- Limit a branch by wrapping it
- ORDER BY 1 is positional
Common mistakes
- Expecting LIMIT to apply only to the last branch
Follow-ups
- How would you take the top row from each branch?
- Why can positional ORDER BY be risky?
Tips
- Locate where the compound ends