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.
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.
For business reporting, how do SUMIFS, COUNTIFS, and AVERAGEIFS compare with PivotTables? When would you prefer conditional aggregate formulas instead of a PivotTable, and when would you avoid them?
Sample Answer
How they compare
- SUMIFS / COUNTIFS / AVERAGEIFS are best when I need a formula-driven output in a specific cell, such as one KPI tile or one row in a report.
- PivotTables are better when I need fast exploration, multiple groupings, drill-down, and a layout that non-technical users can filter.
When I prefer conditional aggregates
- The report needs a fixed template with stable cells.
- I want formulas that are easy to copy across months or categories.
- I need results tied directly to dashboard tiles or other formulas.
- I want transparent logic that can be audited cell by cell.
When I prefer PivotTables
- The question is exploratory or may change often.
- I need summaries by many dimensions, like region, product, and channel.
- I want slicers, timelines, drill-through, or a chart-ready summary.
- The dataset is large enough that formulas would become slow or cluttered.
When I avoid conditional aggregates
- If the workbook has many rows and many formulas, recalculation can get heavy.
- If the grouping needs to be dynamic, PivotTables are usually easier to maintain.
- If stakeholders need self-service filtering, a PivotTable is more user-friendly.
In practice, I often use both: a PivotTable for exploration and a few SUMIFS or COUNTIFS formulas for the final dashboard tiles.
You receive a CSV export with inconsistent date formats, extra spaces, merged cells in headers, and product names that differ only by spelling or casing. How would you clean and structure it in Excel so it can be analyzed reliably without losing the original raw data?
Sample Answer
How I would clean it without losing raw data
- Keep the original CSV untouched on a Raw sheet or, better, load it into Power Query as the source layer.
- Build a separate Clean output table for analysis.
- Never analyze directly from the raw import.
Cleaning steps
- Dates: standardize them in Power Query or with helper columns so every date becomes a true Excel date.
- Spaces and casing: use
TRIM,CLEAN, and consistent case rules to normalize text. - Headers: unmerge cells in the header area, fill missing header labels, and promote a single clean header row.
- Product names: create a mapping table for known variants, such as spelling differences or mixed casing, and convert them to one canonical name.
- Structure: turn the cleaned output into an Excel Table so formulas and pivots can refresh reliably.
Why I prefer Power Query for this
- It preserves the source data.
- It makes the cleanup steps repeatable.
- It is easier to refresh when a new CSV arrives.
Example logic
- Raw product name:
widget pro,Widget Pro,WIDGET PRO - Cleaned product name:
Widget Pro
If I had to do it manually, I would still keep the raw import separate, create a staging sheet, and only then publish the final analysis table. That protects the audit trail and makes the workbook easier to trust.
Write a query that classifies customers into spend tiers using CASE WHEN, for example 'low' / 'medium' / 'high' based on lifetime order total, and returns the count of customers in each tier.
Sample Answer
Direct answer
Aggregate lifetime spend per customer first (including customers with zero orders, via LEFT JOIN and COALESCE), then map the aggregated total to a tier using CASE WHEN, checked from the highest threshold down to the lowest so each customer lands in exactly one bucket.
Approach
- Compute lifetime spend per customer:
LEFT JOINcustomers to orders andSUMthe order amounts, so customers with no orders still appear in the result instead of being silently dropped. - Wrap the sum in
COALESCE(SUM(...), 0)so a customer with zero orders gets0instead of NULL (SUM over an empty group is NULL, not 0). - Apply
CASE WHEN ... THEN ... ENDon the aggregated total, testing conditions from highest to lowest threshold; CASE evaluates top to bottom and stops at the first match, which is what makes ordering the thresholds correctly matter.
Worked example (sqlite3, verified)
Sample data:
CREATE TABLE customers (customer_id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO customers VALUES (1,'Alice'), (2,'Bob'), (3,'Carol'), (4,'Dave'), (5,'Eve');
CREATE TABLE orders (order_id INTEGER PRIMARY KEY, customer_id INTEGER, total_amount INTEGER);
INSERT INTO orders VALUES
(1, 1, 400), (2, 1, 700), -- Alice: 1100 total
(3, 2, 150), (4, 2, 200), -- Bob: 350 total
(5, 3, 50), -- Carol: 50 total
(6, 4, -20), (7, 4, 400); -- Dave: 380 net (a refund row plus a purchase)
-- Eve (5): zero orders
Tiers: high >= $1000, medium >= $300, else low.
Per-customer tier assignment:
WITH lifetime AS (
SELECT c.customer_id, c.name, COALESCE(SUM(o.total_amount), 0) AS total_spend
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.name
)
SELECT
customer_id, name, total_spend,
CASE
WHEN total_spend >= 1000 THEN 'high'
WHEN total_spend >= 300 THEN 'medium'
ELSE 'low'
END AS spend_tier
FROM lifetime
ORDER BY customer_id;
Result:
| customer_id | name | total_spend | spend_tier |
|---|---|---|---|
| 1 | Alice | 1100 | high |
| 2 | Bob | 350 | medium |
| 3 | Carol | 50 | low |
| 4 | Dave | 380 | medium |
| 5 | Eve | 0 | low |
Dave's net spend (380) correctly reflects a $20 refund against a $400 purchase, landing him in medium, not low; Eve, with zero orders, was preserved by the LEFT JOIN and correctly bucketed 'low' via COALESCE rather than dropped from the report entirely.
Count of customers per tier:
WITH lifetime AS (
SELECT c.customer_id, COALESCE(SUM(o.total_amount), 0) AS total_spend
FROM customers c LEFT JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id
),
tiered AS (
SELECT customer_id,
CASE WHEN total_spend >= 1000 THEN 'high' WHEN total_spend >= 300 THEN 'medium' ELSE 'low' END AS spend_tier
FROM lifetime
)
SELECT spend_tier, COUNT(*) AS customer_count FROM tiered GROUP BY spend_tier;
Result: ('high', 1), ('medium', 2), ('low', 2). Matches the per-customer table above exactly (Alice=high, Bob+Dave=medium, Carol+Eve=low).
Key points
- LEFT JOIN plus COALESCE is what keeps zero-activity customers in the report; an INNER JOIN would silently drop Eve before she ever reached the CASE expression.
- CASE WHEN thresholds must be ordered from most restrictive to least restrictive (highest dollar amount first); writing the medium check before the high check would misclassify every high-spend customer as medium, since CASE stops at the first TRUE branch.
- Aggregating to one row per customer before applying CASE (rather than applying CASE per order row) is essential; otherwise a customer with multiple orders would get evaluated against a tier per order, not their true lifetime total.
Complexity, edge cases & pitfalls
- If a customer's orders include a large negative refund that pushes total_spend below zero, this CASE still classifies them 'low' (since it doesn't have a bucket below 'low'); whether negative-spend customers deserve a distinct treatment (e.g. excluded from the report, or a 'net negative' tier) is a business decision worth confirming.
- Hardcoded thresholds (1000, 300) mean a reporting tool has to duplicate that logic or re-run the query to change tier boundaries; a lookup table joined on a
BETWEENrange, or parameters passed into a view, is a cleaner path once thresholds need to be configurable. - CASE WHEN with no ELSE clause returns NULL for any row matching none of the WHEN conditions; this query is safe because ELSE 'low' is a catch-all, but omitting ELSE is a common source of silent NULLs in less carefully written bucketing queries.
- Performance-wise, this pattern requires a full aggregation pass over
orders(unavoidable, since lifetime spend needs every order); an index onorders.customer_idspeeds the join and GROUP BY, but the aggregation cost itself scales with total order volume, not customer count.
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.