SQL Patterns
Quick reference for common SQL patterns.
CTE (Common Table Expressions)
WITH active_users AS (
SELECT id, name, email
FROM users
WHERE status = 'active'
)
SELECT * FROM active_users WHERE created_at > '2024-01-01';
Chained CTEs
WITH
active_users AS (
SELECT id, name FROM users WHERE status = 'active'
),
user_orders AS (
SELECT user_id, COUNT(*) as order_count
FROM orders GROUP BY user_id
)
SELECT u.name, COALESCE(o.order_count, 0) as orders
FROM active_users u
LEFT JOIN user_orders o ON u.id = o.user_id;
Window Functions (Quick Reference)
| Function |
Use |
ROW_NUMBER() |
Unique sequential numbering |
RANK() |
Rank with gaps (1, 2, 2, 4) |
DENSE_RANK() |
Rank without gaps (1, 2, 2, 3) |
LAG(col, n) |
Previous row value |
LEAD(col, n) |
Next row value |
SUM() OVER |
Running total |
AVG() OVER |
Moving average |
SELECT
date,
revenue,
LAG(revenue, 1) OVER (ORDER BY date) as prev_day,
SUM(revenue) OVER (ORDER BY date) as running_total
FROM daily_sales;
JOIN Reference
| Type |
Returns |
INNER JOIN |
Only matching rows |
LEFT JOIN |
All left + matching right |
RIGHT JOIN |
All right + matching left |
FULL JOIN |
All rows, NULL where no match |
Pagination
-- OFFSET/LIMIT (simple, slow for large offsets)
SELECT * FROM products ORDER BY id LIMIT 20 OFFSET 40;
-- Keyset (fast, scalable)
SELECT * FROM products WHERE id > 42 ORDER BY id LIMIT 20;
Index Quick Reference
| Index Type |
Best For |
| B-tree |
Range queries, ORDER BY |
| Hash |
Exact equality only |
| GIN |
Arrays, JSONB, full-text |
| Covering |
Avoid table lookup |
Anti-Patterns
| Mistake |
Fix |
SELECT * |
List columns explicitly |
WHERE YEAR(date) = 2024 |
WHERE date >= '2024-01-01' |
NOT IN with NULLs |
Use NOT EXISTS |
| N+1 queries |
Use JOIN or batch |
Additional Resources
For detailed patterns, load:
./references/window-functions.md - Complete window function patterns
./references/indexing-strategies.md - Index types, covering indexes, optimization
1---2name: sql-patterns3description: Quick reference for common SQL patterns, CTEs, window functions, and indexing strategies. Triggers on: sql patterns, cte example, window functions, sql join, index strategy, pagination sql.4---56# SQL Patterns78Quick reference for common SQL patterns.910## CTE (Common Table Expressions)1112```sql13WITH active_users AS (14 SELECT id, name, email15 FROM users16 WHERE status = 'active'17)18SELECT * FROM active_users WHERE created_at > '2024-01-01';19```2021### Chained CTEs2223```sql24WITH25 active_users AS (26 SELECT id, name FROM users WHERE status = 'active'27 ),28 user_orders AS (29 SELECT user_id, COUNT(*) as order_count30 FROM orders GROUP BY user_id31 )32SELECT u.name, COALESCE(o.order_count, 0) as orders33FROM active_users u34LEFT JOIN user_orders o ON u.id = o.user_id;35```3637## Window Functions (Quick Reference)3839| Function | Use |40|----------|-----|41| `ROW_NUMBER()` | Unique sequential numbering |42| `RANK()` | Rank with gaps (1, 2, 2, 4) |43| `DENSE_RANK()` | Rank without gaps (1, 2, 2, 3) |44| `LAG(col, n)` | Previous row value |45| `LEAD(col, n)` | Next row value |46| `SUM() OVER` | Running total |47| `AVG() OVER` | Moving average |4849```sql50SELECT51 date,52 revenue,53 LAG(revenue, 1) OVER (ORDER BY date) as prev_day,54 SUM(revenue) OVER (ORDER BY date) as running_total55FROM daily_sales;56```5758## JOIN Reference5960| Type | Returns |61|------|---------|62| `INNER JOIN` | Only matching rows |63| `LEFT JOIN` | All left + matching right |64| `RIGHT JOIN` | All right + matching left |65| `FULL JOIN` | All rows, NULL where no match |6667## Pagination6869```sql70-- OFFSET/LIMIT (simple, slow for large offsets)71SELECT * FROM products ORDER BY id LIMIT 20 OFFSET 40;7273-- Keyset (fast, scalable)74SELECT * FROM products WHERE id > 42 ORDER BY id LIMIT 20;75```7677## Index Quick Reference7879| Index Type | Best For |80|------------|----------|81| B-tree | Range queries, ORDER BY |82| Hash | Exact equality only |83| GIN | Arrays, JSONB, full-text |84| Covering | Avoid table lookup |8586## Anti-Patterns8788| Mistake | Fix |89|---------|-----|90| `SELECT *` | List columns explicitly |91| `WHERE YEAR(date) = 2024` | `WHERE date >= '2024-01-01'` |92| `NOT IN` with NULLs | Use `NOT EXISTS` |93| N+1 queries | Use JOIN or batch |9495## Additional Resources9697For detailed patterns, load:98- `./references/window-functions.md` - Complete window function patterns99- `./references/indexing-strategies.md` - Index types, covering indexes, optimization