25 SQL Interview Questions for Data Analyst and Data Scientist Jobs (With Answers)
On this page
Short answer: SQL interviews for data analyst and data scientist roles usually test five areas: (1) basic querying and filtering, (2) aggregation with GROUP BY and HAVING, (3) JOINs and NULL handling, (4) subqueries and CTEs, and (5) window functions such as ROW_NUMBER, RANK and LAG, often through business-style problems like “top 3 products per category” or “month-over-month growth”. Below are 25 commonly asked questions with concise answers and example queries.
Key takeaways
- Expect both theory and live query writing, often on a shared screen or online test.
- JOINs, GROUP BY and window functions appear in most data interviews.
- Explain your thinking aloud: clarify assumptions, then write the query.
- Practise on a realistic schema (customers, orders, products), not just isolated syntax.
Examples use MySQL-style syntax and a simple schema: customers(customer_id, name, city, signup_date), orders(order_id, customer_id, order_date, amount, status), products(product_id, category, product_name), order_items(order_id, product_id, quantity, price).
Basic SQL interview questions
1. What is the difference between WHERE and HAVING?
WHERE filters rows before grouping. HAVING filters groups after aggregation. Use HAVING for conditions on aggregates such as SUM or COUNT.
SELECT customer_id, SUM(amount) AS total
FROM orders
WHERE status = 'completed'
GROUP BY customer_id
HAVING SUM(amount) > 10000;
2. What is the logical order of execution of a SQL query?
FROM / JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT. This explains why you usually can’t use a SELECT alias inside WHERE.
3. What is the difference between DELETE, TRUNCATE and DROP?
DELETE removes selected rows (can use WHERE). TRUNCATE removes all rows quickly but keeps the table structure. DROP removes the table entirely.
4. What is the difference between UNION and UNION ALL?
UNION removes duplicate rows. UNION ALL keeps all rows and is faster because it skips duplicate removal.
5. What are primary keys and foreign keys?
A primary key uniquely identifies each row in a table. A foreign key in one table references the primary key of another, enforcing relationships (for example, orders.customer_id → customers.customer_id).
JOIN interview questions
6. Explain INNER, LEFT, RIGHT and FULL OUTER JOIN.
| Join | Returns |
|---|---|
| INNER JOIN | Only rows with matches in both tables |
| LEFT JOIN | All rows from the left table, matched rows from the right (NULL if none) |
| RIGHT JOIN | All rows from the right table, matched rows from the left |
| FULL OUTER JOIN | All rows from both tables (MySQL doesn’t support it directly; combine LEFT and RIGHT joins with UNION) |
7. Find customers who have never placed an order.
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;
8. What is a self join? Give an example.
A self join joins a table to itself, for example matching employees to their managers in an employees(emp_id, name, manager_id) table:
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.emp_id;
9. Why can a JOIN increase the number of rows unexpectedly?
When joining one-to-many tables (one customer, many orders), each matching row is repeated. Aggregating after such a join can double-count values. Aggregate first in a subquery or CTE, then join.
Aggregation and NULL questions
10. What is the difference between COUNT(*), COUNT(column) and COUNT(DISTINCT column)?
COUNT(*) counts all rows. COUNT(column) counts non-NULL values. COUNT(DISTINCT column) counts unique non-NULL values.
11. How do NULLs behave in comparisons and aggregates?
Comparisons with NULL (= NULL) return unknown, so use IS NULL / IS NOT NULL. Aggregates like SUM and AVG ignore NULLs. Use COALESCE(column, 0) to replace NULLs when appropriate.
12. Find the total revenue and number of orders per city.
SELECT c.city, COUNT(o.order_id) AS orders, SUM(o.amount) AS revenue
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE o.status = 'completed'
GROUP BY c.city
ORDER BY revenue DESC;
13. Find duplicate email addresses in a users table.
SELECT email, COUNT(*) AS cnt
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
Subqueries and CTE questions
14. What is the difference between a subquery and a CTE?
Both create intermediate results. A CTE (WITH ...) is named and defined at the top, making multi-step logic easier to read and reuse within the query. A correlated subquery runs once per outer row and can be slower.
15. Find customers whose total spend is above the average customer spend.
WITH spend AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
)
SELECT customer_id, total
FROM spend
WHERE total > (SELECT AVG(total) FROM spend);
16. Find the second-highest order amount.
SELECT MAX(amount) AS second_highest
FROM orders
WHERE amount < (SELECT MAX(amount) FROM orders);
With window functions you can generalise to the Nth highest (see question 19).
Window function interview questions
17. What is a window function?
A window function performs a calculation across a set of rows related to the current row without collapsing them like GROUP BY does. It uses OVER (PARTITION BY ... ORDER BY ...).
18. What is the difference between ROW_NUMBER, RANK and DENSE_RANK?
| Values | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 500 | 1 | 1 | 1 |
| 500 | 2 | 1 | 1 |
| 400 | 3 | 3 | 2 |
19. Find the top 3 products by revenue in each category.
WITH product_sales AS (
SELECT p.category, p.product_name,
SUM(oi.quantity * oi.price) AS revenue
FROM order_items oi
JOIN products p ON p.product_id = oi.product_id
GROUP BY p.category, p.product_name
), ranked AS (
SELECT *, DENSE_RANK() OVER (PARTITION BY category ORDER BY revenue DESC) AS rnk
FROM product_sales
)
SELECT category, product_name, revenue
FROM ranked
WHERE rnk <= 3;
20. Calculate month-over-month revenue growth.
WITH monthly AS (
SELECT DATE_FORMAT(order_date, '%Y-%m') AS month, SUM(amount) AS revenue
FROM orders
GROUP BY month
)
SELECT month, revenue,
ROUND(100 * (revenue - LAG(revenue) OVER (ORDER BY month))
/ LAG(revenue) OVER (ORDER BY month), 2) AS mom_growth_pct
FROM monthly;
21. Calculate a running total of revenue by date.
SELECT order_date,
SUM(amount) OVER (ORDER BY order_date) AS running_revenue
FROM orders;
If several orders share a date, aggregate by date first so each date appears once.
22. Find each customer’s first order.
SELECT *
FROM (
SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date) AS rn
FROM orders o
) t
WHERE rn = 1;
Scenario and performance questions
23. How would you calculate monthly active customers and retention?
Define “active” (for example, at least one completed order in the month), count distinct customers per month, then use each customer’s first-order month as a cohort and count how many return in later months. Interviewers mainly want to see how you define metrics clearly before writing SQL.
24. How can you make a slow query faster?
- Select only needed columns instead of
SELECT * - Filter early and on indexed columns
- Avoid functions on indexed columns in WHERE when possible
- Aggregate before joining large tables
- Check the execution plan (
EXPLAIN)
25. What is an index, and what is its trade-off?
An index is a data structure that speeds up lookups on specific columns, like a book’s index. The trade-off is extra storage and slower inserts and updates, because the index must be maintained.
How to prepare for SQL interviews
- Master the core: joins, GROUP BY/HAVING, CASE WHEN, NULL handling. Our SQL for Data Science guide lists exactly what to know.
- Practise window functions daily until ranking and LAG/LEAD feel natural.
- Solve business-style problems on a sample e-commerce schema.
- Talk through your approach: restate the question, define assumptions, then code.
- Check edge cases: ties, NULLs, duplicates, empty months.
SQL is one part of the interview process. See the full job-ready data scientist checklist and practise Python interview questions for data science too.
Frequently asked questions
Are SQL interview questions different for data analysts and data scientists?
The core is the same. Data analyst interviews often focus more on reporting queries and business metrics, while data scientist interviews may add feature-building and more complex analytical queries.
Which SQL database should I practise on?
MySQL or PostgreSQL are both fine. Core SQL is similar; just note small syntax differences such as date functions.
How many SQL questions should I practise before an interview?
Quality matters more than count. Make sure you can solve each pattern here (joins, aggregation, ranking, running totals, period comparisons) confidently and explain it.
Do I need to know database design for data analyst interviews?
Basic understanding of keys, relationships and normalisation is usually enough at entry level.
Conclusion
Most SQL interviews come down to a small set of patterns: filter, aggregate, join, rank and compare over time. Practise these 25 questions on a realistic dataset, explain your reasoning clearly, and you’ll be well prepared for data analyst and data scientist interviews.
Practise SQL with real business datasets in our MySQL course, or talk to Mehul about interview preparation.
Learn with Mehul Prajapati in Borivali West
At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.
Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072
Visit the centre or call us to choose the right course and batch and to know the current fee structure.