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 ''
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