When merging sample sets, one might use UNION ALL
Recently I discovered [postgresql requires parentheses](https://stackoverflow.com/a/37352339/4709762) given the absence of `TOP()`
However before I googled the correct syntax; when I was keyboard mashing looking for the correct syntax, I encountered this chestnut...
WTH is going on here?
The docs are a bit vague about this. In the ["Combining Queries"](https://www.postgresql.org/docs/13/queries-union.html) section (which discusses `UNION`/`INTERSECT`/`EXCEPT`) they state:
> query1 and query2 are queries that can use any of the features discussed up to this point
Note that `ORDER BY` is not one for the features discussed ***up to this point***. The *next* section is "[Sorting Rows](https://www.postgresql.org/docs/13/queries-order.html)".
So a query that is the result of `UNION`/`INTERSECT`/`EXCEPT` cannot have multiple `ORDER BY`[^1]. It can have only one, at the very end.
None of this means you cannot have `ORDER BY` inside a *sub*query[^2].
Putting it together, the following two are equivalent:
select * from (select * from foo limit 2) x -- no need to use x(i) as the
union all -- column already has a name
select * from bar limit 2
select * from (select * from foo limit 2) x
select * from bar
[^1]: `LIMIT 2` is a special case of the `ORDER BY` clause, with undefined ordering.
[^2]: though doing so does not guarantee the ordering of the top-level query [except in the simplest cases](https://dba.stackexchange.com/a/185862/1396)
Without explicit parentheses, the second `LIMIT` is scoped to the batch, not the statement. Consider the `EXPLAIN`
Note `select...bar` is **(never executed)**
If we re-write the query as follows... we see..
From this, we can infer that in the first plan the inner limit (plan line four, query line 1) satisfies the outer limit (plan line 1, query line 3). The plan line 3 limit is parsed as limiting the entire batch (hence the need for strict parentheses usage) and the `select...bar` is short-circuited.
The absence of "correct" parentheses usage allows us to limit the inner statement and then capture the outer statement with a larger rowcount.