Cohort 4Register

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.

SQL
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.

SQL
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.

Figure 3.1: The ShopKart tables and how they connect. One customer has many orders; one order has many items and, in this data, occasionally more than one payment.Figure 3.1, continued
Figure 3.1.   The ShopKart tables and how they connect. One customer has many orders; one order has many items and, in this data, occasionally more than one payment. In the diagram: customers orders order_items orders payments products order_items

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.

SQL
-- 1. Pick columns, filter rows.
SELECT full_name, city
FROM customers
WHERE city = 'Pune';
Output
 full_name    | city
--------------+------
 Priya Sharma | Pune
 Aisha Khan   | Pune
SQL
-- 2. Compare a number, and sort the result.
SELECT order_id, order_total
FROM orders
WHERE order_total > 4000
ORDER BY order_total DESC;
Output
 order_id | order_total
----------+-------------
     9009 |     5099.00
     9001 |     4749.00
     9004 |     4200.00
SQL
-- 3. Count everything.
SELECT COUNT(*) AS total_orders FROM orders;
Output
 total_orders
--------------
           14
SQL
-- 4. Count within groups.
SELECT status, COUNT(*) AS orders
FROM orders
GROUP BY status
ORDER BY orders DESC;
Output
 status    | orders
-----------+--------
 DELIVERED |     12
 CANCELLED |      1
 RETURNED  |      1
SQL
-- 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;
Output
 full_name    | order_id | order_total
--------------+----------+-------------
 Arjun Das    |     9009 |     5099.00
 Priya Sharma |     9001 |     4749.00
 Aisha Khan   |     9004 |     4200.00

Query 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.

Figure 3.2: The logical processing order. It defines what the query means. The optimiser is free to execute in any order that produces the same answer.
Figure 3.2.   The logical processing order. It defines what the query means. The optimiser is free to execute in any order that produces the same answer. In the diagram: 1 FROM and JOIN assemble the rows to work with 2 WHERE throw away rows, before any grouping 3 GROUP BY collapse the survivors into groups 4 HAVING throw away whole groups 5 SELECT now compute the output columns 6 ORDER BY sort what is left 7 LIMIT take the top slice

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.

SQL
-- 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.

SQL
SELECT tier,
       COUNT(*)     AS rows_in_group,
       COUNT(tier)  AS non_null_tiers
FROM customers
GROUP BY tier
ORDER BY tier;
Output
 tier    | rows_in_group | non_null_tiers
---------+---------------+----------------
 bronze  |             1 |              1
 gold    |             2 |              2
 silver  |             2 |              2
 NULL    |             1 |              0

COUNT(*) 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.

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')
);
Output
 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:

SQL
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
);
Output
 customer_id | full_name    | tier
-------------+--------------+--------
         102 | Rahul Verma  | silver
         104 | Vikram Rao   | silver
         105 | Meera Nair   | NULL
         106 | Arjun Das    | bronze

3.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.

SQL
-- 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 typeKeeps unmatched left rowsKeeps unmatched right rows
INNER JOINNoNo
LEFT JOINYesNo
RIGHT JOINNoYes
FULL OUTER JOINYesYes
CROSS JOINEvery 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.

SQL
-- 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.00

A 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:

SQL
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.

SQL
-- 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;
Output
 city      | customers | orders | revenue
-----------+-----------+--------+----------
 Pune      |         2 |      4 | 13698.00
 Bengaluru |         2 |      7 | 12894.00
 Hyderabad |         1 |      1 |  3798.00
 Kochi     |         1 |      0 |     0.00

Move 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.

SQL
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:

SQL
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

SQL
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;
Output
 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 |       7

Look 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.

UseFunction
Pick exactly one row per groupROW_NUMBER, with a deterministic tiebreaker
Top N including ties, with gaps afterRANK
Top N including ties, without gapsDENSE_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.

SQL
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.

SQL
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;
Output
 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.00

The 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

SQL
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;
Output
 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.00

SUM(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

SQL
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;
Output
 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 |   1882

RANGE 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

SQL
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;
Output
 month      | revenue  | prev_month | pct_change
------------+----------+------------+------------
 2026-02-01 |  3499.00 |     NULL   |      NULL
 2026-03-01 | 26891.00 |    3499.00 |     668.5

The 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.

SQL
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;
Output
 customer_id | streak_start | streak_end | streak_days
-------------+--------------+------------+-------------
         102 | 2026-03-18   | 2026-03-20 |           3

The 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.

SQL
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;
Output
 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 |      2

Three 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?

SQL
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;
Output
 order_id | status    | order_total
----------+-----------+-------------
     9003 | CANCELLED |     3499.00
     9008 | RETURNED  |      899.00

Both 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.
  • NULL means unknown. NOT IN against a nullable subquery returns nothing at all, silently. Use NOT 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 in ON, left-table conditions go in WHERE.
  • Window functions compute per row without collapsing. ROW_NUMBER for one-per-group, RANK and DENSE_RANK for top-N with ties handled differently.
  • ROWS counts rows, RANGE counts values. With gappy dates, RANGE is 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.

See all 15 chapters

Also free to read here: Chapter One, What a Data Engineer Actually Does and Chapter Six, Where Data Lives.