SQL for Data Science: The Queries Interviewers Actually Ask

The SQL patterns data science interviews in India test most — joins and anti-joins, grouping with HAVING, top N per group, running totals, month-on-month growth, cohort retention, duplicates and share of total — with tested queries, the traps interviewers set and a practice plan.

Quick Answer: SQL is the most consistent technical filter in data science and analyst interviews in India. A small set of patterns covers most questions: joins and anti-joins, grouping with HAVING, top N per group, running totals, period-on-period growth with LAG, cohort retention, duplicates and share of total. Master these with window functions, learn the traps around nulls, ties and integer division, and practise explaining your logic aloud.

Candidates preparing for data science roles often spend weeks on machine learning and a weekend on SQL. Interviewers know this, which is why SQL is so often the first technical round — and where many applications end. The good news is that interview SQL is predictable. A handful of patterns, combined in different ways, covers the large majority of questions.

Every query below was run against a small sample dataset to confirm it works. They use PostgreSQL- and DuckDB-style syntax; date functions differ slightly in MySQL and SQL Server, so check the equivalent in the dialect your target company uses.

The Sample Tables

All examples use two simple tables, similar to what an e-commerce interviewer would give you:

customers(customer_id, name, city, signup_date)
orders(order_id, customer_id, order_date, amount, category)

Nine Patterns That Cover Most Interview Questions

1. Find customers who never ordered (anti-join)

A favourite opener. A LEFT JOIN keeps every customer; those without a matching order have nulls on the order side.

SELECT c.customer_id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;
The trap: putting a condition on the right-hand table in the WHERE clause of a left join silently turns it into an inner join. Filters on the joined table usually belong in the ON clause.

2. Aggregate and filter groups with HAVING

Revenue and distinct buyers by city, keeping only cities above a threshold:

SELECT c.city, COUNT(DISTINCT o.customer_id) AS buyers, SUM(o.amount) AS revenue
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
GROUP BY c.city
HAVING SUM(o.amount) > 5000
ORDER BY revenue DESC;
The trap: WHERE filters rows before grouping; HAVING filters groups after. And COUNT(*) counts rows, while COUNT(DISTINCT customer_id) counts people — interviewers check you know which the question asks for.

3. Top N per group

The single most common window-function question: the top two customers by spend in each category.

WITH cust_cat AS (
  SELECT category, customer_id, SUM(amount) AS spend
  FROM orders
  GROUP BY category, customer_id
)
SELECT category, customer_id, spend
FROM (
  SELECT *, DENSE_RANK() OVER (PARTITION BY category ORDER BY spend DESC) AS rnk
  FROM cust_cat
) t
WHERE rnk <= 2
ORDER BY category, rnk;
The trap: know the difference between ROW_NUMBER (always unique), RANK (ties share a rank and leave gaps) and DENSE_RANK (ties share a rank, no gaps). Say which you chose and why; ask how ties should be handled.

4. Running totals

Cumulative revenue over time:

SELECT order_date, amount,
       SUM(amount) OVER (ORDER BY order_date, order_id) AS running_revenue
FROM orders
ORDER BY order_date, order_id;

Adding order_id to the ordering makes the result deterministic when two orders fall on the same date — a detail interviewers notice.

5. Month-on-month growth

Aggregate first, then compare each month with the previous one using LAG:

WITH monthly AS (
  SELECT DATE_TRUNC('month', order_date) AS month, SUM(amount) AS revenue
  FROM orders
  GROUP BY 1
)
SELECT month, revenue,
       LAG(revenue) OVER (ORDER BY month) AS prev_revenue,
       ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
             / LAG(revenue) OVER (ORDER BY month), 1) AS growth_pct
FROM monthly
ORDER BY month;
The trap: the first month has no previous value, so growth is null — say so rather than letting it look like an error. Also check for months with no orders at all, which disappear from a simple GROUP BY; a calendar table fixes that.

6. Cohort retention

Group customers by the month of their first order and count how many were active in each later month. This is a staple of product and e-commerce interviews.

WITH first_month AS (
  SELECT customer_id, DATE_TRUNC('month', MIN(order_date)) AS cohort
  FROM orders GROUP BY customer_id
),
activity AS (
  SELECT DISTINCT customer_id, DATE_TRUNC('month', order_date) AS active_month
  FROM orders
)
SELECT f.cohort,
       DATE_DIFF('month', f.cohort, a.active_month) AS months_since_first,
       COUNT(DISTINCT a.customer_id) AS active_customers
FROM first_month f
JOIN activity a ON a.customer_id = f.customer_id
GROUP BY 1, 2
ORDER BY 1, 2;

From here, dividing each row by the cohort's month-zero count gives retention percentages. Explaining the logic step by step matters more than writing it in one attempt.

7. Find duplicate records

SELECT customer_id, order_date, amount, COUNT(*) AS copies
FROM orders
GROUP BY customer_id, order_date, amount
HAVING COUNT(*) > 1;

Follow-up questions usually ask how you would delete duplicates while keeping one copy — typically with ROW_NUMBER() partitioned by the duplicate columns, keeping row number one.

8. Share of total

A window function over an aggregate gives each category's percentage of overall revenue in one query:

SELECT category,
       SUM(amount) AS revenue,
       ROUND(100.0 * SUM(amount) / SUM(SUM(amount)) OVER (), 1) AS pct_of_total
FROM orders
GROUP BY category
ORDER BY revenue DESC;
The trap: integer division. Multiplying by 100.0 rather than 100 forces decimal arithmetic in databases that would otherwise round to whole numbers.

9. First and last activity per customer

SELECT customer_id,
       MIN(order_date) AS first_order,
       MAX(order_date) AS last_order,
       DATE_DIFF('day', MIN(order_date), MAX(order_date)) AS days_active
FROM orders
GROUP BY customer_id
ORDER BY customer_id;

A simple pattern that feeds recency features for churn models and "days since last order" metrics in dashboards.

How SQL Actually Executes

Many errors disappear once you know the logical order in which a query is processed: FROM and JOIN, then WHERE, then GROUP BY, then HAVING, then window functions, then SELECT, then DISTINCT, then ORDER BY, then LIMIT. That is why you cannot use a column alias from SELECT in WHERE, why you cannot filter on a window function directly in WHERE — you wrap it in a subquery or common table expression, as in the top N example — and why aggregate conditions belong in HAVING.

Null Handling: The Quiet Source of Wrong Answers

Nulls behave differently from zeros and empty strings. Any comparison with null returns unknown, so WHERE amount != 0 excludes null amounts as well. Aggregates such as SUM and AVG ignore nulls, which changes averages. COUNT(column) skips nulls while COUNT(*) does not. COALESCE replaces nulls with a default when that is the right business choice. Mentioning these behaviours unprompted is one of the clearest signs of real experience.

How to Approach a Live SQL Question

First, restate the question and ask about edge cases: how to treat ties, cancelled orders, nulls, customers with no activity, and the time zone of dates. Second, describe the plan in plain words — "aggregate by month, then compare with the previous month" — before typing. Third, build the query in steps, often with common table expressions, which are easier to read and debug than deeply nested subqueries. Fourth, sanity-check the result: do the totals add up, are row counts plausible, did a join multiply rows unexpectedly?

Interviewers frequently care more about this process than about perfect syntax. A candidate who explains clearly and fixes a small mistake often scores better than one who types a correct query in silence.

Performance Questions for Experienced Candidates

For mid-level roles, expect questions about efficiency: why selecting only needed columns matters, how indexes help filters and joins, why functions applied to an indexed column in a filter can prevent the index from being used, when to pre-aggregate before joining large tables, and how to read a query plan at a basic level. In cloud data warehouses, partitioning and clustering by date are common follow-ups.

A Two-Week SQL Practice Plan

Days 1–3: joins of every type, including anti-joins and self-joins; grouping, HAVING and conditional aggregation with CASE.

Days 4–7: window functions — ranking, LAG and LEAD, running totals, moving averages and share of total. Solve several top N per group variants.

Days 8–10: dates and time — truncation, differences, month-on-month and year-on-year comparisons, cohorts and retention.

Days 11–14: mixed timed problems on realistic schemas, explained aloud, plus a review of null behaviour and execution order. Recreate the patterns above from memory.

Practise on realistic multi-table data rather than single toy tables, and write every solution yourself before checking any answer.

Practice Problems to Try Yourself

Using the same two tables, try these without looking anything up. Each combines the patterns above in a way interviewers like:

1. For each city, find the customer with the highest single order, including ties.
2. Calculate each customer's average gap in days between consecutive orders.
3. Show monthly revenue alongside a three-month moving average.
4. Find customers whose spend in March was higher than in February.
5. For each category, show the share of revenue coming from repeat customers versus first-time buyers.
6. List customers who ordered in every month from January to March.
7. Find the first category each customer ever bought from.
8. Delete exact duplicate orders while keeping one copy of each.

Write your answer, run it on a small dataset you create, and then explain it aloud as if to an interviewer. If you cannot explain why a line is there, you do not yet own the solution.

Mistakes Interviewers See Again and Again

Joining tables at different grains — orders to order items, say — and then summing a header-level amount, which multiplies revenue. Forgetting that an inner join drops customers with no activity. Using ROW_NUMBER when the question expects ties to be kept. Filtering a window function in WHERE. Grouping by a date-time instead of a truncated date and getting one row per order. And never checking the output, so an obviously wrong total goes unnoticed. Each one is easy to avoid once you know to look for it, and saying "let me check this isn't double counting" during an interview earns real credit.

Where SQL Fits in Your Preparation

SQL sits alongside Python, statistics and machine learning as one of the four pillars of data science interviews, and it is often the one that decides whether you reach the others. Our Data Science course teaches SQL on realistic business datasets with interview-style practice, alongside Python and statistics. For candidates moving into modelling, the Machine Learning course builds on these foundations.

People Also Ask / FAQ

How much SQL does a data scientist need?

Enough to write joins, aggregations, window functions and date logic fluently on multi-table data. Database administration is not required.

Which SQL dialect should I learn?

Any mainstream one — PostgreSQL and MySQL are common choices. Core syntax is shared; learn the date functions of the dialect your target companies use.

Are window functions really asked in interviews?

Yes, very often — especially ranking within groups, LAG for period comparisons and running totals.

Should I use subqueries or CTEs?

Either works. Common table expressions are usually easier to read and explain in an interview, which is a real advantage.

Is SQL still relevant with AI tools that write queries?

Yes. AI can draft queries, but you must judge whether they are correct, efficient and answer the real question — which requires solid SQL knowledge.

Master SQL for Data Science Interviews

Live classes, real datasets and interview practice — online and in select cities across India Explore the Data Science Course