Chapter Three
SQL to Interview Level
Free to readPages 54 to 75 of 244, by Durgesh Yadav
Here is a query that a competent analyst wrote, that runs without error, that returns a plausible number, and that is wrong by forty-five per cent. It is the single most common serious defect in analytical SQL, it survives code review regularly, and by the end of section 3.6 you will be able to spot it in about four seconds.
SELECT SUM(o.order_total) AS revenue
FROM orders o
JOIN order_items i ON i.order_id = o.order_id
WHERE o.status = 'DELIVERED';The real answer for our dataset is 30,390. That query returns 44,036. Nothing about it looks suspicious, which is exactly the problem.
SQL is the highest-return skill in this book. Not because it is the most sophisticated, but because it is the one you will use every single day, in every job, at every level, and because the level of SQL that gets you hired sits well past the level where most tutorials stop. Interviewers know this. A data engineering loop will nearly always contain a live SQL round, and the questions in it are chosen precisely because they separate people who can write a query from people who understand what the engine does with it.
This chapter is long. Work through it with a database open.
3.1The dataset
Everything in this chapter runs against six small ShopKart tables. Every query printed here was executed against this data before it went into the book, and every result shown is the actual output.
You can create it in PostgreSQL, DuckDB or SQLite. DuckDB is the easiest option for learning: pip install duckdb, then duckdb.connect(), with no server to run.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
full_name VARCHAR,
city VARCHAR,
signup_date DATE,
tier VARCHAR -- nullable, and that matters later
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER,
order_ts TIMESTAMP,
status VARCHAR, -- DELIVERED, CANCELLED, RETURNED
order_total DECIMAL(10,2)
);
CREATE TABLE order_items (
order_item_id INTEGER PRIMARY KEY,
order_id INTEGER,
product_id INTEGER,
quantity INTEGER,
line_amount DECIMAL(10,2)
);
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
product_name VARCHAR,
category VARCHAR,
unit_price DECIMAL(10,2)
);
CREATE TABLE payments (
payment_id INTEGER PRIMARY KEY,
order_id INTEGER,
paid_ts TIMESTAMP,
method VARCHAR,
amount DECIMAL(10,2)
);
CREATE TABLE app_events (
event_id INTEGER PRIMARY KEY,
customer_id INTEGER,
event_ts TIMESTAMP,
event_name VARCHAR
);Six customers, fourteen orders across February and March 2026, seventeen order lines, thirteen payments. The full seed data is in the companion Field Kit. Three deliberate imperfections are built in, because clean data teaches nothing: one customer has a NULL tier, one order was paid twice, and two orders have no payment at all.


3.2Five queries to get your hands moving
Before the hard parts, five simple ones. Type each, run it, and check that your output matches. If you have written SQL before this takes four minutes and confirms your setup works.
-- 1. Pick columns, filter rows.
SELECT full_name, city
FROM customers
WHERE city = 'Pune'; full_name | city
--------------+------
Priya Sharma | Pune
Aisha Khan | Pune-- 2. Compare a number, and sort the result.
SELECT order_id, order_total
FROM orders
WHERE order_total > 4000
ORDER BY order_total DESC; order_id | order_total
----------+-------------
9009 | 5099.00
9001 | 4749.00
9004 | 4200.00-- 3. Count everything.
SELECT COUNT(*) AS total_orders FROM orders; total_orders
--------------
14-- 4. Count within groups.
SELECT status, COUNT(*) AS orders
FROM orders
GROUP BY status
ORDER BY orders DESC; status | orders
-----------+--------
DELIVERED | 12
CANCELLED | 1
RETURNED | 1-- 5. Pull a name from another table, and take the top three.
SELECT c.full_name, o.order_id, o.order_total
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.status = 'DELIVERED'
ORDER BY o.order_total DESC
LIMIT 3; full_name | order_id | order_total
--------------+----------+-------------
Arjun Das | 9009 | 5099.00
Priya Sharma | 9001 | 4749.00
Aisha Khan | 9004 | 4200.00Query 5 already has the shape of nearly everything in this chapter: take rows from one table, attach matching rows from another, filter, sort, limit. The rest is variations on it, and the traps that hide inside those variations.
3.3How a SELECT actually runs
Almost every confusing thing about SQL becomes obvious once you know this, and most people are never taught it.
You write a query in one order. SQL defines its meaning in a different order. This is called the logical processing order, and it is what determines what a query means — not the sequence of operations the engine physically performs.

Three practical consequences fall straight out of that picture.
WHERE filters rows, HAVING filters groups. WHERE runs before grouping, so it cannot see an aggregate. HAVING runs after, so it can. The rule everyone repeats — use WHERE for rows and HAVING for aggregates — is not a convention, it is a description of the order above.
You cannot use a SELECT alias in WHERE. By the time WHERE runs, the alias does not exist yet, because SELECT has not happened. You can normally use it in ORDER BY, because that runs afterwards. This is why the same alias works in one clause and errors in another, which looks arbitrary until you have this diagram in your head.
WHERE is usually cheaper than HAVING. Filtering before grouping means fewer rows to group. A modern optimiser will often push a HAVING predicate down when it can prove the rewrite is safe, so the difference may vanish in the plan — but writing it in WHERE states your intent clearly and does not depend on the optimiser noticing.
-- Correct: status filters rows, so it belongs in WHERE.
-- The revenue threshold is an aggregate, so it belongs in HAVING.
SELECT c.city,
SUM(o.order_total) AS revenue
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.status = 'DELIVERED'
GROUP BY c.city
HAVING SUM(o.order_total) > 5000
ORDER BY revenue DESC;3.4NULL, and the trap that eats interview candidates
NULL does not mean zero and it does not mean empty string. It means unknown. Once you accept that, SQL’s behaviour stops being strange.
Because NULL is unknown, any comparison with it produces neither true nor false but a third value, also unknown. NULL = NULL is not true. NULL <> 'gold' is not true. Filters keep only rows that are definitely true, so unknown rows are silently dropped.
SELECT tier,
COUNT(*) AS rows_in_group,
COUNT(tier) AS non_null_tiers
FROM customers
GROUP BY tier
ORDER BY tier; tier | rows_in_group | non_null_tiers
---------+---------------+----------------
bronze | 1 | 1
gold | 2 | 2
silver | 2 | 2
NULL | 1 | 0COUNT(*) counts rows. COUNT(column) counts rows where that column is not null. That difference is a favourite one-line interview question, and the row where they diverge is the one that matters.
Now the trap. It has cost more candidates an offer than any other single behaviour in SQL.
-- Find customers whose tier is not used by anyone in Pune or Kochi.
SELECT customer_id, full_name, tier
FROM customers
WHERE tier NOT IN (
SELECT tier FROM customers WHERE city IN ('Pune', 'Kochi')
); customer_id | full_name | tier
-------------+-----------+------
(0 rows)Zero rows. Not an error, not a warning. The subquery returns gold, gold, and one NULL, because Meera Nair in Kochi has no tier. NOT IN expands into a chain of inequality comparisons, one of which is tier <> NULL, which is unknown, so the whole condition can never be definitely true for any row.
The fix is NOT EXISTS, which is safe with nulls because it asks a different question — does a matching row exist — rather than comparing values:
SELECT c.customer_id, c.full_name, c.tier
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM customers p
WHERE p.city IN ('Pune', 'Kochi')
AND p.tier = c.tier
); customer_id | full_name | tier
-------------+--------------+--------
102 | Rahul Verma | silver
104 | Vikram Rao | silver
105 | Meera Nair | NULL
106 | Arjun Das | bronze3.5Aggregation, and the word that matters most
Grain is what one row of a result means. It is the most important idea in this chapter, in Chapter 5, and arguably in the book.
Before writing an aggregate query, finish this sentence out loud: one row of my output is one ____ per ____. One row is one city per month. One row is one customer per product category. If you cannot finish the sentence, the query is not ready to be written, and any number it produces is a coincidence.
GROUP BY sets the grain. Everything in SELECT must then either appear in GROUP BY or be wrapped in an aggregate, because anything else has no single value at that grain — the database is not being pedantic, it does not know which of the five available values you meant.
-- Grain: one row per city per order status.
SELECT c.city, o.status,
COUNT(*) AS orders,
COUNT(DISTINCT o.customer_id) AS customers,
SUM(o.order_total) AS revenue,
ROUND(AVG(o.order_total), 2) AS avg_order_value
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
GROUP BY c.city, o.status
ORDER BY c.city, revenue DESC;Note COUNT(DISTINCT ...). Counting rows and counting distinct entities are different questions, and mixing them up is how “we have 41,000 customers” becomes a number nobody can reproduce.
3.6Joins, and the bug from the first page
Most people are taught joins as “combining two tables”. That framing is where the trouble starts. A better one:
That single sentence — if it matches three, it appears three times — is the whole explanation for the wrong query at the start of the chapter.
| Join type | Keeps unmatched left rows | Keeps unmatched right rows |
|---|---|---|
INNER JOIN | No | No |
LEFT JOIN | Yes | No |
RIGHT JOIN | No | Yes |
FULL OUTER JOIN | Yes | Yes |
CROSS JOIN | Every left row paired with every right row |
The fan-out
Order 9001 has two order lines. Order 9006 has two. When we join orders to order_items, those orders appear twice in the result, and their order_total is therefore counted twice.
-- WRONG. order_total is at order grain, the join is at line grain.
SELECT SUM(o.order_total) AS revenue
FROM orders o
JOIN order_items i ON i.order_id = o.order_id
WHERE o.status = 'DELIVERED';
-- revenue = 44036.00
-- RIGHT, option 1: stay at order grain — do not join at all.
SELECT SUM(o.order_total) AS revenue
FROM orders o
WHERE o.status = 'DELIVERED';
-- revenue = 30390.00
-- RIGHT, option 2: work at line grain and sum a line-grain column.
SELECT SUM(i.line_amount) AS revenue
FROM orders o
JOIN order_items i ON i.order_id = o.order_id
WHERE o.status = 'DELIVERED';
-- revenue = 30390.00A 44.9% overstatement, from a query with no syntax error and no obvious flaw. The rule that prevents it forever:
The safest general pattern is to aggregate before joining:
SELECT c.city,
SUM(o.order_total) AS order_revenue,
SUM(li.items) AS items_sold
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
LEFT JOIN (
SELECT order_id, SUM(quantity) AS items
FROM order_items
GROUP BY order_id -- collapsed to one row per order
) li ON li.order_id = o.order_id
WHERE o.status = 'DELIVERED'
GROUP BY c.city;LEFT JOIN, and where the filter goes
A LEFT JOIN keeps every left row. Putting a condition on the right table in WHERE silently destroys that, because WHERE runs after the join and a null right-hand row fails the test.
-- Keeps Kochi, which has no delivered orders. Condition is in ON.
SELECT c.city,
COUNT(DISTINCT c.customer_id) AS customers,
COUNT(o.order_id) AS orders,
COALESCE(SUM(o.order_total), 0) AS revenue
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.customer_id
AND o.status = 'DELIVERED'
GROUP BY c.city
ORDER BY revenue DESC; city | customers | orders | revenue
-----------+-----------+--------+----------
Pune | 2 | 4 | 13698.00
Bengaluru | 2 | 7 | 12894.00
Hyderabad | 1 | 1 | 3798.00
Kochi | 1 | 0 | 0.00Move AND o.status = 'DELIVERED' into a WHERE clause and Kochi disappears, turning your left join into an inner join without telling you. In a LEFT JOIN, conditions on the right table belong in ON; conditions on the left table belong in WHERE.
Also note COUNT(o.order_id) rather than COUNT(*). For Kochi, the left join produces one row with nulls on the right; COUNT(*) would report 1 order where there are none.
3.7CTEs
A common table expression names a result so the rest of the query can use it. It does not usually make a query faster; it makes it readable, which is what lets you find bugs like the fan-out.
WITH delivered AS (
SELECT * FROM orders WHERE status = 'DELIVERED'
),
per_customer AS (
SELECT customer_id,
COUNT(*) AS orders,
SUM(order_total) AS revenue
FROM delivered
GROUP BY customer_id
)
SELECT c.full_name, c.city, p.orders, p.revenue
FROM per_customer p
JOIN customers c ON c.customer_id = p.customer_id
ORDER BY p.revenue DESC;Write in stages, and check each stage. In an interview, a query built from three named CTEs that you can explain beats a single clever nested statement that you cannot, every time.
3.8Window functions
This is the section that separates intermediate SQL from interview SQL.
An aggregate collapses many rows into one. A window function computes across a set of rows and returns a value for every row, without collapsing anything. That one difference unlocks running totals, rankings, comparisons with the previous row, and most of the patterns in section 3.8.
The syntax has three parts inside OVER:
function() OVER (
PARTITION BY <restart the calculation for each of these>
ORDER BY <the order rows are considered in>
<frame> <which rows around the current one to include>
)PARTITION BY is like GROUP BY except nothing collapses. ORDER BY inside OVER is not about output order, it is about the sequence used for the calculation. The frame decides how much of the partition is visible from the current row.
The ranking family
SELECT o.order_id, c.full_name, o.order_total,
RANK() OVER (ORDER BY o.order_total DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY o.order_total DESC) AS dense_rnk,
ROW_NUMBER() OVER (ORDER BY o.order_total DESC) AS row_num
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.status = 'DELIVERED'
ORDER BY o.order_total DESC; order_id | full_name | order_total | rnk | dense_rnk | row_num
----------+--------------+-------------+-----+-----------+---------
9009 | Arjun Das | 5099.00 | 1 | 1 | 1
9001 | Priya Sharma | 4749.00 | 2 | 2 | 2
9004 | Aisha Khan | 4200.00 | 3 | 3 | 3
9006 | Vikram Rao | 3798.00 | 4 | 4 | 4
9000 | Priya Sharma | 3499.00 | 5 | 5 | 5
9010 | Rahul Verma | 3499.00 | 5 | 5 | 6
9007 | Priya Sharma | 1250.00 | 7 | 6 | 7Look only at the two tied rows and the one after them. RANK gives both ties 5 and then jumps to 7. DENSE_RANK gives both 5 and continues at 6. ROW_NUMBER refuses to acknowledge the tie at all and assigns 5 and 6 arbitrarily.
That last point matters more than it looks. ROW_NUMBER over a non-unique ordering is non-deterministic — run it twice and you may get a different winner. If you are using it to deduplicate, add a tiebreaker to the ORDER BY so the result is reproducible.
| Use | Function |
|---|---|
| Pick exactly one row per group | ROW_NUMBER, with a deterministic tiebreaker |
| Top N including ties, with gaps after | RANK |
| Top N including ties, without gaps | DENSE_RANK |
Frames
The frame clause decides which rows the function can see. Two forms cover almost everything:
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW— everything from the start of the partition up to here. This is a running total.ROWS BETWEEN 6 PRECEDING AND CURRENT ROW— a sliding window of seven rows.
There is one distinction worth knowing because it appears in senior interviews. ROWS counts physical rows; RANGE counts by value. For a rolling seven-day average over data with missing days, ROWS BETWEEN 6 PRECEDING gives you the previous six rows, which may span three weeks. RANGE BETWEEN INTERVAL '6 days' PRECEDING gives you the previous six days, which is almost always what was actually asked for.
3.9The patterns interviewers actually ask
Eight problems. These recur across companies because each one tests a distinct idea. Every solution below was run against the dataset in section 3.1 and the outputs are real.
Pattern 1 — Deduplication
Problem. The payments table has a duplicate: order 9001 was recorded twice, forty seconds apart. Keep the earliest payment per order.
WITH ranked AS (
SELECT p.*,
ROW_NUMBER() OVER (
PARTITION BY p.order_id
ORDER BY p.paid_ts, p.payment_id -- deterministic tiebreak
) AS rn
FROM payments p
)
SELECT payment_id, order_id, paid_ts, amount
FROM ranked
WHERE rn = 1
ORDER BY order_id;Thirteen payment rows become twelve; payment_id 5009 is dropped. Follow-up an interviewer will ask: what if you want to keep the row with the largest amount instead? Change the ORDER BY inside OVER to amount DESC. The pattern does not change, only the definition of “best”. Second follow-up: why not SELECT DISTINCT? Because the rows are not identical — they have different payment_id and paid_ts values — so DISTINCT keeps both. Deduplication almost always means “one row per key”, not “remove identical rows”.
Pattern 2 — Top N per group
Problem. The two highest-revenue products in each category.
WITH product_rev AS (
SELECT pr.category, pr.product_name,
SUM(i.line_amount) AS revenue
FROM order_items i
JOIN products pr ON pr.product_id = i.product_id
JOIN orders o ON o.order_id = i.order_id
WHERE o.status = 'DELIVERED'
GROUP BY pr.category, pr.product_name
),
ranked AS (
SELECT *,
DENSE_RANK() OVER (PARTITION BY category
ORDER BY revenue DESC) AS rnk
FROM product_rev
)
SELECT category, product_name, revenue
FROM ranked
WHERE rnk <= 2
ORDER BY category, revenue DESC; category | product_name | revenue
----------+----------------+----------
Fitness | Yoga Mat | 5000.00
Fitness | Water Bottle | 1798.00
Footwear | Running Shoes | 13996.00
Footwear | Cotton Socks | 1196.00
Outdoor | Trail Backpack | 8400.00The window function cannot go in WHERE, because WHERE runs before SELECT. That is why the ranking needs its own CTE. Snowflake, Databricks and DuckDB offer QUALIFY as a shortcut for exactly this; PostgreSQL does not, so the CTE form is the portable answer and the one to give unless you are asked about a specific engine.
Pattern 3 — Running total
SELECT CAST(order_ts AS DATE) AS order_date,
SUM(order_total) AS daily_revenue,
SUM(SUM(order_total)) OVER (ORDER BY CAST(order_ts AS DATE))
AS running_total
FROM orders
WHERE status = 'DELIVERED'
GROUP BY 1
ORDER BY 1; order_date | daily_revenue | running_total
------------+---------------+---------------
2026-02-25 | 3499.00 | 3499.00
2026-03-01 | 5999.00 | 9498.00
2026-03-04 | 4200.00 | 13698.00
2026-03-07 | 598.00 | 14296.00
2026-03-09 | 3798.00 | 18094.00
... | |
2026-03-22 | 299.00 | 30390.00SUM(SUM(...)) OVER (...) looks wrong and is correct. The inner SUM aggregates to daily grain; the window function then runs over those already-aggregated rows, because window functions are evaluated after GROUP BY. This exact construction is a common interview question, precisely because it forces you to know the evaluation order from section 3.3.
Pattern 4 — Rolling seven-day average
WITH daily AS (
SELECT CAST(order_ts AS DATE) AS order_date,
SUM(order_total) AS revenue
FROM orders
WHERE status = 'DELIVERED'
GROUP BY 1
)
SELECT order_date, revenue,
ROUND(AVG(revenue) OVER (
ORDER BY order_date
RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW
), 0) AS avg_7d
FROM daily
ORDER BY order_date; order_date | revenue | avg_7d
------------+---------+--------
2026-02-25 | 3499.00 | 3499
2026-03-01 | 5999.00 | 4749
2026-03-04 | 4200.00 | 5100
2026-03-07 | 598.00 | 3599
2026-03-09 | 3798.00 | 2865
2026-03-12 | 1250.00 | 1882RANGE is deliberate. Our data has gaps — no orders on many days — so ROWS BETWEEN 6 PRECEDING would average the last six rows, reaching back nearly a month. Follow-up: what if the business wants missing days counted as zero? Then generate a complete date series and left join the daily totals onto it, because a window function cannot invent rows that are not there.
Pattern 5 — Month-over-month change
WITH monthly AS (
SELECT DATE_TRUNC('month', order_ts) AS mth,
SUM(order_total) AS revenue
FROM orders
WHERE status = 'DELIVERED'
GROUP BY 1
)
SELECT CAST(mth AS DATE) AS month, revenue,
LAG(revenue) OVER (ORDER BY mth) AS prev_month,
ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY mth))
/ LAG(revenue) OVER (ORDER BY mth), 1) AS pct_change
FROM monthly
ORDER BY mth; month | revenue | prev_month | pct_change
------------+----------+------------+------------
2026-02-01 | 3499.00 | NULL | NULL
2026-03-01 | 26891.00 | 3499.00 | 668.5The first row is NULL because there is no previous month, which is correct and should be left alone rather than papered over with a zero. Follow-up: what breaks if a month has no orders at all? LAG returns the previous row, not the previous month, so a gap silently compares March to January while labelling it month-over-month. The fix is again a generated date spine.
Pattern 6 — Gaps and islands
Problem. Find runs of consecutive days on which a customer ordered.
WITH active AS (
SELECT DISTINCT customer_id, CAST(order_ts AS DATE) AS d
FROM orders
WHERE status = 'DELIVERED'
),
grouped AS (
SELECT customer_id, d,
d - CAST(ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY d)
AS INTEGER) AS island
FROM active
)
SELECT customer_id,
MIN(d) AS streak_start,
MAX(d) AS streak_end,
COUNT(*) AS streak_days
FROM grouped
GROUP BY customer_id, island
HAVING COUNT(*) >= 2
ORDER BY streak_days DESC; customer_id | streak_start | streak_end | streak_days
-------------+--------------+------------+-------------
102 | 2026-03-18 | 2026-03-20 | 3The trick is worth understanding rather than memorising. Consecutive dates increase by one each row, and ROW_NUMBER also increases by one each row. Subtract one from the other and every date in a consecutive run produces the same constant; the moment a day is skipped, the constant changes. Grouping by that constant groups by run. Once you have seen it, you have it for life, and it appears in interviews as streaks, consecutive logins, uninterrupted subscription periods and downtime windows.
Pattern 7 — Sessionization
Problem. Group app events into sessions, where a gap of more than thirty minutes starts a new one.
WITH with_prev AS (
SELECT customer_id, event_ts, event_name,
LAG(event_ts) OVER (PARTITION BY customer_id
ORDER BY event_ts) AS prev_ts
FROM app_events
),
marked AS (
SELECT *,
CASE WHEN prev_ts IS NULL
OR event_ts > prev_ts + INTERVAL '30 minutes'
THEN 1 ELSE 0 END AS is_new_session
FROM with_prev
),
sessions AS (
SELECT *,
SUM(is_new_session) OVER (
PARTITION BY customer_id ORDER BY event_ts
) AS session_no
FROM marked
)
SELECT customer_id, session_no,
MIN(event_ts) AS started,
MAX(event_ts) AS ended,
COUNT(*) AS events
FROM sessions
GROUP BY customer_id, session_no
ORDER BY customer_id, session_no; customer_id | session_no | started | ended | events
-------------+------------+---------------------+---------------------+--------
101 | 1 | 2026-03-01 10:02:00 | 2026-03-01 10:12:00 | 4
101 | 2 | 2026-03-01 13:40:00 | 2026-03-01 13:44:00 | 2
102 | 1 | 2026-03-01 18:30:00 | 2026-03-01 18:44:00 | 2Three ideas stacked: LAG to see the previous event, a CASE to flag boundaries, and a running SUM of that flag to number the sessions. The running sum turning a series of flags into group identifiers is the same manoeuvre as the islands trick, and once you notice they are the same idea you will start seeing it everywhere.
Pattern 8 — Anti-join
Problem. Which orders have no payment?
SELECT o.order_id, o.status, o.order_total
FROM orders o
LEFT JOIN payments p ON p.order_id = o.order_id
WHERE p.order_id IS NULL
ORDER BY o.order_id; order_id | status | order_total
----------+-----------+-------------
9003 | CANCELLED | 3499.00
9008 | RETURNED | 899.00Both are explainable — a cancelled order and a returned one — which is what makes this a good reconciliation check rather than an alarm. NOT EXISTS is the other correct form and is often clearer. NOT IN is the third form and the one to avoid, for the reason in section 3.4.
3.10Making a query fast
Correctness first, always. But an interviewer will ask why a query is slow, and there are four answers that cover most cases.
It is reading more than it needs. SELECT * on a wide table in a columnar warehouse reads every column. Name the columns you want. In a warehouse this is not a style preference, it is most of the bill.
The filter cannot use the index. A predicate that wraps a column in a function usually forces a full scan. Write order_ts >= DATE '2026-03-01' AND order_ts < DATE '2026-04-01' rather than WHERE YEAR(order_ts) = 2026 AND MONTH(order_ts) = 3. The two are logically identical and only one can use an index on order_ts. A predicate the index can use is called sargable, and the word occasionally appears in interviews.
It is joining more rows than necessary. Filter and aggregate before joining, not after. The fan-out pattern from section 3.6 is a correctness bug and a performance bug at once.
The plan is not what you assumed. Run EXPLAIN — or EXPLAIN ANALYZE, which executes the query and reports actual timings — and read what the engine actually chose. The two things to look for first are a sequential scan where you expected an index, and an estimated row count that is wildly different from the actual one, which usually means statistics are stale.
3.11Mistakes to stop making now
Summary
- The engine evaluates
FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. Most beginner confusion dissolves once that order is memorised. NULLmeans unknown.NOT INagainst a nullable subquery returns nothing at all, silently. UseNOT EXISTS.- Grain is what one output row means. Say it out loud before writing the query.
- A join repeats a left row once per match. Never sum a column at a grain finer than the column’s own.
- On a
LEFT JOIN, right-table conditions go inON, left-table conditions go inWHERE. - Window functions compute per row without collapsing.
ROW_NUMBERfor one-per-group,RANKandDENSE_RANKfor top-N with ties handled differently. ROWScounts rows,RANGEcounts values. With gappy dates,RANGEis usually what was meant.- The islands trick and the sessionization trick are the same idea: turn boundary flags into group identifiers with a running sum.
The other 12 chapters are in the free PDF
This is one of 3 chapters you can read here. The whole book is 244 pages and 15 chapters, and it is free: downloading the PDF takes one Google sign-in.
Also free to read here: Chapter One, What a Data Engineer Actually Does and Chapter Six, Where Data Lives.