Ordering UNION
-ed Sets
Not-parenthesized query expressions contributing to a UNION
cannot take an ORDER BY
clause.You can order the entire output, using one ORDER BY
clause at the end of the overall query, or use parenthesized query expressions, which do allow ORDER BY
.
The simplest — and, in some cases, the only — method for specifying the sort order is by the ordinal column position.However, it is also valid to use the column names or aliases, from the first contributing query only.
The ASC
/DESC
and/or NULLS
directives are available for this global set.
If discrete ordering within the contributing set is required, use parenthesized query expressions, derived tables, or common table expressions for those sets.