Set Operation with ORDER BY
Set Operation with ORDER BY is a SQL statement in the Set Operations category. ORDER BY in a set operation applies to the entire combined result set. Column names from the first query. The syntax is SELECT ... FROM table1 UNION SELECT ... FROM table2 ORDER BY column1;. It returns ordered combined result. A typical example: SELECT name, salary, 'Employee' AS source FROM employees UNION ALL SELECT name, commission, 'Contractor' FROM contractors ORDER BY salary DESC; -- Combined list sorted by salary descending -- ORDER BY can reference column position: ORDER BY 2 DESC -- LIMIT can be applied to the whole set result 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.