Ordering Set Operations
Ordering Set Operations is a SQL statement in the Set Operations category. ORDER BY on a set operation applies to the entire combined result. Place at the very end. The syntax is SELECT ... FROM table1 UNION SELECT ... FROM table2 ORDER BY column;. It returns ordered combined result. A typical example: (SELECT name, salary FROM employees WHERE dept = 'IT' ORDER BY salary DESC LIMIT 5) UNION ALL (SELECT name, salary FROM employees WHERE dept = 'HR' ORDER BY salary DESC LIMIT 5) ORDER BY salary DESC; -- Parentheses may be needed for LIMIT in individual branches A close relative is UNION, which combines results from two queries, removing duplicate rows. Each SELECT must have the same number of columns. A close relative is UNION ALL, which like UNION but does NOT remove duplicate rows. Faster because no dedup is needed. A close relative is INTERSECT, which returns rows that appear in BOTH query results. Supported in PostgreSQL, SQL Server, Oracle.