SQL Queries Quick Reference
Essential SQL syntax cheat sheet covering query execution order, CASE WHEN, COALESCE, JOIN types, aggregations, CTEs, indexes, transactions, and window functions.
1 min readUpdated 2026-11-30
Query Skeleton & Execution Order
Execution order: FROM/JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
sql
SELECT column_a, COUNT(*) AS total
FROM table_name
WHERE status = 'active' AND deleted_at IS NULL
GROUP BY column_a
HAVING COUNT(*) > 1
ORDER BY total DESC
LIMIT 20;NULL Safety & Conditional Logic (COALESCE, CASE WHEN)
sql
SELECT
full_name,
COALESCE(phone, 'Not Provided') AS contact_phone,
CASE
WHEN price >= 80 THEN 'Premium'
WHEN price >= 35 THEN 'Mid-Range'
ELSE 'Budget'
END AS tier
FROM orders;Join Types at a Glance
| Join | Keeps |
|---|---|
INNER JOIN | Only matching rows in both tables |
LEFT JOIN | All rows from left table + matching right rows (NULL if none) |
RIGHT JOIN | All rows from right table + matching left rows |
FULL OUTER JOIN | All rows from both tables |
Common Table Expressions (CTEs)
sql
WITH active_courses AS (
SELECT id, title, category
FROM courses
WHERE published = TRUE
)
SELECT category, COUNT(*) AS count
FROM active_courses
GROUP BY category;Window Functions (ROW_NUMBER, RANK, LAG, Running Sum)
sql
SELECT
name,
category,
price,
ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS row_num,
RANK() OVER (PARTITION BY category ORDER BY price DESC) AS rank_pos,
SUM(price) OVER (PARTITION BY category ORDER BY price DESC) AS running_total
FROM products;Indexes & Atomic Transactions
sql
CREATE INDEX idx_orders_customer_id ON orders(customer_id);
BEGIN;
UPDATE accounts SET balance = balance - 50 WHERE id = 1;
UPDATE accounts SET balance = balance + 50 WHERE id = 2;
COMMIT; -- Or ROLLBACK; on error