SQL Examples
A curated set of small, realistic queries you can paste into the editor and adapt. Each one is something you'll write within your first year of doing SQL professionally.
Top N per group
Top 3 most expensive products per category:
SQL
WITH ranked AS (
SELECT id, category, name, price,
ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS rn
FROM products
)
SELECT * FROM ranked WHERE rn <= 3;
Pivot — sales by month, columns by year
SQL
SELECT MONTH(created_at) AS month,
SUM(CASE WHEN YEAR(created_at) = 2025 THEN total ELSE 0 END) AS y2025,
SUM(CASE WHEN YEAR(created_at) = 2026 THEN total ELSE 0 END) AS y2026
FROM orders
GROUP BY MONTH(created_at)
ORDER BY month;
Find duplicates
SQL
SELECT email, COUNT(*) AS dupes FROM customers GROUP BY email HAVING COUNT(*) > 1;
Running total
SQL
SELECT created_at,
total,
SUM(total) OVER (ORDER BY created_at) AS running_total
FROM orders
ORDER BY created_at;
Anti-join — customers with no orders
SQL
SELECT c.* FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL;
Recursive — manager chain up to the CEO
SQL
WITH RECURSIVE chain AS ( SELECT id, name, manager_id, 0 AS depth FROM employees WHERE id = :start UNION ALL SELECT e.id, e.name, e.manager_id, c.depth + 1 FROM employees e JOIN chain c ON c.manager_id = e.id ) SELECT * FROM chain ORDER BY depth;
Tip: When you spot a pattern that keeps coming up, save it as a snippet in your editor. Two years from now you'll thank yourself.
Example
Example
SELECT name, COUNT(*) AS orders FROM customers c JOIN orders o ON o.customer_id = c.id GROUP BY name ORDER BY orders DESC LIMIT 5;Try it Yourself »
Exercise
Window function used for "top N per group".
() OVER (PARTITION BY category ORDER BY price DESC)
Two words joined with an underscore.
Discussion
Loading…