← Cheat Sheets
SQL Subqueries, CTEs and Set Operations
Structure complex queries.
# SQL Subqueries, CTEs and Set Operations
Structure complex queries.
```sql
-- Common table expression
WITH recent AS (
SELECT customer_id, SUM(total) AS spent
FROM orders
WHERE created_at >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY customer_id
)
SELECT c.name, r.spent
FROM customers c JOIN recent r ON r.customer_id = c.id;
-- Subquery
SELECT * FROM products
WHERE price > (SELECT AVG(price) FROM products);
-- Set operations (same column count and types)
SELECT email FROM a UNION SELECT email FROM b; -- removes duplicates
SELECT email FROM a UNION ALL SELECT email FROM b; -- keeps duplicates
SELECT email FROM a INTERSECT SELECT email FROM b;
SELECT email FROM a EXCEPT SELECT email FROM b;
-- Conditional
SELECT CASE WHEN score >= 50 THEN 'pass' ELSE 'fail' END, COALESCE(nick, name) FROM t;
```