



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




text WRITTEN: SELECT โ FROM โ WHERE โ GROUP BY โ HAVING โ ORDER BY โ LIMIT EXECUTED: FROM โ WHERE โ GROUP BY โ HAVING โ SELECT โ ORDER BY โ LIMIT
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
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;
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 );
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;