Docsity

Comprehensive SQL Cheat Sheet & Quick Reference Guide, Exams of Programming Languages

Toggle sidebar
bg1
SQL Logic Cheat Sheet
1. Query Execution Order (The Logic Backbone)
Write in this order โ†’ but SQL executes in a different order:
text
WRITTEN: SELECT โ†’ FROM โ†’ WHERE โ†’ GROUP BY โ†’ HAVING โ†’ ORDER BY โ†’ LIMIT
EXECUTED: FROM โ†’ WHERE โ†’ GROUP BY โ†’ HAVING โ†’ SELECT โ†’ ORDER BY โ†’ LIMIT
Why it matters: You can't use a SELECT alias in WHERE (it doesn't exist yet), but you can in
ORDER BY.
2. Filtering Logic
sql
-- WHERE = row-level filter (before grouping)
SELECT * FROM orders
WHERE status = 'shipped'
AND total > 100
AND created_at >= '2025-01-01'
AND customer_id IN (SELECT id FROM vip_customers)
AND email LIKE '%@gmail.com'
AND deleted_at IS NULL; -- NULL needs IS, never = NULL
-- HAVING = group-level filter (after GROUP BY)
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 5; -- can't use WHERE here
Logic rule: WHERE filters individual rows. HAVING filters groups. NULL is never equal to
anythingโ€”use IS NULL / IS NOT NULL / COALESCE().
3. Join Logic
pf3
pf4
pf5

Partial preview of the text

Download Comprehensive SQL Cheat Sheet & Quick Reference Guide and more Exams Programming Languages in PDF only on Docsity!

SQL Logic Cheat Sheet

1. Query Execution Order (The Logic Backbone)

Write in this order โ†’ but SQL executes in a different order:

text WRITTEN: SELECT โ†’ FROM โ†’ WHERE โ†’ GROUP BY โ†’ HAVING โ†’ ORDER BY โ†’ LIMIT EXECUTED: FROM โ†’ WHERE โ†’ GROUP BY โ†’ HAVING โ†’ SELECT โ†’ ORDER BY โ†’ LIMIT

Why it matters: You can't use a SELECT alias in WHERE (it doesn't exist yet), but you can in

ORDER BY.

2. Filtering Logic

sql -- WHERE = row-level filter (before grouping) SELECT * FROM orders WHERE status = 'shipped' AND total > 100 AND created_at >= '2025- 01 - 01' AND customer_id IN (SELECT id FROM vip_customers) AND email LIKE '%@gmail.com' AND deleted_at IS NULL; -- NULL needs IS, never = NULL -- HAVING = group-level filter (after GROUP BY) SELECT customer_id, COUNT() AS order_count FROM orders GROUP BY customer_id HAVING COUNT() > 5 ; -- can't use WHERE here

Logic rule: WHERE filters individual rows. HAVING filters groups. NULL is never equal to

anythingโ€”use IS NULL / IS NOT NULL / COALESCE().

3. Join Logic

Join Returns

INNER JOIN Only matching rows in both

LEFT JOIN All left rows + matches (NULL if none)

RIGHT JOIN All right rows + matches

FULL OUTER JOIN All rows from both

CROSS JOIN Cartesian product (every combination)

sql -- Find customers with NO orders (anti-join pattern) SELECT c.id, c.name FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL; -- the "no match" filter -- Self-join: employees and their managers SELECT e.name AS employee, m.name AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.id;

Logic rule: Start from the table you want all rows from, then LEFT JOIN the rest.

4. Aggregation Logic sql SELECT department, COUNT(*) AS total, COUNT(DISTINCT email) AS unique_people, AVG(salary) AS avg_salary, SUM(salary) AS payroll, MIN(hire_date) AS first_hire, MAX(hire_date) AS latest_hire FROM employees

-- Correlated subquery: references outer query SELECT name FROM customers c WHERE EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.id );

Logic rule: If a query has 3+ joins or nested subqueries, refactor into CTEs. Each CTE

should do one thing.

7. Set Operations sql SELECT id FROM table_a UNION -- combines + removes duplicates SELECT id FROM table_b; SELECT id FROM table_a UNION ALL -- combines + keeps duplicates (faster) SELECT id FROM table_b; SELECT id FROM table_a INTERSECT -- rows in BOTH SELECT id FROM table_b; SELECT id FROM table_a EXCEPT -- rows in A but NOT in B SELECT id FROM table_b; 8. Common Patterns sql -- Top N per group SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) rn FROM employees ) t WHERE rn <= 3 ;

-- Deduplicate: keep latest row per key SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC) rn FROM users ) t WHERE rn = 1 ; -- Running total SELECT date, amount, SUM(amount) OVER (ORDER BY date) AS running_total FROM transactions; -- Pivot with conditional aggregation SELECT product, SUM(CASE WHEN month = 'Jan' THEN sales ELSE 0 END) AS jan, SUM(CASE WHEN month = 'Feb' THEN sales ELSE 0 END) AS feb FROM monthly_sales GROUP BY product;