SQL interview questions for data analysts often cover a range of topics, from basic querying techniques to advanced data manipulation and performance optimization. These questions are designed to assess a candidate's understanding of SQL concepts, their ability to write and optimize queries, and their problem-solving skills when working with real-world data scenarios.
SQL Questions For Data Analyst Interview
This guide categorizes SQL interview questions into three levels of difficulty: easy, medium, and hard. By exploring these questions, you’ll gain a comprehensive understanding of the SQL skills required for data analysis roles. Whether you are preparing for an upcoming interview or looking to refine your SQL expertise, this curated list will help you navigate the complexities of SQL and enhance your analytical capabilities.
Basic SQL For Data Analyst Interview Questions
1. What is SQL, and what is its purpose in data analysis?
SQL (Structured Query Language) is a standard language for managing and manipulating relational databases. It allows analysts to query, update, and manage data effectively, which is crucial for data analysis tasks.
2. How do you retrieve all columns from a table named sales
?
Example: "SELECT * FROM sales;"
3. Write a SQL query to select distinct values from a column named product_category
.
Example: "SELECT DISTINCT product_category FROM sales;"
4. How do you filter records in SQL? Provide an example.
Use the WHERE
clause to filter records based on specific conditions.
Example: "SELECT * FROM sales WHERE amount > 1000;"
5. Explain the GROUP BY
clause and provide an example.
The GROUP BY
clause is used to aggregate rows that have the same values in specified columns.
Example: "SELECT product_category, SUM(amount) FROM sales GROUP BY product_category;"
6. What is the purpose of the HAVING
clause? How does it differ from WHERE
?
HAVING
is used to filter groups after aggregation, while WHERE
filters rows before aggregation.
Example: "SELECT product_category, SUM(amount) FROM sales GROUP BY product_category HAVING SUM(amount) > 5000;"
7. How do you sort the results of a query?
Use the ORDER BY
clause to sort results in ascending or descending order.
Example: "SELECT * FROM sales ORDER BY amount DESC;"
8. Write a query to find the total sales amount for each product.
Example: "SELECT product_name, SUM(amount) FROM sales GROUP BY product_name;"
9. What is the difference between INNER JOIN
and LEFT JOIN
?
INNER JOIN
returns rows with matching values in both tables, while LEFT JOIN
returns all rows from the left table and matched rows from the right table, with unmatched rows from the right table filled with NULLs.
INNER JOIN
Example: "SELECT sales.product_name, products.price FROM sales INNER JOIN products ON sales.product_id = products.product_id;"
LEFT JOIN
Example: "SELECT sales.product_name, products.price FROM sales LEFT JOIN products ON sales.product_id = products.product_id;"
10. How do you find the top 5 highest sales amounts?
Example: "SELECT amount FROM sales ORDER BY amount DESC LIMIT 5;"
Medium SQL Question for Data Analyst Interview
11. What is a subquery, and how can you use it in the WHERE
clause?
A subquery is a query within another query used to perform operations based on the results of the outer query.
Example: "SELECT product_name FROM sales WHERE amount > (SELECT AVG(amount) FROM sales);"
12. Explain the concept of a CROSS JOIN
.
A CROSS JOIN
returns the Cartesian product of two tables, where each row in the first table is combined with each row in the second table.
Example: "SELECT * FROM products CROSS JOIN categories;"
13. How do you calculate the average of a column?
Use the AVG()
function to calculate the average value.
Example: "SELECT AVG(amount) FROM sales;"
14. What is the purpose of the COUNT()
function? Provide an example.
The COUNT()
function returns the number of rows that match a specified condition.
Example: "SELECT COUNT(*) FROM sales WHERE product_category = 'Electronics';"
15. Write a query to find the minimum and maximum sales amounts.
Example: "SELECT MIN(amount) AS MinAmount, MAX(amount) AS MaxAmount FROM sales;"
16. How do you update records in a table?
Use the UPDATE
statement to modify existing records.
Example: "UPDATE sales SET amount = amount * 1.1 WHERE product_name = 'Laptop';"
17. Explain the CASE
statement and provide an example.
The CASE
statement allows for conditional logic in SQL queries.
Example: "SELECT product_name, CASE WHEN amount > 1000 THEN 'High' ELSE 'Low' END AS sales_category FROM sales;"
18. How do you handle NULL values in SQL queries?
Use functions like IS NULL
, IS NOT NULL
, or COALESCE()
to handle NULL values.
Example: "SELECT COALESCE(discount, 0) FROM sales;"
19. What is the LIMIT
clause used for? Provide an example.
The LIMIT
clause restricts the number of rows returned by a query.
Example: "SELECT * FROM sales LIMIT 10;"
20. How do you use the JOIN
clause to combine data from multiple tables?
Use JOIN
to combine rows from two or more tables based on related columns.
Example: "SELECT orders.order_id, customers.customer_name FROM orders JOIN customers ON orders.customer_id = customers.customer_id;"
21. What is a self-join? Provide an example.
A self-join is a join where a table is joined with itself. It is useful for hierarchical data.
Example: "SELECT e1.employee_name AS Employee, e2.employee_name AS Manager FROM employees e1 LEFT JOIN employees e2 ON e1.manager_id = e2.employee_id;"
22. Explain the UNION
and UNION ALL
operators.
UNION
combines the results of two queries and removes duplicates. UNION ALL
combines results without removing duplicates.
UNION
Example: "SELECT product_name FROM sales UNION SELECT product_name FROM returns;"
UNION ALL
Example: "SELECT product_name FROM sales UNION ALL SELECT product_name FROM returns;"
23. How do you find duplicate records in a table?
Use the GROUP BY
clause with HAVING COUNT(*) > 1
to find duplicates.
Example: "SELECT product_name, COUNT(*) FROM sales GROUP BY product_name HAVING COUNT(*) > 1;"
24. What is a window function? Provide an example.
Window functions perform calculations across a set of table rows related to the current row, such as running totals or rankings.
Example: "SELECT product_name, amount, RANK() OVER (ORDER BY amount DESC) AS rank FROM sales;"
25. How do you calculate a running total in SQL?
Use the SUM()
window function with an appropriate OVER
clause.
Example: "SELECT order_date, amount, SUM(amount) OVER (ORDER BY order_date) AS running_total FROM orders;"
26. How do you use the EXISTS
clause in SQL?
The EXISTS
clause checks if a subquery returns any rows.
Example: "SELECT product_name FROM sales WHERE EXISTS (SELECT * FROM returns WHERE returns.product_id = sales.product_id);"
27. Explain the difference between WHERE
and HAVING
clauses.
WHERE
filters rows before aggregation, while HAVING
filters groups after aggregation.
WHERE
Example: "SELECT * FROM sales WHERE amount > 1000;"
HAVING
Example: "SELECT product_name, SUM(amount) FROM sales GROUP BY product_name HAVING SUM(amount) > 5000;"
28. How do you find the number of orders per customer?
Example: "SELECT customer_id, COUNT(order_id) FROM orders GROUP BY customer_id;"
29. What is a TEMPORARY
table, and how is it used?
A TEMPORARY
table is a table that exists temporarily during a session and is dropped automatically when the session ends.
Example: "CREATE TEMPORARY TABLE temp_sales AS SELECT * FROM sales WHERE amount > 1000;"
30. How do you use the ALTER TABLE
statement?
The ALTER TABLE
statement modifies an existing table structure, such as adding or dropping columns.
Example: "ALTER TABLE sales ADD COLUMN discount DECIMAL(10, 2);"
31. What is normalization, and why is it important?
Normalization is the process of organizing data to reduce redundancy and improve data integrity. It ensures that the database is efficient and maintains consistency.
Use the INSERT INTO ... VALUES
statement with multiple values or a bulk loading utility.
- Multiple values Example:
"INSERT INTO sales (product_name, amount) VALUES ('Laptop', 1200), ('Smartphone', 800);"
- Bulk load Example (MySQL):
"LOAD DATA INFILE 'file_path.csv' INTO TABLE sales FIELDS TERMINATED BY ',';"
33. Explain the concept of indexing and its benefits.
Indexing improves the speed of data retrieval operations on a table by creating a data structure that allows quick lookups.
34. How do you create an index on a table?
Use the CREATE INDEX
statement to create an index on one or more columns.
Example: "CREATE INDEX idx_product_name ON sales(product_name);"
Hard SQL Question For Data Analyst Interview Questions
Common techniques include using indexes, optimizing queries, reducing the use of subqueries, and ensuring efficient joins.
The EXPLAIN
statement provides information about how a query is executed, including the order of operations and the use of indexes.
Example: "EXPLAIN SELECT * FROM sales WHERE amount > 1000;"
37. What is the purpose of the COALESCE()
function?
The COALESCE()
function returns the first non-NULL value from a list of arguments.
Example: "SELECT COALESCE(discount, 0) FROM sales;"
38. How do you calculate the percentage of total sales for each product?
Use a combination of SUM()
and a window function to calculate the percentage.
Example: "SELECT product_name, SUM(amount) AS total_sales, (SUM(amount) / SUM(SUM(amount)) OVER ()) * 100 AS percentage FROM sales GROUP BY product_name;"
39. What is a VIEW
, and how do you create one?
A VIEW
is a virtual table based on the result of a query. It simplifies complex queries and enhances security.
Example: "CREATE VIEW high_value_sales AS SELECT * FROM sales WHERE amount > 1000;"
40. How do you use the DROP TABLE
statement?
The DROP TABLE
statement deletes an entire table and its data from the database.
Example: "DROP TABLE old_sales;"
41. What is the difference between DELETE
and TRUNCATE
?
DELETE
removes rows from a table based on a condition and can be rolled back, while TRUNCATE
removes all rows from a table and cannot be rolled back.
DELETE
Example: "DELETE FROM sales WHERE amount < 500;"
TRUNCATE
Example: "TRUNCATE TABLE sales;"
Finding the median requires sorting and using window functions.
Example: "WITH OrderedSales AS (SELECT amount, ROW_NUMBER() OVER (ORDER BY amount) AS rn, COUNT(*) OVER () AS total_count FROM sales) SELECT AVG(amount) AS median FROM OrderedSales WHERE rn IN ((total_count + 1) / 2, (total_count + 2) / 2);"
43. What is the RANK()
function, and how is it used?
The RANK()
function assigns a rank to each row within a partition of the result set, with gaps in rank values if there are ties.
Example: "SELECT product_name, amount, RANK() OVER (ORDER BY amount DESC) AS rank FROM sales;"
You can join more than two tables by chainingJOIN
operations.
Example: "SELECT orders.order_id, customers.customer_name, products.product_name FROM orders JOIN customers ON orders.customer_id = customers.customer_id JOIN products ON orders.product_id = products.product_id;"
45. What is a TEMPORARY
table, and when would you use it?
A TEMPORARY
table is used to store intermediate results temporarily during a session, useful for complex queries or batch processing.
Example: "CREATE TEMPORARY TABLE temp_sales AS SELECT * FROM sales WHERE amount > 1000;"
46. How do you retrieve the last N records from a table?
Use the ORDER BY
clause with LIMIT
to get the last N records.
Example: "SELECT * FROM sales ORDER BY sale_date DESC LIMIT 10;"
47. Explain the DATEPART()
function with an example.
DATEPART()
extracts a specific part (e.g., year, month) from a date.
Example: "SELECT DATEPART(year, sale_date) AS sale_year FROM sales;"
48. How do you use JOIN
to include rows with no match in one of the tables?
Use a LEFT JOIN
or RIGHT JOIN
to include rows from one table even if there are no matching rows in the other table.
Example: "SELECT employees.name, departments.department_name FROM employees LEFT JOIN departments ON employees.department_id = departments.department_id;"
49. How can you calculate the difference between two dates in SQL?
Use date functions to calculate the difference between two dates.
Example: "SELECT DATEDIFF(day, start_date, end_date) AS date_difference FROM projects;"
50. What is the difference between CHAR
and VARCHAR
data types?
CHAR
is a fixed-length string, while VARCHAR
is a variable-length string. CHAR
uses the specified length for all values, padding with spaces if needed, whereas VARCHAR
only uses the space needed for each value.
Similar Reads
Data Science Tutorial Data Science is a field that combines statistics, machine learning and data visualization to extract meaningful insights from vast amounts of raw data and make informed decisions, helping businesses and industries to optimize their operations and predict future trends.This Data Science tutorial offe
3 min read
Introduction to Machine Learning
What is Data Science?Data science is the study of data that helps us derive useful insight for business decision making. Data Science is all about using tools, techniques, and creativity to uncover insights hidden within data. It combines math, computer science, and domain expertise to tackle real-world challenges in a
8 min read
Top 25 Python Libraries for Data Science in 2025Data Science continues to evolve with new challenges and innovations. In 2025, the role of Python has only grown stronger as it powers data science workflows. It will remain the dominant programming language in the field of data science. Its extensive ecosystem of libraries makes data manipulation,
10 min read
Difference between Structured, Semi-structured and Unstructured dataBig Data includes huge volume, high velocity, and extensible variety of data. There are 3 types: Structured data, Semi-structured data, and Unstructured data. Structured data - Structured data is data whose elements are addressable for effective analysis. It has been organized into a formatted repos
2 min read
Types of Machine LearningMachine learning is the branch of Artificial Intelligence that focuses on developing models and algorithms that let computers learn from data and improve from previous experience without being explicitly programmed for every task.In simple words, ML teaches the systems to think and understand like h
13 min read
What's Data Science Pipeline?Data Science is a field that focuses on extracting knowledge from data sets that are huge in amount. It includes preparing data, doing analysis and presenting findings to make informed decisions in an organization. A pipeline in data science is a set of actions which changes the raw data from variou
3 min read
Applications of Data ScienceData Science is the deep study of a large quantity of data, which involves extracting some meaning from the raw, structured, and unstructured data. Extracting meaningful data from large amounts usesalgorithms processing of data and this processing can be done using statistical techniques and algorit
6 min read
Python for Machine Learning
Learn Data Science Tutorial With PythonData Science has become one of the fastest-growing fields in recent years, helping organizations to make informed decisions, solve problems and understand human behavior. As the volume of data grows so does the demand for skilled data scientists. The most common languages used for data science are P
3 min read
Pandas TutorialPandas is an open-source software library designed for data manipulation and analysis. It provides data structures like series and DataFrames to easily clean, transform and analyze large datasets and integrates with other Python libraries, such as NumPy and Matplotlib. It offers functions for data t
6 min read
NumPy Tutorial - Python LibraryNumPy (short for Numerical Python ) is one of the most fundamental libraries in Python for scientific computing. It provides support for large, multi-dimensional arrays and matrices along with a collection of mathematical functions to operate on arrays.At its core it introduces the ndarray (n-dimens
3 min read
Scikit Learn TutorialScikit-learn (also known as sklearn) is a widely-used open-source Python library for machine learning. It builds on other scientific libraries like NumPy, SciPy and Matplotlib to provide efficient tools for predictive data analysis and data mining.It offers a consistent and simple interface for a ra
3 min read
ML | Data Preprocessing in PythonData preprocessing is a important step in the data science transforming raw data into a clean structured format for analysis. It involves tasks like handling missing values, normalizing data and encoding variables. Mastering preprocessing in Python ensures reliable insights for accurate predictions
6 min read
EDA - Exploratory Data Analysis in PythonExploratory Data Analysis (EDA) is a important step in data analysis which focuses on understanding patterns, trends and relationships through statistical tools and visualizations. Python offers various libraries like pandas, numPy, matplotlib, seaborn and plotly which enables effective exploration
6 min read
Introduction to Statistics
Statistics For Data ScienceStatistics is like a toolkit we use to understand and make sense of information. It helps us collect, organize, analyze and interpret data to find patterns, trends and relationships in the world around us.From analyzing scientific experiments to making informed business decisions, statistics plays a
12 min read
Descriptive StatisticStatistics is the foundation of data science. Descriptive statistics are simple tools that help us understand and summarize data. They show the basic features of a dataset, like the average, highest and lowest values and how spread out the numbers are. It's the first step in making sense of informat
5 min read
What is Inferential Statistics?Inferential statistics is an important tool that allows us to make predictions and conclusions about a population based on sample data. Unlike descriptive statistics, which only summarize data, inferential statistics let us test hypotheses, make estimates, and measure the uncertainty about our predi
7 min read
Bayes' TheoremBayes' Theorem is a mathematical formula used to determine the conditional probability of an event based on prior knowledge and new evidence. It adjusts probabilities when new information comes in and helps make better decisions in uncertain situations.Bayes' Theorem helps us update probabilities ba
13 min read
Probability Data Distributions in Data ScienceUnderstanding how data behaves is one of the first steps in data science. Before we dive into building models or running analysis, we need to understand how the values in our dataset are spread out and thatâs where probability distributions come in.Let us start with a simple example: If you roll a f
8 min read
Parametric Methods in StatisticsParametric statistical methods are those that make assumptions regarding the distribution of the population. These methods presume that the data have a known distribution (e.g., normal, binomial, Poisson) and rely on parameters (e.g., mean and variance) to define the data.Key AssumptionsParametric t
6 min read
Non-Parametric TestsNon-parametric tests are applied in hypothesis testing when the data does not satisfy the assumptions necessary for parametric tests, such as normality or equal variances. These tests are especially helpful for analyzing ordinal data, small sample sizes, or data with outliers.Common Non-Parametric T
5 min read
Hypothesis TestingHypothesis testing compares two opposite ideas about a group of people or things and uses data from a small part of that group (a sample) to decide which idea is more likely true. We collect and study the sample data to check if the claim is correct.Hypothesis TestingFor example, if a company says i
9 min read
ANOVA for Data Science and Data AnalyticsANOVA is useful when we need to compare more than two groups and determine whether their means are significantly different. Suppose you're trying to understand which ingredients in a recipe affect its taste. Some ingredients, like spices might have a strong influence while others like a pinch of sal
9 min read
Bayesian Statistics & ProbabilityBayesian statistics sees unknown values as things that can change and updates what we believe about them whenever we get new information. It uses Bayesâ Theorem to combine what we already know with new data to get better estimates. In simple words, it means changing our initial guesses based on the
6 min read
Feature Engineering
Model Evaluation and Tuning
Data Science Practice