Skip to content

SQL for Data Science Interview Questions for Data Science

35 SQL for Data Science questions with answers for data science roles — 12 easy, 17 medium, 6 hard.

About SQL for Data Science

SQL rounds test whether you can pull and shape data yourself: joins, aggregations, window functions, CTEs, retention and funnel queries, and debugging wrong numbers. Most data science interviews in India include a live SQL test, often the first technical screen. Clean, correct SQL with careful handling of duplicates and NULLs makes a strong impression.

Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

What is the difference between WHERE and HAVING in SQL?

Save to ▾
Show answer
WHERE filters individual rows before grouping, so it cannot use aggregate functions. HAVING filters groups after GROUP BY and can use aggregates. Example: WHERE order_date >= '2026-01-01' keeps only this year's orders, then GROUP BY customer_id HAVING SUM(amount) > 10000 keeps customers who spent more than 10,000. Filtering early with WHERE is also faster because fewer rows are grouped.
02

Explain INNER, LEFT, RIGHT and FULL OUTER joins.

Save to ▾
Show answer
An INNER JOIN returns only rows with matching keys in both tables. A LEFT JOIN returns all rows from the left table, with NULLs where the right has no match. A RIGHT JOIN is the mirror of that. A FULL OUTER JOIN returns all rows from both sides, matched where possible. In analytics, LEFT JOIN from a customers table is common so customers with no orders are still counted.
03

What are window functions in SQL?

Save to ▾
Show answer
Window functions compute a value for each row using a set of related rows, without collapsing them like GROUP BY does. They use OVER with optional PARTITION BY and ORDER BY. Examples are ROW_NUMBER for ranking, SUM OVER for running totals, LAG and LEAD for previous and next values, and AVG over a frame for moving averages. They are central to data science SQL interviews.
04

What is the difference between ROW_NUMBER, RANK and DENSE_RANK?

Save to ▾
Show answer
All three number rows within a window ordered by some column. ROW_NUMBER gives unique numbers even for ties: 1, 2, 3. RANK gives tied rows the same rank and skips the next numbers: 1, 1, 3. DENSE_RANK gives ties the same rank without gaps: 1, 1, 2. Use ROW_NUMBER to pick exactly one row per group, and DENSE_RANK for questions like the second highest distinct salary.
05

Write SQL to find the second highest salary in an employees table.

Save to ▾
Show answer
SELECT MAX(salary) AS second_highest FROM employees WHERE salary < (SELECT MAX(salary) FROM employees); -- alternative with window function SELECT DISTINCT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees) t WHERE rnk = 2;
06

Write SQL to find duplicate emails in a users table.

Save to ▾
Show answer
SELECT email, COUNT(*) AS cnt FROM users GROUP BY email HAVING COUNT(*) > 1 ORDER BY cnt DESC;
07

What is the logical order of execution of a SQL query?

Save to ▾
Show answer
Although you write SELECT first, the database logically processes FROM and JOIN first, then WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and finally LIMIT. This explains common errors: you cannot use a SELECT alias in WHERE because WHERE runs before SELECT, but you can use it in ORDER BY. Window functions are computed after WHERE and GROUP BY, so filter on them in an outer query.
08

What is the difference between COUNT(*), COUNT(column) and COUNT(DISTINCT column)?

Save to ▾
Show answer
COUNT(*) counts all rows, including rows with NULLs. COUNT(column) counts only rows where that column is not NULL. COUNT(DISTINCT column) counts unique non-NULL values. For example, in an orders table, COUNT(*) is the number of orders, COUNT(coupon_code) is orders that used a coupon, and COUNT(DISTINCT customer_id) is the number of unique buyers. Mixing them up is a common reporting bug.
09

What is the difference between UNION and UNION ALL?

Save to ▾
Show answer
Both stack the results of two queries with the same number and type of columns. UNION removes duplicate rows, which needs an extra sort or hash step and is slower. UNION ALL keeps every row, including duplicates, and is faster. Use UNION ALL by default when you know the sets do not overlap or when duplicates matter, such as combining transaction logs from two systems.
10

Write SQL to pivot order counts by status into columns using CASE WHEN.

Save to ▾
Show answer
SELECT DATE_TRUNC('month', order_date) AS month, SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered, SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled, SUM(CASE WHEN status = 'returned' THEN 1 ELSE 0 END) AS returned FROM orders GROUP BY 1 ORDER BY 1;
11

Tell me about a time you found a data quality issue using SQL.

Save to ▾
Show answer
Situation: during my internship I was building a monthly sales report. Task: make sure numbers were correct before sharing. Action: I compared order counts per day and noticed one day had double the usual orders. A GROUP BY on order_id showed every order that day appeared twice because a load job had run twice. Result: I reported it, the data team removed duplicates and added a uniqueness check. Now I always validate row counts.
12

Tell me about a time you created documentation that helped your team work with data.

Save to ▾
Show answer
Situation: new analysts kept misusing two similar revenue columns. Task: reduce repeated questions and errors. Action: I wrote a short data dictionary for our main tables, with definitions, known pitfalls and sample queries, and linked it in the team wiki and onboarding checklist. I updated it whenever schemas changed. Result: onboarding time dropped, and the number of revenue mismatches in reports fell noticeably within a quarter.
13

Write SQL to find the top 3 products by revenue in each category.

Save to ▾
Show answer
WITH rev AS ( SELECT category, product_id, SUM(price * qty) AS revenue FROM order_items GROUP BY category, product_id ), ranked AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) AS rn FROM rev ) SELECT category, product_id, revenue FROM ranked WHERE rn <= 3;
14

Write SQL to compute a 7-day rolling average of daily active users.

Save to ▾
Show answer
WITH daily AS ( SELECT activity_date, COUNT(DISTINCT user_id) AS dau FROM events GROUP BY activity_date ) SELECT activity_date, dau, AVG(dau) OVER (ORDER BY activity_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS dau_7d_avg FROM daily ORDER BY activity_date;
15

Write SQL to calculate month-over-month revenue growth.

Save to ▾
Show answer
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)) / NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 2) AS mom_pct FROM monthly;
16

What is a CTE and what is a recursive CTE?

Save to ▾
Show answer
A CTE, common table expression, is a named temporary result defined with WITH and used in the query that follows. It breaks complex SQL into readable steps and can be referenced more than once. A recursive CTE refers to itself: an anchor query starts the result and a recursive part keeps adding rows until none are added. It is used for hierarchies like employee-manager chains or generating date series.
17

You added an index but the query is still slow. How do indexes work, and when do they fail to help or even hurt?

Save to ▾
Show answer
An index is a separate sorted structure, usually a B-tree, that lets the database find rows without scanning the whole table, like a book index. It speeds up filters, joins and sorting on the indexed columns. Indexes cost storage and slow down inserts, updates and deletes because each index must be updated. They may be ignored for low-selectivity columns or when a function is applied to the column in WHERE.
18

A query using NOT IN returns zero rows even though matches should exist. What is the likely cause, and how do NULLs behave in SQL?

Save to ▾
Show answer
NULL means unknown, so any comparison with NULL, even NULL = NULL, gives unknown and the row is filtered out. Use IS NULL or IS NOT NULL instead. Aggregates like SUM, AVG and COUNT(column) skip NULLs, so AVG may be computed over fewer rows than you expect. NOT IN with a subquery that contains a NULL returns no rows. COALESCE replaces NULLs with a default value.
19

After joining orders with a promotions table, total revenue doubled. What went wrong?

Save to ▾
Show answer
The join created duplicate order rows, because some orders match more than one promotion row, so each amount is counted several times. Check by comparing COUNT(*) with COUNT(DISTINCT order_id) after the join. Fix it by aggregating the promotions table to one row per order first, picking one promotion with ROW_NUMBER, or summing revenue before the join. Always check row counts after every join.
20

Write SQL to find customers who ordered in January 2026 but not in February 2026.

Save to ▾
Show answer
SELECT DISTINCT o.customer_id FROM orders o WHERE o.order_date >= '2026-01-01' AND o.order_date < '2026-02-01' AND NOT EXISTS ( SELECT 1 FROM orders f WHERE f.customer_id = o.customer_id AND f.order_date >= '2026-02-01' AND f.order_date < '2026-03-01' );
21

What is normalisation, and why are analytics tables often denormalised?

Save to ▾
Show answer
Normalisation splits data into related tables to remove redundancy, so each fact is stored once, which suits transactional systems with many updates. Analytics workloads mostly read large volumes, and joins across many tables are slow and error-prone. So warehouses often use denormalised, wide tables or star schemas that repeat some attributes. The trade-off is more storage and the need to keep copies consistent through pipelines.
22

What is the difference between a star schema and a snowflake schema?

Save to ▾
Show answer
A star schema has a central fact table, like sales with amounts and foreign keys, surrounded by denormalised dimension tables such as product, customer and date. A snowflake schema normalises dimensions further, for example product links to a separate category table. Star schemas need fewer joins and are faster and simpler for analysts. Snowflake schemas save storage and reduce duplication but make queries more complex.
23

Tell me about a time you had to deliver data under an urgent deadline.

Save to ▾
Show answer
Situation: the leadership team needed festive-sale numbers by city for a 9 am review, and the dashboard pipeline had failed overnight. Task: deliver accurate numbers in three hours. Action: I queried the raw orders tables directly, reused validated logic from the dashboard SQL, cross-checked totals with finance's daily figure and flagged two cities with partial data. Result: the review went ahead on time, and I later added pipeline failure alerts.
24

How do you pull large data from a SQL database into Pandas efficiently?

Save to ▾
Show answer
Push as much work as possible into SQL: filter, aggregate and select only needed columns before pulling. Use pd.read_sql with a SQLAlchemy engine and chunksize to stream large results. For very large extracts, export to Parquet from the warehouse and read that, which is much faster than row-by-row transfer. Set dtypes like category early, and never use SELECT star on a big table from a notebook.
25

Write SQL to compute a running total of spend for each user.

Save to ▾
Show answer
SELECT user_id, order_date, amount, SUM(amount) OVER ( PARTITION BY user_id ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS running_spend FROM orders ORDER BY user_id, order_date;
26

Your SQL result does not match the number on the official dashboard. How do you resolve it?

Save to ▾
Show answer
I would first align definitions: date range, time zone, filters like test users or cancelled orders, and whether the metric counts users or events. Then compare at a smaller grain, by day or by city, to find where the gap starts. I would read the dashboard's underlying query and check data refresh times. Once found, I would document the agreed definition so the same mismatch does not repeat.
27

What is the difference between a subquery and a correlated subquery?

Save to ▾
Show answer
A normal subquery runs once on its own and its result is used by the outer query, for example WHERE price > (SELECT AVG(price) FROM products). A correlated subquery refers to columns of the outer query, so it is logically evaluated once per outer row, for example comparing each product with its own category average. Correlated subqueries can be slow; joins or window functions are usually faster alternatives.
28

Describe a time you had to push back on or prioritise many ad-hoc data requests.

Save to ▾
Show answer
Situation: as the only analyst for three teams, I received 15 ad-hoc SQL requests a week and my model work stalled. Task: protect focus without upsetting stakeholders. Action: I grouped requests, built a self-serve dashboard covering the 5 most common questions, and set up a simple weekly priority review with the managers. Result: ad-hoc requests dropped by 60 percent and the model shipped a month later as planned.
29

Write SQL to show each customer's first order date, last order date and the gap between them in days.

Save to ▾
Show answer
SELECT customer_id, MIN(order_date) AS first_order, MAX(order_date) AS last_order, MAX(order_date) - MIN(order_date) AS days_between, COUNT(*) AS orders FROM orders GROUP BY customer_id ORDER BY days_between DESC; -- PostgreSQL: DATE minus DATE gives days; use DATEDIFF in other engines
30

A query on a 200 million row table takes 20 minutes. How do you speed it up?

Save to ▾
Show answer
Start with EXPLAIN to see the plan and find full scans, bad joins or spills. Filter as early as possible and select only needed columns. Make sure the table is partitioned or clustered on the date column and that the query filters on it. Check join keys for type mismatches and duplicates that explode rows. Pre-aggregate into a summary table if the query runs daily, and replace correlated subqueries with joins or window functions.
31

Write SQL to compute week-1 retention by signup week.

Save to ▾
Show answer
WITH signups AS ( SELECT user_id, DATE_TRUNC('week', signup_date) AS cohort, signup_date FROM users ), active AS ( SELECT DISTINCT s.user_id, s.cohort FROM signups s JOIN events e ON e.user_id = s.user_id AND e.event_date >= s.signup_date + INTERVAL '7 day' AND e.event_date < s.signup_date + INTERVAL '14 day' ) SELECT s.cohort, COUNT(*) AS users, ROUND(100.0 * COUNT(a.user_id) / COUNT(*), 1) AS week1_retention_pct FROM signups s LEFT JOIN active a ON a.user_id = s.user_id GROUP BY s.cohort ORDER BY s.cohort;
32

Write SQL to find the median order value per city.

Save to ▾
Show answer
SELECT city, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY amount) AS median_amount FROM orders GROUP BY city; -- PERCENTILE_CONT interpolates; PERCENTILE_DISC returns an actual value
33

Write SQL to compute funnel conversion from visit to cart to purchase.

Save to ▾
Show answer
WITH steps AS ( SELECT user_id, MAX(CASE WHEN event = 'visit' THEN 1 ELSE 0 END) AS visited, MAX(CASE WHEN event = 'add_to_cart' THEN 1 ELSE 0 END) AS carted, MAX(CASE WHEN event = 'purchase' THEN 1 ELSE 0 END) AS purchased FROM events WHERE event_date >= '2026-10-01' GROUP BY user_id ) SELECT SUM(visited) AS visits, SUM(carted) AS carts, SUM(purchased) AS buyers, ROUND(100.0 * SUM(carted) / NULLIF(SUM(visited), 0), 1) AS visit_to_cart_pct, ROUND(100.0 * SUM(purchased) / NULLIF(SUM(carted), 0), 1) AS cart_to_buy_pct FROM steps;
34

Write SQL to find users who logged in on at least three consecutive days.

Save to ▾
Show answer
WITH d AS ( SELECT DISTINCT user_id, CAST(login_at AS DATE) AS day FROM logins ), g AS ( SELECT user_id, day, day - CAST(ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) AS INT) AS grp FROM d ) SELECT DISTINCT user_id FROM g GROUP BY user_id, grp HAVING COUNT(*) >= 3; -- date minus row number is constant within a streak (PostgreSQL syntax)
35

Every time you rerun yesterday's report, the count of new users changes. What is going on and how do you fix it?

Save to ▾
Show answer
Likely causes are late-arriving events, deduplication running after your query, time zone boundaries or records being updated. First compare runs to see which rows change. Then define the metric on a stable basis: use event time with a fixed cut-off, wait for a data freshness window before publishing, and snapshot the result. Document whether numbers are provisional, and make pipelines idempotent so reruns give the same answer.

Frequently asked questions

How important is SQL for Data Science in Data Science interviews?

SQL rounds test whether you can pull and shape data yourself: joins, aggregations, window functions, CTEs, retention and funnel queries, and debugging wrong numbers. Most data science interviews in India include a live SQL test, often the first technical screen. Clean, correct SQL with careful handling of duplicates and NULLs makes a strong impression.

How should I use the SQL for Data Science sheet?

Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.