INNER JOIN: only customers who have orders (the overlap).
LEFT JOIN: all customers, with their orders if any; customers without orders get NULLs.
RIGHT JOIN: the mirror of LEFT, rarely used.
-- customers who never ordered
SELECT c.id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;
Say it like this in the interview
“INNER returns matching rows from both tables; LEFT returns all rows from the left table plus matches, with NULLs where there’s no match. A LEFT JOIN with WHERE right.id IS NULL finds rows without a match, like customers who never ordered.”
Traps that make people fail
Putting a condition on the right table in WHERE instead of ON, which silently turns a LEFT JOIN into an INNER JOIN.
WHERE filters rows before grouping. HAVING filters groups after grouping, so it can use COUNT() or SUM().
SELECT customer_id, COUNT(*) AS orders
FROM orders
WHERE status = 'paid' -- rows
GROUP BY customer_id
HAVING COUNT(*) >= 5; -- groups
Say it like this in the interview
“WHERE filters rows before aggregation and can’t use aggregates; HAVING filters groups after GROUP BY. I filter as much as possible in WHERE, since it reduces work.”
NULL means “unknown”. Is unknown different from 5? Unknown! So NULL rows are not returned. Any comparison with NULL gives unknown, which is not true.
Say it like this in the interview
“7. Comparisons with NULL yield UNKNOWN, which is filtered out. I’d write WHERE discount <> 5 OR discount IS NULL, or use COALESCE. Also COUNT(column) skips NULLs while COUNT(*) counts all rows.”
You write SELECT first, but the database runs it in a different order: find the tables, filter rows, group, filter groups, then pick columns, sort and limit. That’s why you can’t use a column alias in WHERE.
Say it like this in the interview
“Logically: FROM and JOINs, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, then LIMIT/OFFSET. So aliases defined in SELECT aren’t visible in WHERE but are usable in ORDER BY.”
GROUP BY squashes rows into one row per group. Window functions calculate across a group of rows but keep every row, like adding a “rank in department” or “running total” column.
SELECT order_date, amount,
SUM(amount) OVER (ORDER BY order_date) AS running_total,
LAG(amount) OVER (ORDER BY order_date) AS previous_amount
FROM orders;
Say it like this in the interview
“Window functions like ROW_NUMBER, RANK, SUM() OVER, LAG and LEAD compute over a partition while returning every row. Used for rankings, running totals, moving averages and comparing to the previous row.”
Both stack results of two queries. UNION removes duplicate rows (extra work); UNION ALL keeps everything (faster).
Say it like this in the interview
“UNION deduplicates, which requires a sort or hash; UNION ALL simply appends. I use UNION ALL unless I specifically need deduplication. Column counts and types must match.”
A JOIN combines columns from two tables. EXISTS just asks “is there at least one matching row?”, and can stop at the first match.
Say it like this in the interview
“JOIN when I need columns from both tables. EXISTS for existence checks, which can stop early and handles NULLs safely; NOT IN with a subquery returning NULL gives no rows at all, so NOT EXISTS is safer. Modern optimisers often produce similar plans; I check with EXPLAIN.”
SELECT * FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders);
-- fix:
SELECT * FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
In simple words
If the subquery returns even one NULL, NOT IN compares against “unknown”, and the whole condition becomes unknown for every row.
Say it like this in the interview
“orders.customer_id contains a NULL, so NOT IN yields UNKNOWN for everyone. Use NOT EXISTS or filter NULLs in the subquery.”
A CTE is a named temporary result you can use in the rest of the query, making long queries readable. A recursive CTE can walk tree structures like categories or org charts.
Say it like this in the interview
“WITH name AS (...) defines a reusable subquery for readability. Recursive CTEs have an anchor and a recursive part, used for hierarchies like category trees, comment threads or manager chains.”
Find the top salary, then find the biggest salary below it. The window-function version ranks all salaries so you can ask for any position.
-- works when there might be duplicates or no second value
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
-- Nth highest with a window function
SELECT DISTINCT salary FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees
) ranked WHERE rnk = 2;
Say it like this in the interview
“MAX of salaries below the max, which handles duplicates and returns NULL if none exists. For the Nth highest I use DENSE_RANK. LIMIT 1 OFFSET 1 fails with duplicate top salaries unless I add DISTINCT.”
Group by email and keep groups bigger than one. To delete, join the table with itself and remove every row that has a twin with a smaller id.
SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1;
-- MySQL
DELETE u1 FROM users u1
JOIN users u2 ON u1.email = u2.email AND u1.id > u2.id;
-- then prevent it happening again
ALTER TABLE users ADD UNIQUE (email);
Say it like this in the interview
“GROUP BY with HAVING COUNT > 1 to find them, a self-join delete to keep the lowest id, and a unique constraint to stop it recurring. I’d back up and run the SELECT version first.”
Rank employees within each department by salary, then keep rank 1. Window functions make this clean.
SELECT department_id, name, salary
FROM (
SELECT e.*, DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk
FROM employees e
) ranked
WHERE rnk = 1;
Say it like this in the interview
“ROW_NUMBER() or DENSE_RANK() partitioned by department, ordered by salary descending, filtered to rank 1. DENSE_RANK keeps ties.”
Join the employees table to itself: one copy for the employee, one for the manager.
SELECT e.name AS employee, e.salary, m.name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;
Say it like this in the interview
“A self-join on e.manager_id = m.id, filtering e.salary > m.salary.”
Give each login day a row number per user. For consecutive days, date minus row number stays the same, so you can group by that.
WITH days AS (
SELECT DISTINCT user_id, DATE(logged_in_at) AS day FROM logins
), grouped AS (
SELECT user_id, day,
day - INTERVAL ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) DAY AS grp
FROM days
)
SELECT DISTINCT user_id FROM grouped
GROUP BY user_id, grp
HAVING COUNT(*) >= 3;
Say it like this in the interview
“The gaps-and-islands trick: subtract ROW_NUMBER() from the date to form a group key for consecutive runs, then GROUP BY user and that key with HAVING COUNT(*) >= 3.”
An index is the index at the back of a book: instead of reading every page to find “caching”, you jump straight to page 214. But every index must be updated on every insert and update, and it takes space. More indexes = slower writes.
Say it like this in the interview
“A B-tree index lets the database find rows in O(log n) instead of a full scan. I index columns used in WHERE, JOIN and ORDER BY, and composite indexes in the order of the query (leftmost prefix rule). Too many indexes slow writes and use memory. I verify with EXPLAIN.”
They will probably ask next
“Why isn’t my index used?” Functions on the column (WHERE YEAR(created_at) = 2026), leading wildcards (LIKE '%abc'), type mismatches, or low selectivity.
Ask the database how it’s running the query (EXPLAIN), and look for full table scans on big tables.
Say it like this in the interview
“Find it in the slow query log, run EXPLAIN ANALYZE, look for full scans, filesort and temporary tables, and rows examined vs returned. Common fixes: add or adjust a composite index, rewrite non-sargable conditions, avoid SELECT *, replace OFFSET pagination with keyset pagination, update statistics. Also check for lock waits, since the query might be blocked rather than slow.”
A composite index is like a phone book sorted by surname, then first name. You can look up by surname, or surname plus first name, but not by first name alone.
Say it like this in the interview
“The leftmost prefix rule: it helps WHERE country = ?, country = ? AND city = ?, and those plus a range or ORDER BY on created_at. It can’t efficiently serve WHERE city = ? alone. Equality columns first, range columns last.”
EXPLAIN shows the database’s plan: which tables it reads, in what order, using which indexes, and how many rows it expects to look at.
Say it like this in the interview
“I look at access type (ALL means full scan in MySQL, Seq Scan in Postgres), the key used, rows examined versus returned, Using filesort or Using temporary, and join order. EXPLAIN ANALYZE shows actual timing. Big differences between estimated and actual rows suggest stale statistics.”
OFFSET makes the database read and throw away 200,000 rows before giving you 20.
Say it like this in the interview
“The database still scans the skipped rows. Keyset pagination uses the last seen value with an index: WHERE id < :last_id ORDER BY id DESC LIMIT 20. It’s constant time but doesn’t allow jumping to arbitrary pages.”
A transaction is “all or nothing”. Transferring money = take from A and give to B. If the server crashes in the middle, neither should happen.
Atomic (all or nothing), Consistent (rules always hold), Isolated (parallel transactions don’t see each other’s half-done work), Durable (once committed, it survives a crash).
START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1 AND balance >= 100;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT; -- or ROLLBACK on error
Say it like this in the interview
“A transaction groups statements into one atomic unit with ACID guarantees. Isolation levels trade consistency for concurrency; for things like inventory I use SELECT … FOR UPDATE or atomic conditional updates to prevent race conditions.”
Isolation levels control how much transactions running at the same time can see of each other’s unfinished work. Stricter = safer but slower.
Say it like this in the interview
“Read Uncommitted allows dirty reads; Read Committed prevents dirty reads (Postgres default); Repeatable Read prevents non-repeatable reads (MySQL InnoDB default, which also prevents most phantoms with gap locks); Serializable behaves as if transactions ran one at a time. Anomalies: dirty read, non-repeatable read, phantom read, lost update.”
Two transactions each locked a row the other needs, and both wait. The database kills one so the other can continue.
Say it like this in the interview
“Two transactions acquired locks in opposite order. Fixes: access rows in a consistent order, keep transactions short, index the columns used in WHERE so fewer rows get locked, and retry the failed transaction, since deadlocks can’t be fully eliminated under concurrency.”
If both read “1 in stock” and both subtract, you sell 2. The check and the update must happen as one atomic step.
Say it like this in the interview
“An atomic conditional update: UPDATE products SET stock = stock - 1 WHERE id = ? AND stock > 0, then check affected rows; zero means sold out. Alternatively SELECT … FOR UPDATE inside a transaction to lock the row. Optimistic locking with a version column also works.”
Normalisation = store each fact once. Don’t write the customer’s address on every order; store it in the customers table and reference it. Denormalising = deliberately copying data to make reads faster, accepting the cost of keeping copies in sync.
Say it like this in the interview
“Normalisation removes redundancy so updates happen in one place, typically up to third normal form. I denormalise for read-heavy paths, like storing an order total or a comment count, when joins become a bottleneck, and keep it consistent with transactions or triggers.”
Relational (SQL) is the safe default for structured data with relationships and transactions (users, orders, payments). Document databases fit flexible, nested data read as a whole. Key-value stores fit caching and sessions.
Say it like this in the interview
“I default to a relational database like PostgreSQL for strong consistency, joins and transactions. I’d choose a document store when data is naturally hierarchical and read whole, with a flexible schema; key-value like Redis for caching; and specialised stores for search or time series. Scale alone isn’t a reason, since Postgres handles a lot.”
For flexible extra details that vary per row and that you rarely filter on, like product attributes or settings. Not for things you join or filter on all the time.
Say it like this in the interview
“For semi-structured data with varying shape, read mostly as a whole: settings, API payloads, varied product attributes. Postgres jsonb supports indexing (GIN) for some queries. Anything with relationships, constraints or frequent filtering belongs in real columns.”
“DELETE removes rows, can have WHERE, is logged row by row and fires triggers; TRUNCATE removes all rows fast, resets auto-increment, and is DDL in MySQL; DROP removes the table itself.”
A view is a saved query that looks like a table. A stored procedure is a saved program inside the database. A trigger runs automatically when rows change.
Say it like this in the interview
“Views simplify and secure access to complex queries. Procedures move logic into the database, which is fast but harder to version and test. Triggers enforce invariants or audit logs but create hidden side effects. I keep most business logic in the application and use these selectively.”
With read replicas, writes go to the main database and are copied to replicas a moment later. If you write and immediately read from a replica, your new data might not be there yet.
Say it like this in the interview
“Asynchronous replicas trail the primary. A user updates their profile, the next page reads from a replica and shows old data. Fixes: read-your-writes by routing that user’s reads to the primary for a short window, or reading critical data from the primary.”