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.
A manager asks you to explain why sales dropped last week, and the only input you have is a raw Excel export from the CRM. How would you structure the investigation in Excel from the first pass to the final answer, and what analyses would you prioritize?
Sample Answer
How I would investigate it in Excel
1) Validate the export
- Check that the CRM extract has the right date range, required columns, and no obvious duplicates.
- Confirm whether sales means booked revenue, closed-won deals, or another definition.
2) Compare the right time windows
- Look at last week versus the prior week, but also compare against the same days in previous weeks so day-of-week effects do not mislead us.
- Separate the drop into volume, average deal size, and conversion rate if the CRM has pipeline stages.
3) Segment the problem
- Build PivotTables by region, rep, product, channel, and deal stage.
- Check whether the decline is broad-based or isolated to one segment.
- Look for missing large deals, lower activity, or a stage where opportunities stalled.
4) Check for operational causes
- Lost deals, fewer new opportunities, delayed closes, or a sudden change in source mix.
- If the CRM has timestamps, I would also check whether the drop is just a timing issue from late-week logging.
5) Final answer
- I would summarize the biggest driver first, then give one or two supporting pivots or charts.
- If the root cause is unclear, I would be explicit about that and recommend the next data point to collect.
The key is to move from "sales are down" to a specific explanation like "the decline came mainly from one region and a few large deals slipping out of the close window."
Write a query that computes month-over-month percentage change in total revenue, one row per month. Explain how you'd handle the first month in the series (no prior month to compare against).
Sample Answer
Direct answer
Aggregate revenue by month, then use the LAG() window function to pull each month's prior-month total onto the same row. Percentage change is (current - previous) / previous, guarded against a missing or zero prior month with NULLIF.
Structured elaboration
- Aggregation step:
date_trunc('month', created_at)buckets every order into its month. Keep a truemonth_startvalue (not just a display string) as theORDER BYkey forLAG, so window ordering is calendar-correct rather than dependent on string sort order. LAG(revenue) OVER (ORDER BY month_start)reaches back exactly one row, one month, given the prior aggregation, without needing a self-join.- First month in the series:
LAG()returns NULL, since there is no preceding row in the window. The CASE expression turns that into an explicit NULL forpct_changerather than an error or a misleading 0%. Coalescing the first month to 0% would falsely claim "no change" when there is actually nothing to compare against.
Worked example
Sample data (orders), tested in DuckDB 1.5:
| order_id | created_at | amount_cents |
|---|---|---|
| 1 | 2024-01-05 | 10000 |
| 2 | 2024-01-20 | 5000 |
| 3 | 2024-02-03 | 20000 |
| 4 | 2024-02-18 | 10000 |
| 5 | 2024-03-01 | 9000 |
| 6 | 2024-03-15 | 6000 |
WITH monthly AS (
SELECT
strftime(date_trunc('month', created_at), '%Y-%m') AS month,
date_trunc('month', created_at) AS month_start,
SUM(amount_cents) / 100.0 AS revenue
FROM orders
WHERE created_at >= DATE '2024-01-01'
AND created_at < DATE '2025-01-01'
GROUP BY 1, 2
)
SELECT
month,
revenue,
LAG(revenue) OVER (ORDER BY month_start) AS prev_revenue,
CASE
WHEN LAG(revenue) OVER (ORDER BY month_start) IS NULL THEN NULL
WHEN LAG(revenue) OVER (ORDER BY month_start) = 0 THEN NULL
ELSE ROUND((revenue - LAG(revenue) OVER (ORDER BY month_start))
/ NULLIF(LAG(revenue) OVER (ORDER BY month_start), 0) * 100.0, 2)
END AS pct_change
FROM monthly
ORDER BY month_start;
Result:
| month | revenue | prev_revenue | pct_change |
|---|---|---|---|
| 2024-01 | 150.0 | NULL | NULL |
| 2024-02 | 300.0 | 150.0 | 100.0 |
| 2024-03 | 150.0 | 300.0 | -50.0 |
January totals $150 ($100 + $50), with no prior month, so pct_change is NULL. February totals $300 ($200 + $100), a 100% increase over January. March totals $150 ($90 + $60), a 50% decrease from February.
Trade-offs & pitfalls
- A single window function over an already-aggregated monthly table is cheap even at scale; the ORDER BY inside the window is the only sort involved.
- Displaying the first month: leaving
pct_changeas NULL (typically rendered blank in BI tools) is more honest than coalescing to 0. Decide with the requester which they actually want, and if 0 is chosen, label it clearly as "no prior period," not "0% growth." - This query only emits a row for months that had at least one order. A month with zero orders is silently missing from the output rather than showing 0 revenue. If every calendar month needs to be represented, generate the month spine explicitly instead of relying on GROUP BY over the orders table.
- Currency handling:
SUM(amount_cents) / 100.0assumes a single currency and a cents-integer column. A real revenue table often needs currency conversion or a decimal amount column, don't silently sum mixed currencies. LAG()is standard SQL, supported in MySQL 8+, SQL Server, Postgres, DuckDB, Snowflake, and BigQuery, making this one of the more portable patterns in this set.
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.
When would you reach for SQL instead of doing the analysis in a spreadsheet or a BI tool's built-in functions (like a pivot table or VLOOKUP-style lookup)? Give two concrete examples of tasks that are much better done in SQL and explain what a spreadsheet approach would struggle with.
Sample Answer
Reach for SQL whenever the task needs to run against the full underlying data rather than a manually pasted extract, needs to be exactly reproducible, or needs to combine several tables by a key. A spreadsheet's VLOOKUP and pivot table are fine for a small, single-table slice a person can eyeball once; they degrade badly as the row count, the number of source tables, or the need to repeat the calculation correctly next month all grow.
Two concrete examples
1. Joining and deduplicating across multiple sources. Combining a CRM export, a billing export, and a support-ticket export by customer_id into one row per customer. VLOOKUP handles one lookup column against one other sheet; the moment a task needs a three-way join with duplicate keys on either side, VLOOKUP returns only the first match and silently drops or miscounts the rest. A SQL JOIN handles the full match set deterministically, and a GROUP BY handles the deduplication explicitly and visibly.
2. Any calculation someone else needs to reproduce exactly, or that needs to run on a schedule. A pivot table's field configuration lives inside the spreadsheet's UI: it isn't version-controlled, isn't easy to diff, and has to be manually rebuilt correctly by whoever opens the file next. A saved SQL query (or a view) is text: it runs identically every time, can sit in source control, and can be scheduled without a human reopening a workbook.
The reverse direction: SQL's equivalent of a pivot table or VLOOKUP
A GROUP BY with aggregate functions is SQL's version of a pivot table's row-grouping plus value-aggregation. A JOIN on a shared key is SQL's version of VLOOKUP or INDEX-MATCH: instead of "look up this key in that other sheet's range," it's "match every row in table B to the row in table A that shares this key," for as many tables as needed at once.
Worked example
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
region TEXT,
amount NUMERIC
);
INSERT INTO orders (region, amount) VALUES
('East', 400), ('East', 600), ('West', 150),
('West', 200), ('West', 250), ('North', 2400);
SELECT
region,
SUM(amount) AS region_revenue,
ROUND(100.0 * SUM(amount) / (SELECT SUM(amount) FROM orders), 1) AS pct_of_total
FROM orders
GROUP BY region
ORDER BY region_revenue DESC;
Result:
┌────────┬────────────────┬──────────────┐
│ region │ region_revenue │ pct_of_total │
├────────┼────────────────┼──────────────┤
│ North │ 2400 │ 60.0 │
│ East │ 1000 │ 25.0 │
│ West │ 600 │ 15.0 │
└────────┴────────────────┴──────────────┘
A pivot table gets the region_revenue column easily. Getting pct_of_total right, as a value that stays correct if a new region is added later, needs either a spreadsheet formula referencing a moving total range (easy to break: forgetting to update the range after adding a row is a classic spreadsheet bug) or exactly this scalar subquery, which recomputes the grand total from the same source rows every time the query runs.
Trade-offs & pitfalls
- SQL is not better at everything. Ad-hoc, throwaway exploration by someone without database access, or the final polished chart for a stakeholder deck, is usually faster and clearer done in a spreadsheet or the BI layer.
- Centralize a calculation once in SQL (a shared view) instead of letting five dashboards each compute "active users" a slightly different way in their own pivot tables. This is one of the most common reasons dashboards disagree with each other.
- Common wrong turn: over-engineering a one-time, 20-row question into a SQL pipeline when a five-minute spreadsheet look would answer it. Match the tool to whether the task repeats or needs to scale, not to which tool seems more technical.
Given a contracts table where revenue is recognized evenly over the contract term, write SQL to produce recognized revenue per month across the whole portfolio, correctly prorating any contract whose start or end falls mid-month.
Sample Answer
Compute each contract's constant daily rate (total_amount divided by the inclusive day count of its term), generate a month calendar spanning the reporting window, then for every contract-month pair compute the overlap in days between the contract's term and that calendar month. Recognized revenue for that contract in that month is daily_rate * overlap_days; summing across contracts per month gives the portfolio total, and the overlap calculation is exactly what prorates a contract whose start or end falls mid-month.
Approach
term_daysper contract: inclusive day count fromstart_datetoend_date(julianday(end) - julianday(start) + 1; add 1 because both endpoints belong to the term).daily_rate = total_amount / term_days. This is the core straight-line assumption: revenue accrues evenly, one day at a time, for the life of the contract, not in even monthly chunks.- Generate month buckets across the reporting window (a recursive CTE here; a reusable calendar table in production).
- Join contracts to months wherever the contract's term and the month's range overlap at all:
start_date <= month_end AND end_date >= month_start. overlap_daysis the inclusive day count of the intersection of [contract start, contract end] and [month start, month end], usingMAX()of the two starts andMIN()of the two ends (SQLite's scalar multi-argumentMAX()/MIN(), confirmed here to propagate NULL:SELECT MAX(1, NULL, 3)returnsNULL). BigQuery'sGREATEST()/LEAST()match that NULL-propagating behavior, but Postgres'sGREATEST()/LEAST()do not: per the Postgres documentation, they explicitly ignore NULL arguments and only return NULL if every argument is NULL, a documented deviation from the SQL standard. That is not a hypothetical edge case for this query: an open-ended contract with a NULLend_datewould makeMIN(end_date, month_end)collapse to NULL here (and on BigQuery), silently dropping that contract's row from every month, while the same pattern ported to Postgres'sLEAST()would ignore the NULL and keep computing a result, a different, wrong-either-way outcome depending on engine. Guard withCOALESCE(end_date, '9999-12-31')(or another far-future sentinel) before the MIN/LEAST call wherever this pattern needs to run identically across engines.recognized_amount = daily_rate * overlap_days, summed per month for the portfolio total.
Worked example
CREATE TABLE contracts (
contract_id TEXT PRIMARY KEY,
start_date TEXT,
end_date TEXT,
total_amount NUMERIC
);
-- C1: mid-month start AND mid-month end (59-day term)
INSERT INTO contracts VALUES ('C1', '2026-01-15', '2026-03-14', 5900);
-- C2: clean calendar-month term (28-day term)
INSERT INTO contracts VALUES ('C2', '2026-02-01', '2026-02-28', 2800);
-- C3: mid-month to mid-month, spans into the next month
INSERT INTO contracts VALUES ('C3', '2026-03-10', '2026-04-09', 3100);
WITH RECURSIVE months(month_start) AS (
SELECT date('2026-01-01')
UNION ALL
SELECT date(month_start, '+1 month') FROM months WHERE month_start < date('2026-04-01')
),
-- months builds in passes: the base row is 2026-01-01, then each pass takes
-- the previous pass's row and builds the next month from it (date(month_start,
-- '+1 month')), re-running against months's own growing output, until a
-- pass's output fails the WHERE condition and the recursion stops.
month_ranges AS (
SELECT month_start, date(month_start, '+1 month', '-1 day') AS month_end
FROM months
),
term AS (
SELECT
contract_id, start_date, end_date, total_amount,
julianday(end_date) - julianday(start_date) + 1 AS term_days
FROM contracts
),
alloc AS (
SELECT
t.contract_id,
mr.month_start,
MAX(t.start_date, mr.month_start) AS overlap_start,
MIN(t.end_date, mr.month_end) AS overlap_end,
julianday(MIN(t.end_date, mr.month_end))
- julianday(MAX(t.start_date, mr.month_start)) + 1 AS overlap_days,
t.total_amount, t.term_days
FROM term t
JOIN month_ranges mr
ON t.start_date <= mr.month_end AND t.end_date >= mr.month_start
)
SELECT
strftime('%Y-%m', month_start) AS month,
contract_id, overlap_start, overlap_end, overlap_days,
ROUND(total_amount / term_days, 4) AS daily_rate,
ROUND((total_amount / term_days) * overlap_days, 2) AS recognized_amount
FROM alloc
WHERE overlap_days > 0
ORDER BY month, contract_id;
-- Portfolio total recognized revenue per month
-- (CTE scope is per statement: repeat the WITH clause when running this standalone)
WITH RECURSIVE months(month_start) AS (
SELECT date('2026-01-01')
UNION ALL
SELECT date(month_start, '+1 month') FROM months WHERE month_start < date('2026-04-01')
),
-- months builds in passes: the base row is 2026-01-01, then each pass takes
-- the previous pass's row and builds the next month from it (date(month_start,
-- '+1 month')), re-running against months's own growing output, until a
-- pass's output fails the WHERE condition and the recursion stops.
month_ranges AS (
SELECT month_start, date(month_start, '+1 month', '-1 day') AS month_end
FROM months
),
term AS (
SELECT
contract_id, start_date, end_date, total_amount,
julianday(end_date) - julianday(start_date) + 1 AS term_days
FROM contracts
),
alloc AS (
SELECT
t.contract_id,
mr.month_start,
MAX(t.start_date, mr.month_start) AS overlap_start,
MIN(t.end_date, mr.month_end) AS overlap_end,
julianday(MIN(t.end_date, mr.month_end))
- julianday(MAX(t.start_date, mr.month_start)) + 1 AS overlap_days,
t.total_amount, t.term_days
FROM term t
JOIN month_ranges mr
ON t.start_date <= mr.month_end AND t.end_date >= mr.month_start
)
SELECT
strftime('%Y-%m', month_start) AS month,
ROUND(SUM((total_amount / term_days) * overlap_days), 2) AS recognized_revenue
FROM alloc
WHERE overlap_days > 0
GROUP BY month
ORDER BY month;
Result:
┌─────────┬─────────────┬───────────────┬─────────────┬──────────────┬────────────┬────────────────────┐
│ month │ contract_id │ overlap_start │ overlap_end │ overlap_days │ daily_rate │ recognized_amount │
├─────────┼─────────────┼───────────────┼─────────────┼──────────────┼────────────┼────────────────────┤
│ 2026-01 │ C1 │ 2026-01-15 │ 2026-01-31 │ 17.0 │ 100.0 │ 1700.0 │
│ 2026-02 │ C1 │ 2026-02-01 │ 2026-02-28 │ 28.0 │ 100.0 │ 2800.0 │
│ 2026-02 │ C2 │ 2026-02-01 │ 2026-02-28 │ 28.0 │ 100.0 │ 2800.0 │
│ 2026-03 │ C1 │ 2026-03-01 │ 2026-03-14 │ 14.0 │ 100.0 │ 1400.0 │
│ 2026-03 │ C3 │ 2026-03-10 │ 2026-03-31 │ 22.0 │ 100.0 │ 2200.0 │
│ 2026-04 │ C3 │ 2026-04-01 │ 2026-04-09 │ 9.0 │ 100.0 │ 900.0 │
└─────────┴─────────────┴───────────────┴─────────────┴──────────────┴────────────┴────────────────────┘
-- Portfolio total recognized revenue per month --
┌─────────┬────────────────────┐
│ month │ recognized_revenue │
├─────────┼────────────────────┤
│ 2026-01 │ 1700.0 │
│ 2026-02 │ 5600.0 │
│ 2026-03 │ 3600.0 │
│ 2026-04 │ 900.0 │
└─────────┴────────────────────┘
Contract C1 runs January 15 through March 14, a 59-day, $5,900 term, exactly $100/day. January gets 17 days ($1,700, Jan 15-31), February gets the full 28 days ($2,800), March gets 14 days ($1,400, March 1-14). Those three pieces sum back to exactly $5,900, confirming no revenue was lost or double-counted at the boundaries. C3 (March 10 to April 9, $3,100, also $100/day) similarly splits into $2,200 in March and $900 in April. Portfolio totals per month: January $1,700; February $5,600 (C1 + C2); March $3,600 (C1's tail plus C3's start); April $900 (C3's tail).
The same technique, reframed
This overlap-day allocation is a general tool, not a one-off trick for "recognized revenue per month." The identical technique answers several sibling questions you may be asked instead:
- Deferred revenue balance: instead of summing recognized days, sum the unrecognized days remaining on each contract as of a snapshot date (
term_daysminus days elapsed so far), timesdaily_rate. This gives the balance-sheet liability at that point in time, not the income-statement flow. - Forward-looking forecast: run the exact same monthly bucketing, but for months that haven't happened yet, to project how much of each currently-signed contract's revenue will recognize in future periods.
- ACV and backlog bucketing: the same straight-line allocation idea applied to annual contract value (ACV) or to backlog, spreading the total contracted value into monthly (or quarterly) buckets the same overlap-based way, rather than into GAAP-recognized revenue specifically.
Trade-offs & pitfalls
- Complexity: the month-generation CTE is O(months in range); the contract-month join is O(contracts x overlapping months), cheap for a normal-sized contract book, but a contract with a multi-year term joins against many month rows, worth watching if contracts can run 5+ years.
- Edge cases: a contract that starts and ends within the same month (
overlap_daysequals the fullterm_days; the join conditionstart <= month_end AND end >= month_startstill catches it correctly); a 1-day contract term (term_days = 1,daily_rate = total_amount, no special case needed, the formula still works); contract amendments that changetotal_amountor dates mid-term retroactively (this model assumes the current row is authoritative for the whole historical term; a real system needs an effective-dated amendments table, not just an in-placeUPDATE). - Common wrong turn: prorating by months instead of by days, that is, dividing
total_amountevenly across however many calendar months the contract touches, ignoring that touching a month for 3 days versus 28 days shouldn't recognize the same amount. This is the single most common shortcut that produces materially wrong numbers for any contract with a mid-month boundary. - Reconciliation: this recognized-revenue schedule should tie out to the deferred revenue balance on the general ledger (unrecognized-to-date should always equal total contract value minus recognized-to-date). If it doesn't reconcile, look first for cents-level rounding applied per row rather than aggregating everything before rounding once.
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.