Set Operation Precedence
Set Operation Precedence is a SQL statement in the Set Operations category. INTERSECT has higher precedence than UNION/EXCEPT. Use parentheses to control evaluation order. The syntax is SELECT ... UNION SELECT ... INTERSECT SELECT ...;. It returns precedence-controlled result. A typical example: SELECT 'A' AS x UNION SELECT 'A' INTERSECT SELECT 'A'; -- Evaluated as: UNION (no effect) + INTERSECT -- Returns: 'A' -- With parentheses: (SELECT 1 UNION SELECT 2) EXCEPT (SELECT 2 UNION SELECT 3); -- Returns: 1 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. More about this category: Set-based operations — UNION, UNION ALL, INTERSECT, EXCEPT.