INTERSECT with ORDER BY
INTERSECT with ORDER BY is a SQL statement in the Set Operations category. INTERSECT returns common rows. ORDER BY at the end sorts the final result. The syntax is SELECT col FROM t1 INTERSECT SELECT col FROM t2 ORDER BY col;. It returns ordered intersection result. A typical example: SELECT product_id FROM products INTERSECT SELECT product_id FROM current_stock ORDER BY product_id; -- Products that exist AND are in stock, ordered by id -- INTERSECT removes duplicates automatically -- Use INTERSECT ALL to preserve duplicates (supported in some databases) 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.