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 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.
You're given three related tables at different granularities (say users, sessions, and events). Write a query that answers a business question spanning all three (for example: number of distinct users with at least one event in a session in the last 30 days), and explain how you chose the join order and join types.
Sample Answer
Direct answer
With three tables at different granularities (users to sessions to events), join in the direction the question requires: users to sessions to events when you need to filter or aggregate at the event level, and pick INNER JOIN when a row without a match on the next table shouldn't count toward the answer at all. For "distinct users with at least one event in a session in the last 30 days," every step (session must exist, event must exist, both within the window) is a requirement, so INNER JOIN is correct at each step, and the final aggregate is COUNT(DISTINCT user_id) to collapse the fan-out back down to one row per qualifying user.
Approach
- Identify the grain mismatch: one user can have many sessions, and one session can have many events, so a naive 3-way join produces one row per (user, session, event) combination, not one row per user.
- Choose join type based on what "counts": here we only want users who have real qualifying activity, so INNER JOIN at both steps (sessions to users, events to sessions) is correct; a LEFT JOIN would incorrectly let users with zero matching activity survive into a COUNT.
- Filter early: apply the 30-day window on
session_datebefore joining events, so the join only processes sessions inside the window. - Collapse the fan-out with
COUNT(DISTINCT user_id)in the final SELECT, since a user can appear on multiple rows (one per session per event) without being double-counted incorrectly.
Worked example (sqlite3, verified)
Sample data (reference "now" pinned to 2024-06-20, so the 30-day window is 2024-05-21 through 2024-06-20):
CREATE TABLE users (user_id INTEGER PRIMARY KEY, signup_date TEXT);
INSERT INTO users VALUES (1, '2024-01-01'), (2, '2024-01-05'), (3, '2024-02-01');
CREATE TABLE sessions (session_id INTEGER PRIMARY KEY, user_id INTEGER, session_date TEXT);
INSERT INTO sessions VALUES
(1001, 1, '2024-06-01'),
(1002, 1, '2024-06-15'),
(1003, 2, '2024-06-10'),
(1004, 3, '2024-05-01'); -- outside the 30-day window
CREATE TABLE events (event_id INTEGER PRIMARY KEY, session_id INTEGER, event_type TEXT, event_ts TEXT);
INSERT INTO events VALUES
(1, 1001, 'click', '2024-06-01 10:00'),
(2, 1001, 'click', '2024-06-01 10:05'),
(3, 1002, 'view', '2024-06-15 09:00'),
(4, 1003, NULL, '2024-06-10 08:00');
-- session 1004 (user 3) has zero events
Raw 3-way join, to see the fan-out before aggregating:
SELECT u.user_id, s.session_id, e.event_id
FROM users u
JOIN sessions s ON s.user_id = u.user_id
JOIN events e ON e.session_id = s.session_id
WHERE s.session_date >= '2024-05-21'
ORDER BY u.user_id, s.session_id, e.event_id;
Result (4 rows): user 1 appears twice for session 1001 (2 events) and once for session 1002 (1 event), user 2 appears once. User 3's session (1004) is outside the window and drops out at the sessions join; it would have dropped out at the events join anyway since it has zero events.
The actual answer, distinct users with an event in a session in the window:
SELECT COUNT(DISTINCT u.user_id) AS users_with_event_in_window
FROM users u
JOIN sessions s ON s.user_id = u.user_id
JOIN events e ON e.session_id = s.session_id
WHERE s.session_date >= '2024-05-21' AND s.session_date <= '2024-06-20';
Result: 2. Verified against the raw join: users 1 and 2 both had at least one qualifying event row, user 3 had none.
Per-user breakdown, to double-check the fan-out didn't distort anything:
SELECT u.user_id, COUNT(DISTINCT s.session_id) AS sessions_with_event, COUNT(e.event_id) AS event_count
FROM users u
JOIN sessions s ON s.user_id = u.user_id
JOIN events e ON e.session_id = s.session_id
WHERE s.session_date >= '2024-05-21' AND s.session_date <= '2024-06-20'
GROUP BY u.user_id;
Result: user 1 has sessions_with_event = 2, event_count = 3 (2 events in session 1001, 1 in session 1002); user 2 has sessions_with_event = 1, event_count = 1. COUNT(DISTINCT session_id) correctly reports 2 sessions for user 1 even though the raw join produced 3 rows for him.
Key points
- Join order here (users to sessions to events) mirrors the data's natural hierarchy; filtering on
session_dateright after the sessions join, before ever touching events, keeps the intermediate result small. - INNER JOIN at both steps is deliberate: a user needs a real qualifying session with a real qualifying event to count, matching the question's "at least one event in a session" requirement exactly.
COUNT(DISTINCT user_id)(notCOUNT(user_id)orCOUNT(*)) is what turns the fan-out rows back into "how many unique users," since a qualifying user can legitimately appear on more than one row.
Complexity, edge cases & pitfalls
- The 3-way join's cost is dominated by however many (session, event) pairs exist inside the date window; filtering the date range before the events join (rather than after) avoids joining events that belong to out-of-window sessions in the first place.
- If the question instead asked "how many users have zero events," this same query is wrong: you'd need a LEFT JOIN from users all the way through with
IS NULLchecks, not an INNER JOIN, because INNER JOIN by construction only keeps users with a match. - Watch
COUNT(DISTINCT ...)cost on very large tables; it typically requires a sort or hash-based dedup internally, which is more expensive than a plainCOUNT(*), though still the correct choice here for correctness over a raw count. - If a session can have zero events (like session 1004 for user 3), it's silently dropped by the INNER JOIN to events, correctly, since the question requires an actual event, not merely a session.
Not every company's reporting period lines up with the calendar month. Given a transactions table and a fiscal_calendar lookup table mapping calendar dates to fiscal year/month, write a query that aggregates revenue by fiscal period, and explain why you'd model this as a join to a calendar table rather than date arithmetic.
Sample Answer
Join each transaction's date to a fiscal_calendar lookup table on the exact date, and group by the fiscal columns it returns. Model this as a join, not date arithmetic (DATE_TRUNC, manual month offsets), because fiscal period boundaries are a business decision that can be irregular: they don't have to land on calendar month-ends, and no closed-form date formula can capture that reliably. A calendar table stores the mapping as data, once, and every query just joins to it.
The join
SELECT
fc.fiscal_year,
fc.fiscal_month_number,
fc.fiscal_period_label,
COUNT(t.txn_id) AS txn_count,
SUM(t.amount) AS total_amount
FROM transactions t
LEFT JOIN fiscal_calendar fc ON fc.cal_date = t.txn_date
GROUP BY 1, 2, 3
ORDER BY fc.fiscal_year, fc.fiscal_month_number;
Worked example: why the calendar table matters, not just style preference
Run in sqlite3; strftime('%Y-%m', txn_date) is sqlite3's month-truncation function. The equivalent in Postgres is DATE_TRUNC('month', txn_date), in BigQuery DATE_TRUNC(txn_date, MONTH), in SQL Server DATEFROMPARTS(YEAR(txn_date), MONTH(txn_date), 1), all illustrating the same naive date-arithmetic approach the calendar-table join is being compared against.
Seed a small "4-4-5" style fiscal calendar (a retail convention where each quarter's three months split into a 4-week, a 4-week, and a 5-week period) where fiscal period 1 runs 2026-01-18 through 2026-02-14 (crossing the January/February month boundary) and fiscal period 2 starts 2026-02-15 (mid-month):
fiscal_calendar: (2026-01-30, FY2026, P01), (2026-02-01, FY2026, P01), (2026-02-15, FY2026, P02)
transactions: (1, 2026-01-30, 100), (2, 2026-02-01, 200), (3, 2026-02-15, 50), (4, 2026-03-01, 75)
Calendar-join result:
fiscal_period_label fiscal_year fiscal_month_number txn_count total_amount
UNMAPPED 1 75
FY2026-P01 2026 1 2 300
FY2026-P02 2026 2 1 50
Compare that to naive calendar-month grouping (strftime('%Y-%m', txn_date) or equivalently DATE_TRUNC('month', txn_date)) on the exact same rows:
calendar_month total_amount
2026-01 100
2026-02 250
2026-03 75
The two approaches disagree, and the disagreement is the whole point: fiscal period P01 correctly groups transactions 1 and 2 together (total 300, they're in the same fiscal period even though one is dated in January and one in February), but naive month-grouping splits them apart (100 in "2026-01", part of 250 in "2026-02"). Meanwhile naive "2026-02" of 250 wrongly merges transaction 2 (fiscal P01) with transaction 3 (fiscal P02), two different fiscal periods that happen to share a calendar month. No amount of date-arithmetic cleverness reproduces the calendar table's answer here, because the boundary (Feb 15) isn't a fixed offset from anything, it's whatever the finance calendar says it is that year.
Transaction 4 (2026-03-01) has no row in this intentionally partial calendar, and the LEFT JOIN surfaces it as UNMAPPED rather than silently dropping it, the same silent-drop risk that applies to any join. In production, that's your signal the calendar table needs to be extended, not a query bug.
Trade-offs and pitfalls
- The calendar table has to be maintained and kept current. It needs a row for every date the business might report on, extended annually (or whenever the fiscal calendar is redefined), and if it falls behind, transactions land in
UNMAPPED(via theLEFT JOIN) rather than being silently miscategorized, which is the safer failure mode but still needs monitoring. - Indexing.
fiscal_calendar.cal_dateas a primary key (as seeded here) makes this an efficient equality join, meaningfully cheaper than a range join; it's an equi-join specifically because the calendar table pre-computes the answer for every date, so you don't needBETWEENlogic at query time. - Multi-entity / multi-fiscal-year complexity. Companies with subsidiaries on different fiscal calendars (common after M&A) need the calendar table keyed by entity as well as date, an extra join column, not a fundamentally different pattern.
- Auditability is the real payoff. Beyond correctness, centralizing the fiscal logic in one table means a fiscal calendar change (the company shifts its year-end) is a data update in one place, not a hunt through every report's date-arithmetic logic to find and fix every place the old boundary was hardcoded.
What's the difference between GROUP BY and DISTINCT? Give an example of each, and show a case where you need HAVING on top of a GROUP BY versus a case where a plain DISTINCT is all you need.
Sample Answer
DISTINCT removes duplicate rows from a result set. GROUP BY groups rows that share a value so an aggregate function (COUNT, SUM, AVG) can be computed per group. Plain DISTINCT never computes anything about a group besides its existence; the moment a question needs a count, a sum, or a threshold applied to a computed value, you need GROUP BY, and HAVING if that threshold applies to the aggregate itself.
When DISTINCT alone is enough
"Which countries appear in the users table?" No calculation involved, just a deduplicated list of values.
When you need GROUP BY, and HAVING on top of it
"Which countries have more than 2 users?" Now there's a count (an aggregate), and a threshold applied to that count (a filter after aggregation). WHERE can't do this: WHERE filters rows before aggregation runs, so a condition like COUNT(*) > 2 doesn't exist yet at the point WHERE evaluates. HAVING runs after GROUP BY has produced its per-group aggregates, so it's the clause that can filter on them.
Worked example
CREATE TABLE users (
user_id INTEGER PRIMARY KEY,
country TEXT
);
INSERT INTO users (country) VALUES
('USA'), ('USA'), ('USA'), ('IN'), ('IN'), ('UK');
-- DISTINCT: unique countries present, no counts
SELECT DISTINCT country FROM users ORDER BY country;
-- GROUP BY + HAVING: countries with more than 2 users
SELECT country, COUNT(*) AS user_count
FROM users
GROUP BY country
HAVING COUNT(*) > 2;
Result:
-- DISTINCT --
┌─────────┐
│ country │
├─────────┤
│ IN │
│ UK │
│ USA │
└─────────┘
-- GROUP BY + HAVING COUNT(*) > 2 --
┌─────────┬────────────┐
│ country │ user_count │
├─────────┼────────────┤
│ USA │ 3 │
└─────────┴────────────┘
DISTINCT country returns all three countries with no information about how many users are in each. GROUP BY country HAVING COUNT(*) > 2 returns only USA, the one country whose user count clears the threshold, along with that count.
Trade-offs & pitfalls
DISTINCTacross multiple columns is equivalent toGROUP BYon those same columns with no aggregate function selected:SELECT DISTINCT a, b FROM tandSELECT a, b FROM t GROUP BY a, breturn the same rows. Treat them as interchangeable only when there's no aggregate involved.COUNT(DISTINCT user_id)inside aGROUP BYis a third, different thing: deduplicating within an aggregate, not deduplicating the whole result set. Don't conflateSELECT DISTINCTwithCOUNT(DISTINCT ...); they solve different problems.- Common wrong turn: writing
WHERE COUNT(*) > 2instead ofHAVING COUNT(*) > 2. Most engines reject this outright with a clear error, but under interview pressure candidates sometimes freeze rather than immediately naming why: aggregates aren't materialized yet whenWHEREruns.
Write a query that computes Daily Active Users (DAU) for a given month: for each date, the count of distinct users with at least one event that day.
Sample Answer
Direct answer
Truncate each event's timestamp down to a calendar date, group by that date, and count DISTINCT user_id per date. A user with several events in one day should only count once toward that day's DAU.
Structured elaboration
DATE(event_time)collapses a timestamp to a calendar date so all of a day's events group together. Grouping by the raw timestamp instead would put nearly every event in its own group.COUNT(DISTINCT user_id)is what makes it "active users" and not "events." A power user firing 50 events in a day still contributes exactly 1 to that day's DAU.- Filter out
NULLuser_id up front. An anonymous or malformed event would otherwise sit in its own NULL-keyed bucket rather than being cleanly excluded. - Use a half-open range for the month boundary (
>= '2024-01-01' AND < '2024-02-01') rather thanBETWEEN, for the same boundary-safety reason as any date-range filter.
Worked example
Sample data (events), tested in DuckDB 1.5:
| user_id | event_time |
|---|---|
| 1 | 2024-01-01 08:00:00 |
| 2 | 2024-01-01 09:30:00 |
| 2 | 2024-01-01 20:00:00 |
| 3 | 2024-01-02 10:00:00 |
| 1 | 2024-01-02 11:00:00 |
| NULL | 2024-01-02 12:00:00 |
| 1 | 2024-01-03 09:00:00 |
| 2 | 2024-01-03 09:15:00 |
| 3 | 2024-01-03 09:45:00 |
| 4 | 2024-02-01 09:00:00 |
SELECT
DATE(event_time) AS event_date,
COUNT(DISTINCT user_id) AS dau
FROM events
WHERE user_id IS NOT NULL
AND event_time >= '2024-01-01'::timestamp
AND event_time < '2024-02-01'::timestamp
GROUP BY DATE(event_time)
ORDER BY event_date;
Result:
| event_date | dau |
|---|---|
| 2024-01-01 | 2 |
| 2024-01-02 | 2 |
| 2024-01-03 | 3 |
January 1 is 2 (users 1, 2, with user 2's two same-day events counted once). January 2 is 2 (users 1, 3; the NULL user_id row and the February row are both excluded). January 3 is 3 (users 1, 2, 3).
Trade-offs & pitfalls
- Complexity is a single grouped aggregation over the filtered rows, the practical cost driver at scale is whether event_time is indexed or partitioned by date. Precomputing an
event_datecolumn (and indexing or partitioning on it) is the standard fix once the events table gets large. - Edge cases: duplicate events per user per day collapse correctly via
COUNT(DISTINCT); a NULL user_id must be excluded explicitly or it corrupts the day's count; an event in the last second of a day still counts for that day, not the next. - "Active" always needs a definition: does any event count, or only specific event types (excluding heartbeat or ping events, for instance)? This is the same base query that DAU/MAU ratio (stickiness), month-over-month DAU trend, per-user local-midnight boundaries, and anonymous-id-to-user-id identity resolution all build on top of, see the follow-ups.
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.