Your first Data Analyst SQL round rarely stops at SELECT and WHERE. Interviewers push into joins across messy tables, business metrics like retention and churn, and open-ended problems you have not seen before. This blog covers 50 SQL interview questions for Data Analysts, grouped into foundational, intermediate, and advanced levels, with answers, runnable queries, and the reasoning interviewers actually score. If you are still mapping the wider path, start with our Data Analyst career path guide and the data analytics learning roadmap.
Key Takeaways
- Data Analyst SQL interviews test problem-solving and reasoning, not memorized syntax.
- The heaviest-weighted topics are joins, window functions, and business-metric queries such as retention, churn, and growth. Together they account for roughly 58% of questions.
- Freshers should master joins, GROUP BY, subqueries, and NULL handling first, then move to window functions and time-series analysis.
- This guide covers 50 questions across three levels, each with an answer, a sample query, and expected output where it helps.
Table of Contents
- SQL interview questions at a glance
- Foundational questions (Q1 to Q14)
- Intermediate questions (Q15 to Q30)
- Advanced questions (Q31 to Q50)
- What companies look for in Data Analyst SQL interviews
- Common SQL interview mistakes to avoid
- Frequently asked questions
SQL Interview Questions at a Glance
The table below shows where questions cluster, so you know where to spend preparation time. The estimate is based on our research for publicly available interview questions from platforms like Glassdoor, AmbitionBox, & LinkedIn.
| SQL Interview Topic | Interview Weightage |
|---|---|
| Advanced Analytics & Window Functions | 20% |
| Joins, Set Operations & Data Merging | 20% |
| Business Metrics & Time-Series Analysis | 18% |
| Aggregation, Filtering & Conditional Logic | 12% |
| CTEs, Subqueries & Query Architecture | 12% |
| Data Cleaning & Standardization | 8% |
| SQL Fundamentals & Data Types | 5% |
| Performance, Indexes & Optimization | 5% |
Foundational SQL Interview Questions for Freshers
1. What is SQL, and why is it important for Data Analysts?
SQL (Structured Query Language) is used to retrieve, manipulate, and analyze data stored in relational databases. Data Analysts use SQL to extract datasets, filter records, combine tables, calculate metrics, and investigate business problems, which makes it the core tool for turning raw tables into answers.
2. What is the difference between a primary key and a foreign key?
| Primary Key | Foreign Key |
|---|---|
| Uniquely identifies a record | Creates a relationship between tables |
| Cannot contain duplicate values | Can contain duplicate values |
| Cannot contain NULL values | Can contain NULL values, depending on the design |
3. What are the commonly used SQL data types?
Common SQL data types include:
- INTEGER, whole numbers
- DECIMAL, precise numeric values
- VARCHAR, variable-length text
- CHAR, fixed-length text (pads to the defined length; use VARCHAR when length varies to save space)
- DATE, calendar dates
- TIMESTAMP, date and time
- BOOLEAN, true or false values
The exact data types and syntax can vary between SQL databases.
4. How do you filter records using WHERE in SQL?
The WHERE clause filters individual rows based on a specified condition.
SELECT employee_name, salary FROM employees WHERE salary > 50000;
This query returns employees whose salary is greater than 50,000.
5. What is the difference between WHERE and HAVING?
| WHERE | HAVING |
|---|---|
| Filters individual rows | Filters grouped results |
| Applied before aggregation | Applied after GROUP BY |
| Used for row-level conditions | Commonly used with aggregate conditions |
| Example: salary > 50000 | Example: AVG(salary) > 50000 |
6. How does GROUP BY work with aggregate functions?
GROUP BY collapses rows that share a value into one row per group, so aggregate functions return a result for each group.
SELECT department, AVG(salary) AS avg_salary FROM employees GROUP BY department;
Sample input (employees):
| department | salary |
|---|---|
| Sales | 40000 |
| Sales | 60000 |
| Tech | 90000 |
Expected output:
| department | avg_salary |
|---|---|
| Sales | 50000 |
| Tech | 90000 |
7. What are the commonly used aggregate functions in SQL?
The most commonly used aggregate functions are:
- COUNT(), counts records or values
- SUM(), calculates a total
- AVG(), calculates an average
- MIN(), returns the smallest value
- MAX(), returns the largest value
8. How is CASE WHEN used for conditional logic in SQL?
CASE WHEN applies conditional logic and returns different values based on specified conditions.
SELECT
employee_name,
salary,
CASE
WHEN salary >= 100000 THEN 'High'
WHEN salary >= 50000 THEN 'Medium'
ELSE 'Low'
END AS salary_category
FROM employees;9. How do you calculate conditional counts or sums using SQL?
Conditional aggregation combines aggregate functions with CASE WHEN, which is useful when several business metrics come from the same dataset.
SELECT
COUNT(CASE WHEN status = 'Completed' THEN 1 END) AS completed_orders,
SUM(CASE WHEN status = 'Completed' THEN amount ELSE 0 END) AS completed_revenue
FROM orders;10. How do you identify and handle NULL values in SQL?
NULL represents a missing or unknown value. Check it with IS NULL or IS NOT NULL, never with = NULL. COALESCE() can supply a default value when one is required.
SELECT * FROM customers WHERE phone_number IS NULL;
11. How do you find duplicate records in a SQL table?
Group the records by the column or combination of columns that should be unique, then filter groups with more than one occurrence.
SELECT email, COUNT(*) AS record_count FROM customers GROUP BY email HAVING COUNT(*) > 1;
12. How do you clean and standardize inconsistent data using SQL?
SQL string and conversion functions standardize values.
SELECT
TRIM(customer_name) AS clean_name,
UPPER(country) AS standardized_country
FROM customers;Common cleaning operations include removing unwanted spaces, standardizing text case, replacing missing values, converting data types, and standardizing categories.
13. What is normalization, and why does it matter for analysts?
Normalization organizes data to reduce redundancy and protect integrity. First Normal Form removes repeating groups, Second Normal Form removes partial dependencies, and Third Normal Form removes transitive dependencies. Analysts care because normalized schemas explain why data is split across tables and therefore why joins are needed. A related idea is ACID (atomicity, consistency, isolation, durability), the guarantees that keep transactional data reliable enough to report on.
14. What is the difference between DELETE, TRUNCATE, and DROP?
| DELETE | TRUNCATE | DROP |
|---|---|---|
| Removes rows that match a condition | Removes all rows | Removes the whole table |
| Can be rolled back | Harder or impossible to roll back | Removes structure and data |
| Keeps table structure | Keeps table structure | Table no longer exists |
| Slower, logs each row | Faster, minimal logging | Used to delete the object entirely |
Intermediate SQL Interview Questions for Data Analysts
15. What is a JOIN in SQL, and when is it used?
A JOIN combines records from two or more tables using a related column, and is used when the information an analysis needs is spread across multiple tables.
SELECT
c.customer_name,
o.order_id
FROM customers c
INNER JOIN orders o
ON c.customer_id = o.customer_id;16. What is the difference between INNER JOIN and LEFT JOIN?
| INNER JOIN | LEFT JOIN |
|---|---|
| Returns matching records from both tables | Returns all records from the left table |
| Unmatched records are excluded | Unmatched left-table records are retained |
| Useful when only matches are required | Useful when missing matches need to be identified |
17. What are RIGHT JOIN and FULL OUTER JOIN?
A RIGHT JOIN keeps all rows from the right table and matching rows from the left, the mirror image of a LEFT JOIN. A FULL OUTER JOIN keeps all rows from both tables, filling unmatched sides with NULL. FULL OUTER JOIN is useful for reconciliation, for example finding records present in either system but not both.
SELECT c.customer_id, o.order_id
FROM customers c
FULL OUTER JOIN orders o
ON c.customer_id = o.customer_id;18. How do you find customers who have never placed an order?
A LEFT JOIN with a NULL check identifies customers without a matching order.
SELECT c.customer_id, c.customer_name
FROM customers c
LEFT JOIN orders o
ON c.customer_id = o.customer_id
WHERE o.customer_id IS NULL;19. How do you join three or more tables in SQL?
Chain multiple JOIN clauses when data is distributed across several related tables. Each JOIN should have a clear relationship between the tables.
SELECT
c.customer_name,
o.order_id,
p.product_name
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
JOIN products p ON o.product_id = p.product_id;20. What is a SELF JOIN, and when would you use it?
A SELF JOIN joins a table to itself, commonly for hierarchical relationships such as employees and their managers.
SELECT
e.employee_name,
m.employee_name AS manager_name
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.employee_id;21. What is a CROSS JOIN, and what result does it produce?
A CROSS JOIN returns every possible combination of rows from two tables. If one table has 5 rows and another has 4, the result has 20 combinations. It is useful for building combinations such as products by region, dates by customer, or plans by pricing option.
22. What is the difference between UNION and UNION ALL?
| UNION | UNION ALL |
|---|---|
| Combines query results | Combines query results |
| Removes duplicate rows | Retains duplicate rows |
| May need extra processing to deduplicate | Usually requires less processing |
23. How do you identify and handle duplicate rows created by a JOIN?
Duplicates after a JOIN usually signal a one-to-many or many-to-many relationship rather than a need for DISTINCT. Check the relationship, identify the expected level of detail, confirm whether the join key is unique, aggregate where required, and use DISTINCT only when duplicate rows are genuinely unwanted.
24. What is a VIEW, and when would an analyst use one?
A VIEW is a virtual table defined by a saved query. It does not store data itself; it runs its query when referenced. Analysts use views to simplify repeated complex logic, present a clean table to reporting tools, and restrict which columns downstream users can see.
CREATE VIEW high_value_orders AS SELECT order_id, customer_id, amount FROM orders WHERE amount > 1000;
25. What is a subquery in SQL, and where can it be used?
A subquery is a query nested inside another SQL statement, usable in places such as WHERE, FROM, and SELECT.
SELECT employee_name, salary
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);26. What is a correlated subquery, and how is it different from a regular subquery?
A correlated subquery references a column from the outer query, so its result depends on the current row being processed. The example below finds employees earning more than the average salary of their own department.
SELECT e.employee_name, e.department, e.salary
FROM employees e
WHERE e.salary > (
SELECT AVG(e2.salary)
FROM employees e2
WHERE e2.department = e.department
);27. What is a Common Table Expression (CTE), and why is it useful?
A CTE creates a named temporary result that the main query can reference, which helps break complex queries into readable steps.
WITH department_sales AS (
SELECT department, SUM(sales) AS total_sales
FROM employees
GROUP BY department
)
SELECT *
FROM department_sales
WHERE total_sales > 100000;28. What is the difference between a CTE and a subquery?
| CTE | Subquery |
|---|---|
| Defined using WITH | Written directly inside the query |
| Easier to structure multi-step logic | Often convenient for smaller operations |
| Can improve readability | Can be more compact |
| Multiple CTEs can be chained | Nested subqueries can become harder to read |
29. What is the difference between IN and EXISTS in SQL?
| IN | EXISTS |
|---|---|
| Checks whether a value belongs to a set | Checks whether a matching row exists |
| Compares values | Tests for existence |
| Often useful with a list or subquery | Commonly used with correlated subqueries |
| Performance depends on data and structure | Performance depends on data and structure |
30. How would you find the second-highest salary in a table?
A subquery can find the highest salary first, then the maximum salary below it. This returns the second distinct highest salary.
SELECT MAX(salary) AS second_highest_salary
FROM employees
WHERE salary < (
SELECT MAX(salary)
FROM employees
);Advanced SQL Interview Questions for Data Analysts
31. What is a window function, and how is it different from GROUP BY?
A window function performs calculations across related rows while keeping the individual rows in the result. GROUP BY, by contrast, collapses rows into groups.
SELECT
employee_name,
department,
salary,
AVG(salary) OVER (PARTITION BY department) AS department_avg
FROM employees;32. What is the difference between ROW_NUMBER(), RANK(), and DENSE_RANK()?
| Function | Ties get same rank? | Gaps after ties? |
|---|---|---|
| ROW_NUMBER() | No | No |
| RANK() | Yes | Yes |
| DENSE_RANK() | Yes | No |
For salaries 100K, 100K, 90K the results are:
| Function | Result |
|---|---|
| ROW_NUMBER() | 1, 2, 3 |
| RANK() | 1, 1, 3 |
| DENSE_RANK() | 1, 1, 2 |
33. How would you find the top 3 highest-paid employees in each department, including ties?
DENSE_RANK() ranks employees within each department, and keeping ranks of 3 or less returns the top three including ties.
WITH ranked_employees AS (
SELECT
employee_name,
department,
salary,
DENSE_RANK() OVER (
PARTITION BY department ORDER BY salary DESC
) AS salary_rank
FROM employees
)
SELECT *
FROM ranked_employees
WHERE salary_rank <= 3;Sample input (Tech department):
| employee_name | salary |
|---|---|
| Asha | 120000 |
| Ravi | 120000 |
| Meena | 110000 |
| Sara | 90000 |
Expected output (salary_rank kept where <= 3):
| Employee_name | salary | salary_rank |
|---|---|---|
| Asha | 120000 | 1 |
| Ravi | 120000 | 1 |
| Meena | 110000 | 2 |
| Sara | 90000 | 3 |
34. How would you find the latest transaction for each customer?
ROW_NUMBER() assigns the most recent transaction a rank of 1 within each customer, and filtering for rank 1 returns it.
WITH ranked_transactions AS (
SELECT
customer_id,
transaction_id,
transaction_date,
ROW_NUMBER() OVER (
PARTITION BY customer_id ORDER BY transaction_date DESC
) AS rn
FROM transactions
)
SELECT *
FROM ranked_transactions
WHERE rn = 1;35. How do you calculate a running total using a window function?
A running total uses SUM() with an ordered window, so each row holds the accumulated value up to that point.
SELECT
order_date,
revenue,
SUM(revenue) OVER (ORDER BY order_date) AS running_revenue
FROM daily_sales;36. How do you compare each row with the previous row using LAG()?
LAG() retrieves a value from a previous row without a self-join, which you can then use to calculate change or growth.
SELECT
month,
revenue,
LAG(revenue) OVER (ORDER BY month) AS previous_revenue
FROM monthly_sales;37. How do you compare each row with the next row using LEAD()?
LEAD() retrieves a value from a subsequent row, useful for comparing current records with future periods.
SELECT
month,
revenue,
LEAD(revenue) OVER (ORDER BY month) AS next_month_revenue
FROM monthly_sales;38. How do you calculate a moving average using SQL?
A moving average uses AVG() with a window frame. The frame below covers the current month and the two preceding rows.
SELECT
month,
revenue,
AVG(revenue) OVER (
ORDER BY month
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS three_month_average
FROM monthly_sales;39. How do you calculate a rolling 3-month revenue metric?
After aggregating revenue by month, apply a SUM() window frame over the current and two preceding months.
WITH monthly_revenue AS (
SELECT month, SUM(revenue) AS revenue
FROM sales
GROUP BY month
)
SELECT
month,
revenue,
SUM(revenue) OVER (
ORDER BY month
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS rolling_3_month_revenue
FROM monthly_revenue;40. How do you calculate each product’s percentage contribution to total revenue?
Calculate revenue by product, then use a window function to divide each value by the overall total.
WITH product_revenue AS (
SELECT product_id, SUM(revenue) AS revenue
FROM sales
GROUP BY product_id
)
SELECT
product_id,
revenue,
revenue * 100.0 / SUM(revenue) OVER () AS revenue_percentage
FROM product_revenue;41. How would you find the median value of a column in SQL?
The median has no single standard function across databases, so a common approach numbers the rows in order and averages the middle one or two values.
WITH ordered AS (
SELECT
amount,
ROW_NUMBER() OVER (ORDER BY amount) AS rn,
COUNT(*) OVER () AS total
FROM sales
)
SELECT AVG(amount) AS median
FROM ordered
WHERE rn IN ((total + 1)/2, (total + 2)/2);For amounts 10, 20, 30, 40 the median returned is 25 (average of the two middle values).
42. How would you identify gaps or consecutive periods in user activity?
Consecutive-activity problems are solved with gaps-and-islands techniques. LAG() first compares each activity date with the previous date, and the resulting differences reveal breaks and streaks.
SELECT
user_id,
activity_date,
LAG(activity_date) OVER (
PARTITION BY user_id ORDER BY activity_date
) AS previous_activity_date
FROM user_activity;43. How would you calculate month-over-month revenue growth?
Aggregate revenue by month, use LAG() to retrieve the previous month, then compute the percentage change.
WITH monthly_revenue AS (
SELECT month, SUM(revenue) AS revenue
FROM sales
GROUP BY month
)
SELECT
month,
revenue,
LAG(revenue) OVER (ORDER BY month) AS previous_revenue,
ROUND(
(revenue - LAG(revenue) OVER (ORDER BY month))
* 100.0 / LAG(revenue) OVER (ORDER BY month),
1
) AS mom_growth_pct
FROM monthly_revenue;Expected output:
| month | revenue | previous_revenue | mom_growth_pct |
|---|---|---|---|
| Jan | 10000 | NULL | NULL |
| Feb | 12000 | 10000 | 20.0 |
| Mar | 9000 | 12000 | -25.0 |
44. How would you calculate year-over-year sales growth?
Aggregate sales by year and compare each year with the previous year using LAG(), then convert the difference into a percentage.
WITH yearly_sales AS (
SELECT year, SUM(sales) AS total_sales
FROM orders
GROUP BY year
)
SELECT
year,
total_sales,
LAG(total_sales) OVER (ORDER BY year) AS previous_year_sales
FROM yearly_sales;45. Which date and time functions are most useful for analysts?
Analysts constantly bucket and difference dates. The exact names vary by database, but the patterns are the same: extract a part of a date, truncate to a period, or measure the gap between two dates.
- EXTRACT(YEAR FROM order_date) or DATEPART, pull the year, month, or day
- DATE_TRUNC(‘month’, order_date), roll timestamps up to the start of a period
- DATEDIFF(day, start_date, end_date), measure the gap between two dates
- CURRENT_DATE and INTERVAL, build relative windows such as the last 90 days
SELECT
DATE_TRUNC('month', order_date) AS order_month,
COUNT(*) AS orders
FROM orders
GROUP BY DATE_TRUNC('month', order_date);46. How would you calculate a conversion rate using SQL?
Conversion rate is the proportion of eligible users who complete a defined action. The denominator should match the business definition of an eligible user.
SELECT
SUM(CASE WHEN purchased = 1 THEN 1 ELSE 0 END)
* 100.0 / COUNT(*) AS conversion_rate
FROM users;For 4 users where 1 purchased, the conversion_rate is 25.0.
47. How would you identify customers who have churned?
Churn depends on the business definition. If a customer is considered churned after 90 days without a purchase, use the latest transaction date. Date syntax varies across databases.
SELECT
customer_id,
MAX(order_date) AS last_order_date
FROM orders
GROUP BY customer_id
HAVING MAX(order_date) < CURRENT_DATE - INTERVAL '90 days';48. How would you calculate customer retention using SQL?
Retention compares customers active in a later period with the original cohort. A basic approach identifies customers active in both periods; a complete retention rate needs a clearly defined cohort and denominator.
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING
SUM(CASE WHEN order_month = 'January' THEN 1 ELSE 0 END) > 0
AND
SUM(CASE WHEN order_month = 'February' THEN 1 ELSE 0 END) > 0;49. How would you find the average order value for each month?
Average order value divides total revenue by the number of distinct orders. COUNT(DISTINCT order_id) matters when one order spans multiple rows.
SELECT
month,
SUM(order_value) / COUNT(DISTINCT order_id) AS average_order_value
FROM orders
GROUP BY month;50. How would you approach optimizing a slow SQL query?
Start with the execution plan, which shows how the database intends to run the query and exposes table scans, index usage, joins, and sorts. From there, a practical process is:
- Read the execution plan and find the most expensive operations
- Look for large table scans and inefficient joins
- Review filtering and JOIN conditions
- Check whether useful indexes exist on filtered, joined, or sorted columns
- Avoid selecting unnecessary columns and remove redundant joins or calculations
- Re-measure after each change; optimize on evidence, not assumptions
Indexes speed up lookups on frequently filtered or joined columns, but they add storage and slow INSERT, UPDATE, and DELETE, so add them deliberately.
For the analytics rounds that usually follow SQL, see our Tableau interview questions for freshers and Data Science interview questions.
What Companies Look for in Data Analyst SQL Interviews
Knowing SQL is only part of the picture. Understanding what different companies expect helps freshers prepare strategically, since question types, difficulty, and practical expectations vary across roles.
What product-based companies expect
Product-based companies work with large volumes of customer, product, transaction, and engagement data. Their SQL interviews lean toward complex joins, CTEs, window functions, and metrics like retention, churn, and conversion. Expect a question such as “calculate 7-day retention by signup cohort,” which tests SQL and analytical thinking together.
What service-based companies look for
Service-based interviews vary by client project and often emphasize accurate queries, database relationships, and solving problems within a time limit. Timed coding assessments are common, so speed and correctness matter alongside concepts. Expect a question such as “write a query to find duplicate invoices within a date range.”
SQL interview expectations at mid-sized companies
Mid-sized companies expect a little more independence. Questions often combine joins, CTEs, subqueries, window functions, and time-series analysis rather than testing one concept at a time, with follow-ups on why an approach was chosen. Expect a question such as “find month-over-month growth and explain how you would validate it.”
SQL interview questions at startups
Startups expect ownership from day one with less structured support. Interviews focus on interpreting an open-ended requirement, working independently, validating results, and turning raw data into insight, often tied to the company product. Expect a question such as “here is a raw events table, define and measure activation.”
Related reading: roles and responsibilities of a data analyst, top data analytics companies hiring freshers in India, and data analyst salary in Bangalore.
Common SQL Interview Mistakes to Avoid
☐ Writing the query before understanding the problem
☐ Choosing the wrong JOIN or mishandling duplicate records
☐ Confusing WHERE, GROUP BY, and HAVING
☐ Ignoring NULL values, ties, and other edge cases
☐ Using the wrong window or aggregation logic
☐ Focusing on syntax without explaining the approach and business logic
Conclusion
SQL interviews for Data Analyst roles test whether you can think with data, pick the right approach, and explain your reasoning. Work these 50 questions by solving before reading the answer, then adapt each query to a new business rule. SQL remains one of the most widely used technologies in the field, per the Stack Overflow Developer Survey 2025 [verify live URL], which is why it stays the foundation of analyst hiring. The WILA Advanced Diploma in Data Analytics turns that practice into interview-ready skill through capstone projects and mock rounds.
Frequently Asked Questions
1. How many SQL questions should a Data Analyst fresher prepare?
There is no fixed number that guarantees success. Preparing a structured set across foundational, intermediate, and advanced levels helps freshers recognize common patterns and build practical problem-solving skill, which matters more than raw volume.
2. What SQL topics should a Data Analyst fresher learn for interviews?
Build a strong base in fundamentals, filtering, aggregation, conditional logic, data cleaning, and joins. Then progress to subqueries, CTEs, window functions, business metrics, time-series analysis, and query optimization.
3. Are SQL interview questions for Data Analysts difficult for freshers?
Difficulty depends on the company, role, and process. Fresher interviews often begin with fundamentals and progress toward joins, analytical queries, and practical business problems that test how you apply concepts.
4. What type of SQL questions are asked in Data Analyst interviews?
They include conceptual questions, query-writing tasks, and real-world scenarios. Common problems involve joining tables, calculating business metrics, handling missing data, ranking records, and comparing time periods.
5. Do MNCs ask advanced SQL questions to freshers?
Some MNCs test advanced concepts depending on the role and assessment. Freshers should be ready for window functions, complex joins, business metrics, time-series analysis, and analytical problem-solving.
6. How can freshers prepare for SQL interviews effectively?
Learn concepts systematically, practise writing queries, solve business-oriented problems, and understand why each approach works. Practising unfamiliar variations of common questions builds confidence. A structured data analytics course can shorten this path.
7. Are 50 SQL interview questions enough to clear a Data Analyst interview?
They cannot guarantee success, but they provide a practical foundation in common question patterns and problem-solving approaches that help you handle unfamiliar questions with more confidence.
8. Is SQL still important for a Data Analyst career?
Yes. SQL remains widely used for working with relational data and supports data extraction, analysis, business reporting, and everyday problem-solving, which is why it stays central to analyst roles.







