{}DSA Atlas

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…).

Beginner → Advanced12 interview questions

SQL command families

FamilyCommandsPurpose
DDL (definition)CREATE, ALTER, DROP, TRUNCATEschema
DML (manipulation)INSERT, UPDATE, DELETE, MERGEdata changes
DQL (query)SELECTreading
DCL (control)GRANT, REVOKEpermissions
TCL (transaction)BEGIN, COMMIT, ROLLBACK, SAVEPOINTtransactions

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

FROM WHERE GROUP BY HAVING WINDOW SELECT ORDER BY LIMIT aliases defined in SELECT are visible only to ORDER BY (and LIMIT); aggregates are filtered in HAVING
The order the database logically evaluates a query — not the order you write it.

Joins

INNER LEFT FULL OUTER LEFT anti-join
Venn diagrams are an approximation: joins multiply matching rows, they don't just "overlap sets".
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 SELECT must be in GROUP BY (or functionally dependent on it, in Postgres).
  • COUNT(*) vs COUNT(col) vs COUNT(DISTINCT col).
  • GROUPING SETS, ROLLUP, CUBE for subtotals in one pass.

Subqueries

KindExampleNotes
ScalarWHERE 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
Correlatedreferences the outer rowlogically runs per outer row; optimisers often decorrelate
Derived tableFROM (SELECT …) tneeds an alias
LATERALFROM 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)
)
CategoryFunctions
RankingROW_NUMBER, RANK, DENSE_RANK, NTILE(n), PERCENT_RANK, CUME_DIST
OffsetLAG(x, n), LEAD(x, n), FIRST_VALUE, LAST_VALUE, NTH_VALUE
AggregateSUM, 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 = NULL is UNKNOWN, not TRUE. Use IS NULL, IS DISTINCT FROM.
  • WHERE keeps only TRUE rows (UNKNOWN is dropped).
  • Aggregates ignore NULLs (except COUNT(*)); SUM of no rows is NULL → COALESCE(SUM(x), 0).
  • NOT IN with a NULL in the list returns nothing → prefer NOT EXISTS.
  • UNIQUE columns allow multiple NULLs in most databases (Postgres 15+: NULLS NOT DISTINCT to 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 OFFSET pagination on large offsets — use keyset pagination (see Backend pagination).
  • Batch writes; avoid N+1 queries from ORMs (use joins or IN batches).
  • Always read EXPLAIN ANALYZE before guessing — next chapter.

Interview questions

0 / 12 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.