UNION with Subquery
UNION with Subquery is a SQL statement in the Set Operations category. Wrapping a UNION in a subquery allows ORDER BY, LIMIT, or additional filtering on the combined result. The syntax is SELECT * FROM (SELECT ... UNION SELECT ...) AS derived ORDER BY col;. It returns filtered union result. A typical example: SELECT * FROM ( SELECT id, name, salary FROM current_employees UNION ALL SELECT id, name, salary FROM former_employees ) AS all_staff WHERE salary > 50000 ORDER BY salary DESC LIMIT 10; -- Top 10 highest paid current or former employees 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.