SQL interview questions for data analysts are commonly focused on retrieving data, filtering records, joining tables, calculating business metrics, and solving real-world data problems. If you are preparing for a Data Analyst interview in 2026, learning SQL is essential because companies use databases to store and analyze large amounts of business information.
From basic SELECT queries to advanced concepts such as window functions, subqueries, and Common Table Expressions (CTEs), SQL helps analysts turn raw data into meaningful insights.
Whether you are a fresher, a job seeker, or a professional planning to switch careers, this guide covers important SQL interview questions with answers and practical examples to help you prepare confidently.
What Is SQL and Why Is It Important for Data Analysts?
SQL stands for Structured Query Language. It is used to communicate with relational databases, retrieve information, update records, and perform calculations on stored data.
Data analysts use SQL to extract relevant information from databases and answer business questions. For example, an e-commerce company may want to identify its best-selling products, while a bank may need to analyze customer transactions.
SQL makes these tasks easier by allowing analysts to work directly with structured data.
Why Do Data Analysts Need SQL?
- Data extraction: Retrieve specific information from large databases.
- Data cleaning: Identify duplicate records, missing values, and inconsistent information.
- Data analysis: Calculate totals, averages, and other business metrics.
- Data reporting: Prepare datasets for Excel, Power BI, and Tableau dashboards.
- Business decision-making: Identify sales trends, customer behavior, and operational problems.
For aspiring analysts, understanding SQL fundamentals and practicing queries regularly can improve technical interview preparation.
Top SQL Interview Questions for Data Analysts
The following questions cover basic, intermediate, and advanced SQL concepts frequently relevant to data analyst interviews.
1. What Is SQL?
SQL is a programming language used to manage and query data stored in relational database management systems.
It allows users to retrieve records, filter information, combine tables, and perform calculations.
Example:
SELECT *
FROM employees;
This query retrieves all columns and rows from the employees table.
2. What Is the Difference Between WHERE and HAVING?
Both WHERE and HAVING filter data, but they operate at different stages of a query.
| WHERE | HAVING |
|---|---|
| Filters individual rows. | Filters grouped results. |
| Applied before GROUP BY aggregation. | Applied after grouping and aggregation. |
| Commonly used with regular conditions. | Commonly used with aggregate conditions. |
| Cannot directly filter on an aggregate calculated in the same query’s SELECT list. | Can filter using aggregate functions such as COUNT and SUM. |
Example using WHERE:
SELECT *
FROM employees
WHERE salary > 50000;
Example using HAVING:
SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
The first query returns employees earning more than 50,000. The second returns departments with more than five employees.
3. What Is the Difference Between DELETE, DROP, and TRUNCATE?
These SQL commands serve different purposes when removing data.
| Command | Purpose | Effect |
|---|---|---|
| DELETE | Removes selected rows or all rows. | The table structure remains. |
| DROP | Removes the table itself. | Both table structure and its data are removed. |
| TRUNCATE | Removes all rows from a table. | The table structure remains. |
Example:
DELETE FROM employees
WHERE employee_id = 101;
This statement removes the employee whose ID is 101.
TRUNCATE TABLE employees;
This removes all rows from the table in database systems that support this command.
Interview tip: Transaction behavior, rollback support, permissions, and identity-counter handling differ across database systems. Avoid assuming that these commands behave identically in every SQL database.
4. What Is a JOIN in SQL?
A JOIN combines related data from two or more tables using a matching condition.
Data analysts frequently use JOINs to combine employee records with department information or customer records with sales transactions.
The main types of JOINs include:
- INNER JOIN: Returns rows with matching values in both tables.
- LEFT JOIN: Returns every row from the left table and matching rows from the right table.
- RIGHT JOIN: Returns every row from the right table and matching rows from the left table.
- FULL OUTER JOIN: Returns matching rows and nonmatching rows from both tables, where supported.
- CROSS JOIN: Returns combinations of rows from both tables.
Example:
SELECT e.employee_name, d.department_name
FROM employees e
INNER JOIN departments d
ON e.department_id = d.department_id;
This query combines employee names with their corresponding department names.
5. What Is the Difference Between UNION and UNION ALL?
UNION and UNION ALL combine the results of multiple SELECT statements.
| UNION | UNION ALL |
|---|---|
| Removes duplicate rows from the combined result. | Retains duplicate rows. |
| May require additional processing to eliminate duplicates. | Often requires less processing because duplicates are retained. |
| Useful when unique results are required. | Useful when all records must be preserved. |
Example:
SELECT city FROM customers
UNION
SELECT city FROM suppliers;
This returns distinct city values from both tables.
To preserve duplicates, replace UNION with UNION ALL.
6. What Is a Primary Key?
A primary key uniquely identifies each row in a database table.
For example, an employee ID can serve as the primary key in an employee table.
Important characteristics include:
- Each primary-key value must be unique.
- A primary-key column cannot contain NULL values.
- A table can have only one primary-key constraint, although that key can consist of multiple columns.
Primary keys help maintain data integrity and establish relationships between tables.
7. What Is a Foreign Key?
A foreign key is a column or group of columns used to establish a relationship with a primary key or another eligible unique key in a related table.
For example, an employees table may contain a department_id column that references the department_id primary key in a departments table.
Foreign keys help maintain referential integrity by preventing relationships from referencing nonexistent parent records, subject to the database’s constraints and configuration.
8. What Is GROUP BY in SQL?
GROUP BY groups rows that share the same values in specified columns. Analysts commonly use it with aggregate functions to calculate department-wise salaries, monthly sales, or product-wise revenue.
Example:
SELECT department, AVG(salary) AS average_salary
FROM employees
GROUP BY department;
This query calculates the average salary for each department.
Common aggregate functions include:
- COUNT(): Counts rows or non-NULL values, depending on the expression.
- SUM(): Calculates the total of numeric values.
- AVG(): Calculates the average of non-NULL numeric values.
- MIN(): Returns the minimum value.
- MAX(): Returns the maximum value.
9. How Do You Find Duplicate Records in SQL?
Identifying duplicate records is an important data-cleaning task.
Suppose the customers table contains an email column. You can identify email addresses appearing more than once using GROUP BY and HAVING.
SELECT email, COUNT(*) AS occurrence_count
FROM customers
GROUP BY email
HAVING COUNT(*) > 1;
This query identifies email values that appear in multiple rows.
Real-world application: Data analysts use similar queries to investigate duplicate customer registrations, repeated transaction identifiers, and inconsistent business records.
Remember that duplicate detection depends on the business definition of a duplicate. Two rows sharing an email address may not always represent the same person.
10. How Do You Find the Second-Highest Salary?
Finding the second-highest salary is a popular SQL interview problem.
One solution is to use a subquery:
SELECT MAX(salary) AS second_highest_salary
FROM employees
WHERE salary < (
SELECT MAX(salary)
FROM employees
);
The inner query finds the highest salary. The outer query returns the greatest salary below that value.
This solution returns the second-highest distinct salary when one exists. If every employee has the same salary, the result will be NULL.
If the interviewer asks for the second-highest salary using ranking functions, you can use DENSE_RANK() instead.
Intermediate SQL Interview Questions
Once you understand the basics, interviewers may ask you to solve problems involving conditional logic, date functions, subqueries, and data aggregation.
11. What Is the Difference Between ROW_NUMBER(), RANK(), and DENSE_RANK()?
These are window functions used to assign rankings to rows.
| Function | How It Works | Example for Values 100, 100, 90 |
|---|---|---|
| ROW_NUMBER() | Assigns a unique sequential number to each row. | 1, 2, 3 |
| RANK() | Assigns the same rank to ties and skips subsequent ranks. | 1, 1, 3 |
| DENSE_RANK() | Assigns the same rank to ties without skipping ranks. | 1, 1, 2 |
The order of tied rows is not guaranteed unless you specify additional ordering columns.
Example:
SELECT
employee_name,
salary,
DENSE_RANK() OVER (
ORDER BY salary DESC
) AS salary_rank
FROM employees;
This query assigns the same rank to employees with equal salaries.
12. What Is a Subquery in SQL?
A subquery is a query nested inside another SQL statement.
It can be used in SELECT, FROM, WHERE, or other supported clauses.
Example:
SELECT employee_name, salary
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);
This query returns employees earning more than the overall average salary.
Subqueries are useful when one calculation depends on the result of another query.
13. What Is a Common Table Expression (CTE)?
A Common Table Expression, or CTE, is a named temporary result set defined using the WITH clause. It is available to the statement that follows it.
CTEs can make complex SQL queries easier to read and maintain.
Example:
WITH department_salary AS (
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
)
SELECT department, avg_salary
FROM department_salary
WHERE avg_salary > 50000;
This query calculates the average salary for each department and then filters departments with an average above 50,000.
14. What Is CASE WHEN in SQL?
CASE WHEN is used to apply conditional logic in a query.
For example, a data analyst may want to classify employees into salary categories.
SELECT
employee_name,
salary,
CASE
WHEN salary >= 80000 THEN 'High'
WHEN salary >= 50000 THEN 'Medium'
ELSE 'Low'
END AS salary_category
FROM employees;
The query assigns a salary category based on the employee’s salary.
CASE expressions are useful for creating business categories, conditional calculations, and custom report labels.
15. What Is the Difference Between COUNT(*) and COUNT(column_name)?
COUNT(*) counts rows, including rows containing NULL values in individual columns.
COUNT(column_name) counts only rows in which the specified column is not NULL.
Example:
SELECT
COUNT(*) AS total_rows,
COUNT(email) AS rows_with_email
FROM customers;
This query counts all customer rows and separately counts the rows with a non-NULL email value.
This distinction is particularly useful when checking data completeness.
Advanced SQL Interview Questions for Data Analysts
Advanced SQL questions often focus on analytical problem-solving rather than memorizing syntax. You may be asked to analyze customer retention, rank products, calculate running totals, or compare performance over time.
16. What Are Window Functions in SQL?
Window functions perform calculations across a set of related rows without collapsing those rows into one result per group.
Unlike GROUP BY, window functions can retain individual row details while calculating rankings, running totals, or averages.
Example:
SELECT
employee_name,
department,
salary,
AVG(salary) OVER (
PARTITION BY department
) AS department_avg_salary
FROM employees;
This query displays each employee alongside the average salary of their department.
Common window functions include ROW_NUMBER(), RANK(), DENSE_RANK(), LAG(), LEAD(), and aggregate functions used with an OVER clause.
17. How Do You Calculate a Running Total in SQL?
A running total calculates a cumulative sum as rows progress through a specified order.
Suppose a sales table contains sale_date and amount columns.
SELECT
sale_date,
amount,
SUM(amount) OVER (
ORDER BY sale_date
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW
) AS running_total
FROM sales;
This query calculates the cumulative sales amount in date order.
If multiple transactions share the same date, add a unique transaction identifier to the ORDER BY clause to define a consistent row sequence.
Running totals are commonly used in financial reporting, monthly revenue tracking, and performance analysis.
18. How Do You Find the Top Three Salaries in Each Department?
You can solve this problem using the DENSE_RANK() window function.
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 employee_name, department, salary
FROM ranked_employees
WHERE salary_rank <= 3;
This query returns employees whose salaries fall within the top three distinct salary levels in each department.
Because DENSE_RANK() preserves ties, more than three employees may be returned for a department.
If the requirement is to return no more than three employees per department, use ROW_NUMBER() with a suitable tie-breaking column.
19. How Do You Find Customers Who Have Never Placed an Order?
This question tests your understanding of JOINs and NULL values.
Assume there are two tables: customers and orders.
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;
The query returns customers without matching order records.
This type of analysis helps businesses identify inactive customers, understand purchasing behavior, and develop customer engagement strategies.
An alternative is to use NOT EXISTS, which can be particularly clear when expressing an absence of matching records.
20. How Do You Calculate Month-Wise Sales?
Month-wise sales analysis is a common requirement in reporting and business intelligence.
The exact date functions depend on the SQL database being used. The following example uses PostgreSQL syntax.
SELECT
DATE_TRUNC('month', sale_date) AS sales_month,
SUM(amount) AS total_sales
FROM sales
GROUP BY DATE_TRUNC('month', sale_date)
ORDER BY sales_month;
This query groups sales by month and calculates total revenue for each month.
Data analysts use similar queries to identify seasonal trends, compare monthly performance, and prepare dashboards in Power BI or Tableau.
Practical SQL Interview Questions Based on Real-World Scenarios
Technical interviews often include business problems that require you to write a query and explain your approach.
| Business Scenario | SQL Concept | What the Interviewer Tests |
|---|---|---|
| Find the top five selling products. | ORDER BY and LIMIT or equivalent syntax | Sorting and filtering |
| Identify duplicate customer records. | GROUP BY and HAVING | Data-quality analysis |
| Calculate average order value. | AVG, SUM, and COUNT | Business metrics |
| Find customers who never ordered. | LEFT JOIN or NOT EXISTS | Relational data analysis |
| Rank employees by salary. | DENSE_RANK or ROW_NUMBER | Window functions |
| Calculate monthly revenue. | Date functions and GROUP BY | Time-based analysis |
| Find sales above the average. | Subqueries or CTEs | Multi-step queries |
| Calculate cumulative sales. | SUM with OVER | Analytical functions |
Example: Find the Top Five Selling Products
Assume a sales table contains product_name and quantity columns.
SELECT
product_name,
SUM(quantity) AS total_quantity
FROM sales
GROUP BY product_name
ORDER BY total_quantity DESC
LIMIT 5;
This PostgreSQL/MySQL-style query returns the five products with the highest total quantity sold. SQL Server and some other database systems use different syntax for limiting result sets.
Example: Calculate Average Order Value
Average order value is commonly calculated by dividing total order revenue by the number of orders.
If the orders table contains one row per order, the query can be written as:
SELECT
SUM(order_amount) / NULLIF(COUNT(*), 0)
AS average_order_value
FROM orders;
The NULLIF function prevents division by zero. If there are no orders, the result is NULL.
If the table contains multiple rows per order, first aggregate the line items to the order level to avoid calculating an incorrect average.
Common SQL Mistakes to Avoid in Interviews
Knowing SQL syntax is important, but interviewers also assess whether you understand the logic behind your queries.
Avoid these common mistakes:
- Confusing WHERE with HAVING when filtering aggregate results.
- Forgetting the join condition and unintentionally creating a large Cartesian result.
- Using SELECT * when only a few columns are required.
- Ignoring NULL values while calculating averages or counting records.
- Using DISTINCT to hide duplicate records without investigating their cause.
- Forgetting that joins can multiply rows when tables contain multiple matching records.
- Using ROW_NUMBER(), RANK(), and DENSE_RANK() interchangeably.
- Assuming date functions and limiting syntax are identical across databases.
- Writing queries without checking whether the results make business sense.
- Ignoring edge cases such as duplicate salaries, empty tables, and missing values.
A strong candidate explains not only how a query works but also why the chosen approach is appropriate.
How to Prepare for SQL Interviews as a Data Analyst
A structured preparation plan can help you build confidence and improve your problem-solving skills.
Step 1: Master SQL Fundamentals
Start with SELECT, WHERE, ORDER BY, DISTINCT, and basic filtering conditions. Practice retrieving specific information from sample datasets.
Step 2: Practice Joins and Aggregations
Learn INNER JOIN, LEFT JOIN, GROUP BY, HAVING, COUNT, SUM, and AVG. These concepts are essential for combining and summarizing business data.
Step 3: Learn Subqueries and CTEs
Practice solving multi-step problems and breaking complex queries into smaller, understandable parts.
Step 4: Understand Window Functions
Focus on ranking, running totals, department-wise comparisons, and previous-row analysis using LAG() and LEAD().
Step 5: Solve Real-World Business Problems
Work with sales, customer, employee, inventory, and transaction datasets. Practice turning business questions into SQL queries.
Step 6: Explain Your Query Logic
During interviews, explain your assumptions, approach, expected output, and handling of edge cases. This demonstrates analytical thinking rather than simple memorization.
Step 7: Practice Mock Interviews
Mock interviews help you practice answering technical questions under time pressure. They also provide opportunities to improve communication and explain your SQL logic clearly.
Conclusion
SQL is an essential skill for data analysts because it enables them to retrieve, clean, transform, and analyze structured data. Preparing for SQL interviews requires more than memorizing definitions. You must understand how queries work and apply them to real business situations.
Start with basic queries, practice JOINs and aggregate functions, and gradually move toward subqueries, CTEs, and window functions. Regular hands-on practice can help you approach technical interview questions more confidently.
At Skillcure Academy, aspiring data analysts can focus on practical learning, technical problem-solving, and interview preparation. Practicing SQL queries alongside Excel, Power BI, Python, and real-world projects can help you develop skills relevant to data analytics roles.
If you are preparing for a Data Analyst career, begin practicing SQL today and build your confidence one query at a time.
Frequently Asked Questions (FAQs)
1. Which SQL questions are commonly asked in Data Analyst interviews?
Common topics include SELECT, WHERE, GROUP BY, HAVING, JOINs, subqueries, aggregate functions, duplicate detection, second-highest salary, and window functions.
2. Is SQL enough to get a Data Analyst job?
SQL is an important skill, but many Data Analyst roles also require Excel, data visualization tools such as Power BI or Tableau, analytical thinking, and communication skills. Some positions also require Python.
3. How long does it take to learn SQL for Data Analyst interviews?
The time required depends on your existing knowledge and practice schedule. Beginners may need several weeks of consistent study to become comfortable with common interview problems. Advanced query writing generally requires additional practice.
4. Which SQL topics should freshers learn first?
Freshers should begin with SELECT, WHERE, ORDER BY, GROUP BY, HAVING, aggregate functions, and JOINs. After mastering these concepts, they can progress to subqueries, CTEs, and window functions.
5. How can I practice SQL for Data Analyst interviews?
Practice writing queries using sample employee, customer, sales, and order datasets. Solve problems involving duplicates, rankings, missing records, and monthly sales. Reviewing your query output and explaining your approach will help strengthen your interview preparation.





