SQL for Data Analysis Questions
Writing SQL to answer analytical and business questions. Covers filtering, joins, grouping and aggregation, subqueries, CTEs, and translating an ambiguous request into a correct query. Includes spreadsheet-to-SQL fluency for everyday analyst workflows.
Write a query to find users who placed at least 3 orders in the last 12 months and whose average order value is above a given amount. Given orders(order_id, user_id, amount_cents, created_at), return the qualifying user_ids.
Sample Answer
Direct answer
Filter orders to the last 12 months, group by user_id, and use HAVING to require both COUNT(*) >= 3 and an average-order-value threshold, computed as AVG(amount_cents) / 100.0 since the amount is stored in cents. Both conditions are aggregate conditions, so both belong in HAVING, joined with AND.
Approach
- Filter to the relevant window first (
WHERE created_atin the last 12 months), so only recent orders count toward frequency and AOV. - Group by
user_id. - In HAVING, require
COUNT(*) >= 3for frequency andAVG(amount_cents) / 100.0 > thresholdfor average order value, in the same clause since both are per-group aggregate conditions.
Worked example (sqlite3, verified)
Sample data (reference "now" pinned to 2024-04-01, so the last 12 months = [2023-04-01, 2024-04-01)):
CREATE TABLE orders (order_id INTEGER PRIMARY KEY, user_id INTEGER, amount_cents INTEGER, created_at TEXT);
INSERT INTO orders VALUES
(1, 1, 6000, '2024-01-05'),
(2, 1, 5500, '2024-02-10'),
(3, 1, 7000, '2024-03-01'), -- user 1: 3 orders, AOV ~= $61.67
(4, 2, 2000, '2024-01-15'),
(5, 2, 1500, '2024-02-20'),
(6, 2, 1000, '2024-03-05'), -- user 2: 3 orders, AOV = $15.00 (fails threshold)
(7, 3, 9000, '2024-01-01'),
(8, 3, 8000, '2024-02-01'), -- user 3: only 2 orders (fails count)
(9, 4, 12000, '2023-01-01'); -- user 4: outside the 12-month window
Query, at least 3 orders in the window and AOV above $50:
SELECT user_id, COUNT(*) AS order_count, AVG(amount_cents) / 100.0 AS aov_usd
FROM orders
WHERE created_at >= '2023-04-01' AND created_at < '2024-04-01'
GROUP BY user_id
HAVING COUNT(*) >= 3 AND AVG(amount_cents) / 100.0 > 50
ORDER BY user_id;
Result: exactly 1 row, (1, 3, 61.666666666666664).
Full per-user breakdown (no HAVING filter, to show why each other user was excluded):
SELECT user_id, COUNT(*) AS order_count, AVG(amount_cents) / 100.0 AS aov_usd
FROM orders
WHERE created_at >= '2023-04-01' AND created_at < '2024-04-01'
GROUP BY user_id
ORDER BY user_id;
Result: (1, 3, 61.67), (2, 3, 15.0), (3, 2, 85.0). User 2 has enough orders (3) but fails AOV ($15 < $50). User 3 clears AOV easily ($85) but only has 2 orders, failing the count threshold. User 4's single order predates the window entirely and never appears in either result.
Key points
- Both filter conditions on the group (order count, AOV) are aggregate conditions, so both must be in HAVING; there's no valid way to express either one in WHERE.
- Storing money in cents and dividing by 100.0 in the SELECT (not earlier) avoids integer-division truncation in engines where integer/integer division floors the result;
100.0forces floating-point division. - The date filter in WHERE happens before grouping, which is both correct (it must, since "last 12 months" is a per-row property, not a per-user aggregate) and efficient (fewer rows reach GROUP BY).
Complexity, edge cases & pitfalls
- An index on
(user_id, created_at)lets the engine narrow to each user's recent orders efficiently before aggregating; without it, this query does a full scan oforders. - If
amount_centscan be NULL for some rows,AVGsilently ignores those rows rather than erroring, which quietly changes both the order count used for HAVING's COUNT(*) (still counts the row) and the AOV (excludes it), a subtle mismatch worth guarding withWHERE amount_cents IS NOT NULLif NULL amounts are a data quality issue rather than a valid zero-dollar order. - The "last 12 months" boundary is a common off-by-one risk: this answer defines it as
[2023-04-01, 2024-04-01), a full rolling year ending the day before the reference date; using>=on the lower bound and strict<on the upper bound (rather than<=on a date that might include a partial day) avoids double-counting the boundary day. - Requiring
COUNT(*) >= 3in the same window as the AOV means a user just barely at 3 orders has their average pulled by exactly those 3 values, small samples can look extreme; that's expected here and worth flagging to a stakeholder if the tier is meant to reward high-value repeat customers rather than accidentally reward small-sample noise.
An orders table stores order_date in UTC, but you need to report 'orders placed on 2025-11-01' in each customer's local time. Given a users table with a timezone column, write a query that buckets orders correctly by each user's local date, and explain the pitfall of just applying one global UTC offset.
Sample Answer
Direct answer
Convert each order's UTC instant into the customer's own local wall-clock time using their IANA timezone name (the standard named-timezone database, e.g. America/New_York), then take the date part of that converted timestamp for bucketing. Applying one global UTC offset to every user is wrong for two separate reasons: different users need different offsets, and even a single user's offset changes across a DST (daylight saving time) transition, so any fixed number is only ever correct for part of your users for part of the year.
Structured elaboration
- IANA zone names vs fixed offsets:
AT TIME ZONE 'America/New_York'looks up the full DST rule set (the tzdb) for that region and applies whichever offset is correct for that specific timestamp. A fixed offset like-05:00has no rules, it is just always five hours, which is right for New York in winter (EST) and wrong in summer (EDT). - Steps: join
orderstousersonuser_id, convertorder_date(a UTC instant) into local time withorder_date AT TIME ZONE u.timezone, cast the result toDATE, filter and aggregate on that local date. - Two distinct offset traps, both present in the worked example below:
- One offset cannot fit users in different zones at all (Kolkata is UTC+5:30 with no DST; New York alternates between UTC-4 and UTC-5).
- Even for a single zone, the correct offset itself changes at the DST boundary, so a number that was right for New York in July is wrong in December.
- Dialect notes: Postgres and DuckDB (with the
icuextension loaded) both supporttimestamp AT TIME ZONE 'IANA/Name'directly, using the underlying tzdata. MySQL needs the timezone tables populated (mysql_tzinfo_to_sql) beforeCONVERT_TZ()recognizes IANA names; without that load it silently returnsNULLinstead of erroring. BigQuery usesDATETIME(timestamp_expr, tz_string). Snowflake usesCONVERT_TIMEZONE(tz, timestamp).
Worked example (executed, DuckDB 1.5 with the icu extension loaded, session TimeZone set to UTC)
Seed data: three users in three timezones, and five orders clustered right around the UTC midnight boundary for 2025-11-01 so the correct local date differs from the naive interpretation for most of them.
INSTALL icu; LOAD icu; SET TimeZone='UTC';
CREATE TABLE users (user_id INTEGER, tz_name VARCHAR);
INSERT INTO users VALUES
(1, 'America/New_York'),
(2, 'Asia/Kolkata'),
(3, 'Europe/London');
CREATE TABLE orders (order_id INTEGER, user_id INTEGER, order_date TIMESTAMPTZ, amount_usd DECIMAL(10,2));
INSERT INTO orders VALUES
(1, 1, TIMESTAMPTZ '2025-11-01 03:30:00 UTC', 100.00),
(2, 1, TIMESTAMPTZ '2025-11-01 12:00:00 UTC', 50.00),
(3, 2, TIMESTAMPTZ '2025-10-31 19:00:00 UTC', 75.00),
(4, 2, TIMESTAMPTZ '2025-11-01 20:00:00 UTC', 200.00),
(5, 3, TIMESTAMPTZ '2025-11-01 10:00:00 UTC', 30.00);
Correct query:
SELECT o.order_id, o.user_id, o.amount_usd,
CAST((o.order_date AT TIME ZONE u.tz_name) AS DATE) AS local_date
FROM orders o JOIN users u ON o.user_id = u.user_id
WHERE CAST((o.order_date AT TIME ZONE u.tz_name) AS DATE) = DATE '2025-11-01';
Per-order local conversion (the intermediate step, shown for every order):
| order_id | user_id | tz_name | order_date (UTC) | local_timestamp | local_date |
|---|---|---|---|---|---|
| 1 | 1 | America/New_York | 2025-11-01 03:30:00+00 | 2025-10-31 23:30:00 | 2025-10-31 |
| 2 | 1 | America/New_York | 2025-11-01 12:00:00+00 | 2025-11-01 08:00:00 | 2025-11-01 |
| 3 | 2 | Asia/Kolkata | 2025-10-31 19:00:00+00 | 2025-11-01 00:30:00 | 2025-11-01 |
| 4 | 2 | Asia/Kolkata | 2025-11-01 20:00:00+00 | 2025-11-02 01:30:00 | 2025-11-02 |
| 5 | 3 | Europe/London | 2025-11-01 10:00:00+00 | 2025-11-01 10:00:00 | 2025-11-01 |
Correct result for "orders placed on 2025-11-01" (3 orders, $155.00): order 2 (NY, local 08:00 Nov 1), order 3 (Kolkata, UTC Oct 31 19:00 is already local 00:30 Nov 1), order 5 (London, same day in both).
Now the pitfalls, run against the identical seed data:
-- Pitfall 1: bucket by the raw UTC date, ignore timezone entirely
SELECT COUNT(*) AS n_orders, SUM(amount_usd) AS revenue
FROM orders WHERE CAST(order_date AS DATE) = DATE '2025-11-01';
-- result: 4 orders, $380.00 (orders 1, 2, 4, 5)
-- Pitfall 2: apply ONE global fixed offset (UTC-5) to every user regardless of their actual zone
SELECT COUNT(*) AS n_orders, SUM(amount_usd) AS revenue
FROM orders WHERE CAST((order_date - INTERVAL 5 HOUR) AS DATE) = DATE '2025-11-01';
-- result: 3 orders, $280.00 (orders 2, 4, 5)
Correct: 3 orders, $155.00. Raw-UTC-date: 4 orders, $380.00 (wrongly includes order 1, which was really Oct 31 in New York, and wrongly includes order 4, which was really Nov 2 in Kolkata; wrongly excludes order 3). Global -5h offset: coincidentally also lands on 3 orders, but the WRONG 3: it wrongly excludes order 3 (Kolkata's true offset is +5:30, not -5) and wrongly includes order 4, while order 1 happens to still land on Oct 31 by coincidence. The row count matching the correct answer by accident is the most dangerous failure mode here: a count-only sanity check would not catch it, only the revenue total ($280 vs the correct $155) or a row-by-row diff would.
Trade-offs and pitfalls
- A
users.timezonethat isNULLor an invalid IANA string needs an explicit policy:LEFT JOINplusCOALESCE(u.timezone, 'UTC')with the fallback rows flagged in a separateis_timezone_assumedcolumn, rather than silently dropping those users or silently mis-bucketing them as UTC without a flag. - Per-row
AT TIME ZONEconversion is not sargable (an index can't be used to search on it, because the column is wrapped in a function) against a plain index onorder_date, so filtering a huge table to "around 2025-11-01" should first narrow with a cheap UTC range wide enough to cover every timezone's version of that local day (roughlyorder_date >= '2025-10-31' AND order_date < '2025-11-03'covers the full +14/-12 UTC offset range), then apply the exact per-user local-date predicate on that smaller set. - The global-offset pitfall is really two bugs wearing one trenchcoat: cross-user (one offset cannot serve users in different zones) and cross-time (one offset cannot serve one zone across a DST boundary). Fixing only one of them (e.g. hardcoding "New York is always -5" outside DST season) still leaves the other live and waiting for the next March or November boundary.
- IANA tzdb data itself is updated periodically (governments change DST rules with short notice); pin and update the engine's tzdata/ICU version deliberately rather than assuming it is frozen forever.
Walk me through the differences between INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN. Using two small tables (say customers and orders), show how the result set and row counts change for each join type, and call out what happens to unmatched rows on each side.
Sample Answer
Direct answer
INNER JOIN keeps only rows where the join key matches in both tables. LEFT JOIN keeps every row from the left table and fills unmatched right-side columns with NULL. RIGHT JOIN is the mirror image (every row from the right table, unmatched left-side columns are NULL). FULL OUTER JOIN keeps every row from both sides, with NULLs on whichever side didn't match.
Structured elaboration
| Join type | Rows kept | Unmatched left rows | Unmatched right rows |
|---|---|---|---|
| INNER JOIN | Only matching pairs | Dropped | Dropped |
| LEFT JOIN | All left rows | Kept (right columns NULL) | Dropped |
| RIGHT JOIN | All right rows | Dropped | Kept (left columns NULL) |
| FULL OUTER JOIN | All rows from both sides | Kept (right columns NULL) | Kept (left columns NULL) |
A useful mental model: start from LEFT JOIN (all of the left table, matched where possible), and each other join type is a variation of which side you insist on keeping in full.
Worked example (sqlite3, verified)
Sample data:
CREATE TABLE customers (customer_id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE orders (order_id INTEGER PRIMARY KEY, customer_id INTEGER, amount INTEGER);
INSERT INTO customers VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Carol');
INSERT INTO orders VALUES
(101, 1, 50),
(102, 1, 30),
(103, 2, 20),
(104, 9, 75); -- order for a customer_id that does not exist (orphan row)
Carol (customer_id 3) has never ordered. Order 104 belongs to customer_id 9, who doesn't exist in customers, an intentional reconciliation-style gap (an order with no matching customer, the mirror case of a customer with no orders).
INNER JOIN:
SELECT c.customer_id, c.name, o.order_id, o.amount
FROM customers c
INNER JOIN orders o ON c.customer_id = o.customer_id;
Result (3 rows): (1,'Alice',101,50), (1,'Alice',102,30), (2,'Bob',103,20). Carol and order 104 both vanish.
LEFT JOIN:
SELECT c.customer_id, c.name, o.order_id, o.amount
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id;
Result (4 rows): the 3 inner rows plus (3,'Carol',NULL,NULL). Carol appears once with NULL order columns; order 104 still doesn't appear (it lives on the right side).
RIGHT JOIN:
SELECT c.customer_id, c.name, o.order_id, o.amount
FROM customers c
RIGHT JOIN orders o ON c.customer_id = o.customer_id;
Result (4 rows): the 3 inner rows plus (NULL,NULL,104,75). Now order 104 survives with NULL customer columns; Carol drops out.
FULL OUTER JOIN:
SELECT c.customer_id, c.name, o.order_id, o.amount
FROM customers c
FULL OUTER JOIN orders o ON c.customer_id = o.customer_id;
Result (5 rows): the 3 inner rows, (3,'Carol',NULL,NULL), and (NULL,NULL,104,75). Both unmatched sides are preserved.
Business-reporting framing (reconciliation). This is exactly the shape of a reconciliation report: "which customers show up in our CRM but never billed" versus "which billing records reference a customer we don't recognize." A FULL OUTER JOIN filtered to only the unmatched rows surfaces both at once:
SELECT c.customer_id AS cust_id, o.customer_id AS order_cust_id, o.order_id
FROM customers c
FULL OUTER JOIN orders o ON c.customer_id = o.customer_id
WHERE c.customer_id IS NULL OR o.order_id IS NULL;
Result (2 rows): (NULL, 9, 104) (an order referencing a missing customer) and (3, NULL, NULL) (a customer with no orders). In finance/reconciliation terms these are the two classic break types: unmatched source records and unmatched target records.
Trade-offs & pitfalls
- MySQL has no
FULL OUTER JOINkeyword (and older MySQL/other engines also lackRIGHT JOINin some restricted dialects, though RIGHT JOIN is broadly supported). The portable emulation isLEFT JOIN ... UNION ... RIGHT JOIN ...filtered appropriately, orLEFT JOIN ... UNION ... (INNER JOIN swapped). This answer's queries were run and verified against SQLite 3.39+, which supports RIGHT JOIN and FULL OUTER JOIN natively. - RIGHT JOIN is rarely used in practice because you can always rewrite it as a LEFT JOIN by swapping the table order; most style guides prefer that for readability.
- A common mistake: putting a filter on the right table in the WHERE clause instead of the ON clause of a LEFT JOIN.
WHERE o.amount > 10after a LEFT JOIN silently turns it back into an INNER JOIN, because NULL rows fail that comparison. The filter belongs in the ON clause if you want to keep unmatched rows:LEFT JOIN orders o ON c.customer_id = o.customer_id AND o.amount > 10. - If the join key isn't unique on one side, a "safe" LEFT JOIN can still fan out rows (one customer row duplicated once per matching order), which quietly breaks downstream counts and sums if you forget to aggregate first.
You're handed a long, deeply nested SQL query full of duplicated subquery expressions that a teammate says is 'impossible to review.' Refactor it into a readable series of CTEs and explain how you decided where to break it up.
Sample Answer
Direct answer
Refactor by first finding every place the same subquery expression is computed more than once and giving that expression a single name as a CTE, then breaking the rest of the query at its natural pipeline stages: filter, per-key aggregate, derived metric. The goal is that each CTE answers one question a reviewer can check independently, and any business rule (like "what counts as completed revenue") is defined in exactly one place.
Approach
- Find duplicated subquery expressions first. If the same filter-and-aggregate logic appears in two or three places (as a correlated scalar subquery, say), that is the strongest signal for a CTE: one definition, referenced everywhere.
- Name each transformation stage by what it represents to the business, not how it's computed:
completed_orders,customer_revenue,totals, notcte1,cte2. - Replace ad hoc tricks (a correlated
COUNT()faking a rank) with the SQL feature built for the job (RANK()). - Keep the final
SELECTthin: it should just assemble already-clear pieces.
-- BEFORE: the "completed revenue for this customer" expression is computed three
-- separate times, and the rank is faked with a correlated COUNT.
SELECT
o.customer_id,
(SELECT SUM(o2.amount) FROM orders o2
WHERE o2.customer_id = o.customer_id AND o2.status = 'completed') AS revenue,
(SELECT COUNT(*) FROM (
SELECT o4.customer_id, SUM(o4.amount) AS rev
FROM orders o4
WHERE o4.status = 'completed'
GROUP BY o4.customer_id
HAVING SUM(o4.amount) > (
SELECT SUM(o5.amount) FROM orders o5
WHERE o5.customer_id = o.customer_id AND o5.status = 'completed'
)
)
) + 1 AS revenue_rank,
(SELECT SUM(o2.amount) FROM orders o2
WHERE o2.customer_id = o.customer_id AND o2.status = 'completed') * 1.0 /
(SELECT SUM(o3.amount) FROM orders o3 WHERE o3.status = 'completed') AS pct_of_total_revenue
FROM orders o
WHERE o.status = 'completed'
GROUP BY o.customer_id
ORDER BY revenue DESC, o.customer_id;
-- AFTER: each expression computed once, each stage named
WITH completed_orders AS (
SELECT * FROM orders WHERE status = 'completed'
),
customer_revenue AS (
SELECT customer_id, SUM(amount) AS revenue
FROM completed_orders
GROUP BY customer_id
),
totals AS (
SELECT SUM(revenue) AS total_revenue FROM customer_revenue
),
ranked AS (
SELECT customer_id, revenue,
RANK() OVER (ORDER BY revenue DESC) AS revenue_rank
FROM customer_revenue
)
SELECT
r.customer_id,
r.revenue,
r.revenue_rank,
r.revenue * 1.0 / t.total_revenue AS pct_of_total_revenue
FROM ranked r
CROSS JOIN totals t
ORDER BY r.revenue DESC, r.customer_id;
Key points
completed_ordersis the single source of truth for "what counts as revenue"; if the business rule changes (say, adding another eligible status), it changes in one place instead of three.RANK()replaces the correlated "count how many customers have more revenue than me, plus one" trick; it says exactly what it means and ties are handled by the engine's documented semantics instead of ad hoc logic.totalsis computed once and joined in withCROSS JOIN, instead of being recomputed inline for every row.
Complexity
The before-version recomputes the completed-revenue-per-customer aggregation up to three times per outer row in the worst case (query-plan dependent), plus a correlated subquery per row for the fake rank, which is at least O(n) work per outer row, O(n^2) overall in the naive case. The after-version computes each aggregate once (O(n) to scan and group) and ranks with a single sort (O(k log k) over k customers), then joins the constant totals row in O(1) per row.
Edge cases
- Ties in revenue:
RANK()gives tied customers the same rank and skips the next rank number (1, 2, 2, 4), matching the correlated-count trick's behavior exactly, verified below. - A customer with zero completed orders never appears in
customer_revenue(it's built fromcompleted_orders), so this refactor implicitly excludes them, same as the original; if you need customers with $0 shown explicitly, that is a deliberate change to the CTE, not a side effect to discover later.
Worked example (executed, SQLite)
Seed: 4 customers, mixed completed/pending/refunded orders, including a genuine tie between two customers.
BEFORE (nested, duplicated expressions):
('C1', 150.0, 1, 0.36585365853658536)
('C2', 120.0, 2, 0.2926829268292683)
('C3', 120.0, 2, 0.2926829268292683)
('C4', 20.0, 4, 0.04878048780487805)
AFTER (refactored into CTEs):
('C1', 150.0, 1, 0.36585365853658536)
('C2', 120.0, 2, 0.2926829268292683)
('C3', 120.0, 2, 0.2926829268292683)
('C4', 20.0, 4, 0.04878048780487805)
Identical output, including the C2/C3 tie sharing rank 2 and C4 correctly landing at rank 4 (not 3), confirming the RANK() replacement preserves the original tie-breaking behavior.
Trade-offs and pitfalls
This kind of refactor is not just about making one query prettier: it is how you own the analytics platform's SQL hygiene over time, since deeply nested, duplicated-expression queries are exactly what accumulates when a report gets patched under deadline pressure by several different people. Naming the business rule once (completed_orders) means the next person who needs to add a new order status doesn't have to grep the query for every place "completed" is spelled out. The main wrong turn is over-fragmenting: wrapping every trivial single-use filter in its own CTE adds indirection without adding clarity. Break at points where a name genuinely documents intent or where an expression is reused, not at every line.
Write a query to find customers who have never placed an order. Given customers(customer_id, email) and orders(order_id, customer_id), return customer_id and email for every customer with zero matching orders.
Sample Answer
Direct answer
Finding customers with zero orders is an anti-join: return every row from customers that has no corresponding row in orders. The two standard ANSI patterns are LEFT JOIN ... WHERE right_key IS NULL and NOT EXISTS (subquery); both are correct, and for this exact question they return identical results.
Approach
- Start from
customers(the side you need every row from) and LEFT JOIN toorderson the customer key. - A customer with no orders produces a joined row where every
orderscolumn is NULL. - Filter to exactly those rows with
WHERE o.order_id IS NULL(an anti-join), or equivalently useNOT EXISTSto ask the same question without materializing a join.
Worked example (sqlite3, verified)
Sample data:
CREATE TABLE customers (customer_id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO customers VALUES
(1, 'alice@x.com'), (2, 'bob@x.com'), (3, 'carol@x.com'), (4, 'dave@x.com');
CREATE TABLE orders (order_id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT);
INSERT INTO orders VALUES (101, 1, '2024-01-05'), (102, 1, '2024-03-10'), (103, 2, '2024-02-01');
-- customers 3 and 4 have zero orders
LEFT JOIN ... IS NULL:
SELECT c.customer_id, c.email
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
WHERE o.order_id IS NULL
ORDER BY c.customer_id;
Result: (3, 'carol@x.com'), (4, 'dave@x.com'). Exactly the 2 customers with no matching order row.
NOT EXISTS (equivalent):
SELECT c.customer_id, c.email
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id)
ORDER BY c.customer_id;
Result: identical, (3, 'carol@x.com'), (4, 'dave@x.com').
Extension: also return the most recent order date, NULL if none. This is the natural follow-on to the same LEFT JOIN, just without filtering out matched rows, aggregated with MAX:
SELECT c.customer_id, c.email, MAX(o.order_date) AS most_recent_order_date
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.email
ORDER BY c.customer_id;
Result: (1, alice, '2024-03-10'), (2, bob, '2024-02-01'), (3, carol, NULL), (4, dave, NULL). MAX over an all-NULL group (Carol, Dave) correctly returns NULL rather than erroring or defaulting to 0.
Key points
LEFT JOIN ... IS NULLandNOT EXISTSare semantically equivalent for a simple single-column anti-join like this one.- The
IS NULLfilter must reference a column from the right table that is guaranteed non-NULL when a match exists (typically its primary key,o.order_idhere), not an arbitrary right-side column that could itself legitimately be NULL in a matched row. - The extension query keeps every customer (LEFT JOIN, no WHERE filter) and lets
MAX(order_date)do double duty: it answers "most recent order" for customers with orders and naturally yields NULL for customers without any.
Complexity, edge cases & pitfalls
- Both patterns need an index on
orders.customer_idto avoid a full scan per customer; with that index,NOT EXISTStypically compiles to a semi-join/anti-join plan that stops at the first match, which is often at least as fast as the LEFT JOIN plan and easier to reason about when more join conditions are added later. - If
orders.customer_idcan itself be NULL (an order somehow unassigned),NOT EXISTSis unaffected, but a naiveWHERE customer_id NOT IN (SELECT customer_id FROM orders)breaks completely: a single NULL in the subquery's result makesNOT INreturn zero rows for the whole outer query. This is whyNOT EXISTS(or the LEFT JOIN pattern) is preferred overNOT INfor anti-joins. - If
customershas duplicate customer_id values (a data quality issue, not expected under a primary key), the LEFT JOIN version could return the same customer more than once when it has orders, though the anti-join branch itself is unaffected since it only fires for customers with zero matches.
Unlock Full Question Bank
Get access to all SQL for Data Analysis interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.