SQL Mastery
SQL command families, logical query order, every join type, GROUP BY/HAVING, subqueries and EXISTS, CTEs and recursion, window functions, NULL pitfalls, upserts, and 15 classic interview queries solved (Nth salary, duplicates, top-N per group, gaps & islands, running totals, retention…).
SQL command families
| Family | Commands | Purpose |
|---|---|---|
| DDL (definition) | CREATE, ALTER, DROP, TRUNCATE | schema |
| DML (manipulation) | INSERT, UPDATE, DELETE, MERGE | data changes |
| DQL (query) | SELECT | reading |
| DCL (control) | GRANT, REVOKE | permissions |
| TCL (transaction) | BEGIN, COMMIT, ROLLBACK, SAVEPOINT | transactions |
Sample schema used below
SQL
CREATE TABLE department (id INT PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE employee (
id INT PRIMARY KEY, name TEXT NOT NULL, dept_id INT REFERENCES department(id),
manager_id INT REFERENCES employee(id), salary INT NOT NULL, hired_on DATE NOT NULL
);
CREATE TABLE customer (id INT PRIMARY KEY, name TEXT, signup_at TIMESTAMPTZ);
CREATE TABLE orders (
id INT PRIMARY KEY, customer_id INT REFERENCES customer(id),
amount NUMERIC(10,2), status TEXT, created_at TIMESTAMPTZ
);
CREATE TABLE logins (user_id INT, login_at TIMESTAMPTZ);
Logical query processing order
Joins
SQL
-- employees with their department (drops employees without one)
SELECT e.name, d.name AS dept FROM employee e JOIN department d ON d.id = e.dept_id;
-- all employees, department or NULL
SELECT e.name, d.name FROM employee e LEFT JOIN department d ON d.id = e.dept_id;
-- customers who never ordered (anti-join)
SELECT c.* FROM customer c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
-- self join: employees earning more than their manager
SELECT e.name FROM employee e JOIN employee m ON m.id = e.manager_id
WHERE e.salary > m.salary;
Aggregation
SQL
SELECT dept_id,
COUNT(*) AS headcount, -- counts rows
COUNT(manager_id) AS with_manager, -- ignores NULLs
AVG(salary)::int AS avg_salary,
SUM(salary) FILTER (WHERE hired_on >= '2025-01-01') AS new_hire_payroll
FROM employee
GROUP BY dept_id
HAVING COUNT(*) >= 5
ORDER BY avg_salary DESC;
- Every non-aggregated column in
SELECTmust be inGROUP BY(or functionally dependent on it, in Postgres). COUNT(*)vsCOUNT(col)vsCOUNT(DISTINCT col).GROUPING SETS,ROLLUP,CUBEfor subtotals in one pass.
Subqueries
| Kind | Example | Notes |
|---|---|---|
| Scalar | WHERE salary > (SELECT AVG(salary) FROM employee) | must return one value |
| IN / EXISTS (semi-join) | WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id) | EXISTS stops at the first match |
| Correlated | references the outer row | logically runs per outer row; optimisers often decorrelate |
| Derived table | FROM (SELECT …) t | needs an alias |
| LATERAL | FROM customer c, LATERAL (SELECT … WHERE customer_id = c.id LIMIT 3) x | "for each row, run this" — great for top-N per group |
CTEs and recursion
SQL
-- org chart: everyone under manager 1, with depth
WITH RECURSIVE reports AS (
SELECT id, name, manager_id, 1 AS depth
FROM employee WHERE manager_id = 1
UNION ALL
SELECT e.id, e.name, e.manager_id, r.depth + 1
FROM employee e JOIN reports r ON e.manager_id = r.id
)
SELECT * FROM reports ORDER BY depth, name;
Window functions
A window function computes a value per row over a set of related rows (the window) without collapsing them like GROUP BY does.
SQL
function(...) OVER (
PARTITION BY ... -- restart per group
ORDER BY ... -- order within the group
ROWS BETWEEN ... AND ... -- frame (default with ORDER BY: RANGE UNBOUNDED PRECEDING to CURRENT ROW)
)
| Category | Functions |
|---|---|
| Ranking | ROW_NUMBER, RANK, DENSE_RANK, NTILE(n), PERCENT_RANK, CUME_DIST |
| Offset | LAG(x, n), LEAD(x, n), FIRST_VALUE, LAST_VALUE, NTH_VALUE |
| Aggregate | SUM, AVG, COUNT, MIN, MAX over a frame |
SQL
SELECT id, customer_id, amount, created_at,
SUM(amount) OVER (PARTITION BY customer_id ORDER BY created_at) AS running_total,
AVG(amount) OVER (ORDER BY created_at ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS moving_avg_7,
amount - LAG(amount) OVER (PARTITION BY customer_id ORDER BY created_at) AS change_vs_prev,
amount * 100.0 / SUM(amount) OVER () AS pct_of_total
FROM orders;
NULL semantics
NULL = NULLis UNKNOWN, not TRUE. UseIS NULL,IS DISTINCT FROM.WHEREkeeps only TRUE rows (UNKNOWN is dropped).- Aggregates ignore NULLs (except
COUNT(*));SUMof no rows is NULL →COALESCE(SUM(x), 0). NOT INwith a NULL in the list returns nothing → preferNOT EXISTS.UNIQUEcolumns allow multiple NULLs in most databases (Postgres 15+:NULLS NOT DISTINCTto change that).
Writing data safely
SQL
-- upsert
INSERT INTO inventory (sku, qty) VALUES ('A1', 5)
ON CONFLICT (sku) DO UPDATE SET qty = inventory.qty + EXCLUDED.qty;
-- conditional update that avoids lost updates (atomic in one statement)
UPDATE account SET balance = balance - 100
WHERE id = 7 AND balance >= 100; -- check affected row count = 1
-- return what changed
UPDATE orders SET status = 'shipped' WHERE id = 99 RETURNING id, status;
15 classic interview queries
1. Nth highest salary
SQL
SELECT DISTINCT salary FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS r FROM employee
) t WHERE r = :n;
2. Highest-paid employee per department
SQL
SELECT DISTINCT ON (dept_id) dept_id, name, salary -- Postgres
FROM employee ORDER BY dept_id, salary DESC;
3. Departments with no employees
SQL
SELECT d.* FROM department d LEFT JOIN employee e ON e.dept_id = d.id WHERE e.id IS NULL;
4. Duplicate emails
SQL
SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1;
5. Employees earning above their department average
SQL
SELECT name, salary, dept_avg FROM (
SELECT name, salary, AVG(salary) OVER (PARTITION BY dept_id) AS dept_avg FROM employee
) t WHERE salary > dept_avg;
6. Monthly revenue and month-over-month growth
SQL
WITH m AS (
SELECT date_trunc('month', created_at) AS month, SUM(amount) AS revenue
FROM orders WHERE status = 'paid' GROUP BY 1
)
SELECT month, revenue,
ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
/ NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 1) AS mom_growth_pct
FROM m ORDER BY month;
7. Repeat-customer rate
SQL
SELECT COUNT(*) FILTER (WHERE n > 1) AS repeat_customers,
COUNT(*) AS customers,
ROUND(100.0 * COUNT(*) FILTER (WHERE n > 1) / COUNT(*), 1) AS repeat_pct
FROM (SELECT customer_id, COUNT(*) AS n FROM orders GROUP BY customer_id) t;
8. Running balance per account
SQL
SELECT account_id, ts, delta,
SUM(delta) OVER (PARTITION BY account_id ORDER BY ts, id) AS balance
FROM ledger_entry;
9. Consecutive login streaks (gaps and islands)
See the interview questions below for the full query: day − ROW_NUMBER() is constant within a streak.
10. Median salary
SQL
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY salary) AS median FROM employee;
11. Pivot: orders per status as columns
SQL
SELECT date_trunc('day', created_at) AS day,
COUNT(*) FILTER (WHERE status = 'paid') AS paid,
COUNT(*) FILTER (WHERE status = 'refunded') AS refunded,
COUNT(*) FILTER (WHERE status = 'pending') AS pending
FROM orders GROUP BY 1 ORDER BY 1;
12. Day-1 retention (users who came back the day after signup)
SQL
SELECT c.signup_at::date AS cohort,
COUNT(*) AS signups,
COUNT(*) FILTER (WHERE EXISTS (
SELECT 1 FROM logins l
WHERE l.user_id = c.id AND l.login_at::date = c.signup_at::date + 1
)) AS retained_d1
FROM customer c GROUP BY 1 ORDER BY 1;
13. Sessionisation (new session after 30 minutes of inactivity)
SQL
WITH flagged AS (
SELECT user_id, login_at,
CASE WHEN login_at - LAG(login_at) OVER (PARTITION BY user_id ORDER BY login_at)
> INTERVAL '30 minutes' THEN 1 ELSE 0 END AS new_session
FROM logins
)
SELECT user_id, login_at,
SUM(new_session) OVER (PARTITION BY user_id ORDER BY login_at) AS session_no
FROM flagged;
14. Swap two values (e.g. seat ids of adjacent students)
SQL
SELECT CASE
WHEN id % 2 = 1 AND id < (SELECT MAX(id) FROM seat) THEN id + 1
WHEN id % 2 = 0 THEN id - 1
ELSE id
END AS id, student
FROM seat ORDER BY id;
15. Top 10% of customers by lifetime value
SQL
SELECT customer_id, ltv FROM (
SELECT customer_id, SUM(amount) AS ltv, NTILE(10) OVER (ORDER BY SUM(amount) DESC) AS decile
FROM orders GROUP BY customer_id
) t WHERE decile = 1;
Views, procedures, triggers
- View: a stored query; materialized view stores results (refresh needed).
- Stored procedure / function: logic inside the database (fewer round trips; harder to version, test and scale).
- Trigger: runs on INSERT/UPDATE/DELETE — useful for audit logs and invariants; hidden side effects make them easy to misuse.
Performance habits
- Select only needed columns (avoid
SELECT *on wide tables — it also defeats covering indexes). - Make predicates sargable:
WHERE created_at >= '2026-01-01'uses an index,WHERE date(created_at) = '2026-01-01'may not (use an expression index or rewrite as a range). - Avoid
OFFSETpagination on large offsets — use keyset pagination (see Backend pagination). - Batch writes; avoid N+1 queries from ORMs (use joins or
INbatches). - Always read
EXPLAIN ANALYZEbefore guessing — next chapter.
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.