Set Operations with CTE
Set Operations with CTE is a SQL statement in the Set Operations category. Combine the power of CTEs with set operations for cleaner, more modular queries. The syntax is WITH cte AS (SELECT ...) SELECT * FROM cte UNION SELECT * FROM other;. It returns cTE-powered set operation. A typical example: WITH active_users AS ( SELECT id, name, email FROM users WHERE status = 'active' ), bounced_users AS ( SELECT id, name, email FROM users WHERE email_bounced = 1 ) SELECT id, name, email, 'Active' AS status FROM active_users UNION ALL SELECT id, name, email, 'Bounced' AS status FROM bounced_users ORDER BY status, name; -- CTE + UNION ALL for a clean combined report 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.