SQL (Structured Query Language) is a programming language used to store, manage, and retrieve data from databases. In many jobs today, especially in IT, business analysis, and software development, knowing SQL is very important because most companies store their important information in databases.
People who work with SQL need to understand how to write queries to fetch data, update records, create tables, use joins, handle stored procedures, and optimize databases for better performance. They also need basic knowledge of database design, indexing, transactions, and data security.
Preparing for SQL interview questions and answers is important because it helps candidates explain their skills clearly and handle both technical and real-world scenario questions during interviews. Good preparation shows you can work with real databases and solve actual problems in the job.
On this page, we are sharing a collection of popular SQL interview questions and answers for both freshers and experienced candidates. These cover basic concepts, advanced topics, and practical scenario-based questions to help you prepare better. We are also providing a PDF download, so you can study offline anytime.
Table of Contents
Basic SQL interview questions and Answers for Freshers
First, we’ll start with basic SQL interview questions and answers for freshers. These cover commonly asked topics like SQL concepts, writing queries, and working with data.
1. What is SQL?
Answer:
SQL (Structured Query Language) is a standard language used to access, manage, and manipulate databases. It is used for querying data, inserting records, updating values, and managing database structures.
2. What are the different types of SQL statements?
Answer:
Basic SQL interview questions and Answers often start with this. SQL statements are categorized into:
- DDL (Data Definition Language) – CREATE, ALTER, DROP
- DML (Data Manipulation Language) – SELECT, INSERT, UPDATE, DELETE
- DCL (Data Control Language) – GRANT, REVOKE
- TCL (Transaction Control Language) – COMMIT, ROLLBACK, SAVEPOINT
3. How do you retrieve all records from a table?
Answer:
SELECT * FROM table_name;
4. How do you retrieve only specific columns from a table?
Answer:
SELECT column1, column2 FROM table_name;
5. What is a primary key?
Answer:
A primary key uniquely identifies each row in a table. It cannot contain null values and must be unique.
6. What is a foreign key?
Answer:
A foreign key links one table to another. It references the primary key in another table to enforce referential integrity.
7. How do you insert data into a table?
Answer:
INSERT INTO table_name (column1, column2) VALUES (value1, value2);
8. How do you update a record in SQL?
Answer:
UPDATE table_name SET column1 = value1 WHERE condition;
9. How do you delete a record in SQL?
Answer:
DELETE FROM table_name WHERE condition;
10. What is the difference between WHERE and HAVING?
Answer:
Clause | Used With | Purpose |
---|---|---|
WHERE | SELECT, UPDATE, DELETE | Filters rows before grouping |
HAVING | GROUP BY | Filters after aggregation |
11. What is the use of the GROUP BY clause?
Answer:
It groups rows with the same values into summary rows, often used with aggregate functions like SUM()
, AVG()
, COUNT()
.
SELECT department, COUNT(*) FROM employees GROUP BY department;
12. What is the purpose of the ORDER BY clause?
Answer:
ORDER BY is used to sort query results in ascending or descending order.
SELECT name FROM employees ORDER BY name ASC;
13. What is the difference between INNER JOIN and LEFT JOIN?
Answer:
Type | Returns |
---|---|
INNER JOIN | Matching rows from both tables |
LEFT JOIN | All rows from the left, and matched from right |
14. How do you use the LIKE operator in SQL?
Answer:
LIKE is used for pattern matching in Basic SQL interview questions and Answers.
SELECT * FROM customers WHERE name LIKE 'A%';
15. What are aggregate functions in SQL?
Answer:
COUNT()
– number of rowsSUM()
– total of a columnAVG()
– average of a columnMAX()
– highest valueMIN()
– lowest value
16. What is a subquery?
Answer:
A subquery is a query nested inside another SQL query.
SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
17. How do you eliminate duplicate records in a result set?
Answer:
SELECT DISTINCT column_name FROM table_name;
18. What is the BETWEEN operator in SQL?
Answer:
It filters values within a specific range.
SELECT * FROM products WHERE price BETWEEN 100 AND 500;
19. How do you rename a column in the result set?
Answer:
SELECT column_name AS alias_name FROM table_name;
20. What is normalization in SQL?
Answer:
Normalization is the process of organizing data to reduce redundancy and improve data integrity. It involves dividing a database into two or more tables and defining relationships between them.

Also Check: Python Interview Questions and Answers
Advanced SQL interview questions and Answers for Experienced
These questions gradually increase in complexity, covering window functions, optimization, complex joins, subqueries, and advanced querying techniques.
21. What is the difference between RANK, DENSE_RANK, and ROW_NUMBER?
Answer:
Function | Behavior |
---|---|
RANK | Skips rank after duplicates |
DENSE_RANK | Does not skip ranks |
ROW_NUMBER | Unique sequence without tie logic |
Example:
SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees;
22. What is a CTE and how is it different from a subquery?
Answer:
A CTE (Common Table Expression) improves readability and can be recursive. Unlike subqueries, CTEs can reference themselves.
WITH HighSalary AS (
SELECT * FROM employees WHERE salary > 50000
)
SELECT * FROM HighSalary;
23. How do you find the nth highest salary using SQL?
Answer:
SELECT DISTINCT salary FROM employees e1
WHERE N - 1 = (
SELECT COUNT(DISTINCT salary) FROM employees e2
WHERE e2.salary > e1.salary
);
24. What is a recursive CTE? Provide an example.
Answer:
A recursive CTE refers to itself to perform hierarchical operations.
WITH RECURSIVE emp_tree AS (
SELECT id, name, manager_id FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id
FROM employees e
JOIN emp_tree t ON e.manager_id = t.id
)
SELECT * FROM emp_tree;
25. How do you remove duplicates while keeping the latest record?
Answer:
DELETE FROM orders o1
WHERE o1.id NOT IN (
SELECT MAX(o2.id) FROM orders o2 GROUP BY o2.order_number
);
26. What is the purpose of the PARTITION BY clause in window functions?
Answer:PARTITION BY
splits data into partitions (groups) for functions like RANK, SUM, AVG to work within each group.
SELECT department, employee,
RANK() OVER (PARTITION BY department ORDER BY salary DESC)
FROM employees;
27. How do you calculate a moving average in SQL?
Answer:
SELECT date, sales,
AVG(sales) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg
FROM revenue;
28. What is the difference between INNER JOIN and FULL OUTER JOIN?
Answer:
Join Type | Description |
---|---|
INNER JOIN | Only matching records |
FULL OUTER JOIN | All records with NULL where unmatched |
29. How can you pivot data in SQL?
Answer (MySQL Example):
SELECT department,
SUM(CASE WHEN gender = 'M' THEN 1 ELSE 0 END) AS Male,
SUM(CASE WHEN gender = 'F' THEN 1 ELSE 0 END) AS Female
FROM employees
GROUP BY department;
30. What is a correlated subquery?
Answer:
A correlated subquery refers to columns from the outer query and is evaluated once per row.
SELECT e1.name
FROM employees e1
WHERE salary > (
SELECT AVG(salary) FROM employees e2 WHERE e2.department = e1.department
);
31. How can you identify and avoid SQL performance issues?
Answer:
- Use
EXPLAIN
to analyze queries - Add indexes on frequently filtered columns
- Avoid using
SELECT *
- Minimize subqueries and use joins where better
- Consider denormalization for read-heavy loads
32. How do you implement pagination in SQL?
Answer:
SELECT * FROM products
ORDER BY id
LIMIT 10 OFFSET 20;
This retrieves page 3 of 10 items each.
33. How do you find gaps in a sequence of numbers?
Answer:
SELECT a.id + 1 AS missing
FROM numbers a
LEFT JOIN numbers b ON a.id + 1 = b.id
WHERE b.id IS NULL;
34. What is the use of EXISTS vs IN?
Answer:
Feature | EXISTS | IN |
---|---|---|
Returns | Boolean (TRUE/FALSE) | Set of values |
Performance | Faster for correlated subqueries | Better for small static lists |
35. How do you find employees with duplicate emails?
Answer:
SELECT email, COUNT(*)
FROM employees
GROUP BY email
HAVING COUNT(*) > 1;
36. What is the difference between DELETE, TRUNCATE, and DROP?
Answer:
Command | Removes Data | Rollback | Affects Structure |
---|---|---|---|
DELETE | Yes | Yes | No |
TRUNCATE | Yes | No | No |
DROP | Yes (all) | No | Yes |
37. What are materialized views and when to use them?
Answer:
A materialized view stores the result of a query physically and can be refreshed periodically. Useful for heavy aggregation and reporting queries.
38. How do you find the maximum salary in each department?
Answer:
SELECT department, MAX(salary)
FROM employees
GROUP BY department;
39. How do you use CASE WHEN in SQL?
Answer:
SELECT name, salary,
CASE
WHEN salary > 100000 THEN 'High'
WHEN salary > 50000 THEN 'Medium'
ELSE 'Low'
END AS salary_bracket
FROM employees;
40. How do you optimize a slow SQL query?
Answer:
- Use appropriate indexes
- Reduce the number of joins
- Avoid complex subqueries
- Use temporary tables if needed
- Rewrite logic with CTEs or window functions
- Use
LIMIT
,WHERE
, andEXPLAIN
Technical SQL Interview Questions and Answers
Here are some Technical SQL Interview Questions and Answers for intermediate to advanced level candidates.
41. How do you find duplicate records in a table?
Answer:
Use GROUP BY
and HAVING
to find duplicates based on specific columns.
SELECT email, COUNT(*)
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
42. What is the difference between WHERE and HAVING in SQL?
Answer:
Clause | Used With | Filters |
---|---|---|
WHERE | Before GROUP BY | Individual rows |
HAVING | After GROUP BY | Aggregated groups |
SELECT department, COUNT(*)
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
43. How do you get the second highest salary from a table?
Answer:
Use DISTINCT
, ORDER BY
, and LIMIT
.
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
44. What is the purpose of the IN and EXISTS operators in SQL?
Answer:
IN
: Checks if a value matches any in a listEXISTS
: Checks if a subquery returns rows
Use EXISTS
when working with correlated subqueries for better performance in large datasets.

45. What is the use of indexes in SQL and how do they improve performance?
Answer:
Indexes speed up data retrieval by creating a pointer structure on columns. They are useful on columns used in WHERE
, JOIN
, and ORDER BY
.
CREATE INDEX idx_name ON employees(last_name);
Note: Over-indexing can slow down INSERT
and UPDATE
.
46. Explain window functions with an example.
Answer:
Window functions perform calculations across rows related to the current row without collapsing the result set.
SELECT employee_id, department, salary,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dept_rank
FROM employees;
47. How do you delete duplicate records but keep one?
Answer:
Use ROW_NUMBER()
in a CTE to identify duplicates.
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn
FROM users
)
DELETE FROM cte WHERE rn > 1;
48. What is a correlated subquery? Give an example.
Answer:
A correlated subquery refers to the outer query and is executed once for every row of the outer query.
SELECT name FROM employees e
WHERE salary > (
SELECT AVG(salary) FROM employees WHERE department = e.department
);
49. How do you optimize a slow SQL query?
Answer:
- Use
EXPLAIN
to analyze execution plan - Add indexes on filtered and joined columns
- Avoid
SELECT *
, use specific columns - Limit nested subqueries
- Use
JOIN
instead of correlated subqueries where possible
50. How do you write a query to transpose rows into columns (pivot)?
Answer:
Use CASE WHEN
with aggregation.
SELECT department,
SUM(CASE WHEN gender = 'M' THEN 1 ELSE 0 END) AS male_count,
SUM(CASE WHEN gender = 'F' THEN 1 ELSE 0 END) AS female_count
FROM employees
GROUP BY department;
Also check: Technical Interview Questions and Answers
SQL interview questions and Answers for Data Analyst
hese are crafted to assess practical data analysis capabilities using SQL, increasing in complexity from simple queries to advanced analytics functions.
51. How do you retrieve the top 5 highest-paid employees from an employee table?
Answer:
SELECT name, salary
FROM employees
ORDER BY salary DESC
LIMIT 5;
52. How would you calculate the average order value per customer?
Answer:
SELECT customer_id, AVG(order_total) AS avg_order_value
FROM orders
GROUP BY customer_id;
53. How do you calculate the percentage contribution of each product to total sales?
Answer:
SELECT product_id,
SUM(sales_amount) AS total_sales,
SUM(sales_amount) * 100.0 / (SELECT SUM(sales_amount) FROM sales) AS percentage_contribution
FROM sales
GROUP BY product_id;
54. How do you find customers who have not placed any orders?
Answer:
SELECT c.customer_id, c.name
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
WHERE o.order_id IS NULL;
55. How do you identify duplicate rows based on email in a user table?
Answer:
SELECT email, COUNT(*)
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
56. How do you calculate the cumulative sum of sales by date?
Answer:
SELECT sale_date, sales_amount,
SUM(sales_amount) OVER (ORDER BY sale_date) AS cumulative_sales
FROM sales;
57. How would you find the month with the highest sales?
Answer:
SELECT EXTRACT(MONTH FROM sale_date) AS sale_month,
SUM(sales_amount) AS monthly_sales
FROM sales
GROUP BY sale_month
ORDER BY monthly_sales DESC
LIMIT 1;
58. How do you compare year-over-year growth in SQL?
Answer:
SELECT year,
SUM(revenue) AS total_revenue,
LAG(SUM(revenue)) OVER (ORDER BY year) AS last_year_revenue,
(SUM(revenue) - LAG(SUM(revenue)) OVER (ORDER BY year)) * 100.0 /
LAG(SUM(revenue)) OVER (ORDER BY year) AS yoy_growth_percentage
FROM sales
GROUP BY year;
Need more data analyst interview questions? Visit here: Data Analyst Interview Questions and Answers
Scenario Based SQL interview questions and Answers
59. You have a Sales table. How would you retrieve the top-selling product in each region?
Answer:
SELECT region, product, total_sales
FROM (
SELECT region, product, SUM(sales_amount) AS total_sales,
RANK() OVER (PARTITION BY region ORDER BY SUM(sales_amount) DESC) AS rnk
FROM sales
GROUP BY region, product
) ranked
WHERE rnk = 1;
60. A Customers table has some customers who have never made a purchase. How do you find and list them?
Answer:
SELECT c.customer_id, c.name
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
WHERE o.order_id IS NULL;
This scenario tests knowledge of LEFT JOIN
and null-checking logic.
61. From an Orders table, how do you find customers who placed more than one order on the same day?
Answer:
SELECT customer_id, order_date, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id, order_date
HAVING COUNT(*) > 1;
62. How do you return the first order placed by each customer from an Orders table?
Answer:
SELECT customer_id, order_id, order_date
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date) AS rn
FROM orders
) ranked
WHERE rn = 1;
This uses ROW_NUMBER()
and is common in interviews for customer history analytics.
63. A Transactions table contains rows for each product purchase. How do you find products that were sold every day in January 2024?
Answer:
SELECT product_id
FROM transactions
WHERE DATE(transaction_date) BETWEEN '2024-01-01' AND '2024-01-31'
GROUP BY product_id
HAVING COUNT(DISTINCT DATE(transaction_date)) = 31;
This shows logical filtering and validation across multiple dates.
64. How do you detect a price increase compared to the previous day for the same product in a “Product_prices” table?
Answer:
SELECT product_id, price_date, price,
LAG(price) OVER (PARTITION BY product_id ORDER BY price_date) AS previous_price
FROM product_prices
WHERE price > LAG(price) OVER (PARTITION BY product_id ORDER BY price_date);
SQL interview questions and Answers PDF
Here is the PDF file of SQL questions and answers, so you can download and read anytime.
FAQs: SQL interview questions and Answers
What does an SQL-based job role typically involve?
An SQL job primarily involves working with relational databases to extract, manipulate, and analyze data. Professionals in these roles may design database schemas, write complex queries, optimize database performance, and support data pipelines. These roles are common in data analytics, business intelligence, data engineering, and backend development.
What are the common challenges faced during an SQL interview?
Candidates often face challenges with writing efficient queries under time constraints, especially involving JOIN
, GROUP BY
, and subqueries. Many interviews also include real-world scenarios that test your ability to clean data, handle edge cases, and explain query logic clearly. Performance tuning and SQL logic questions can be tricky if you’re not well-practiced.
What types of roles typically require SQL expertise?
SQL is a foundational skill across several roles, including Data Analyst, Business Analyst, Data Engineer, Database Administrator (DBA), and even Software Engineers who interact with backend systems. Strong SQL knowledge is essential for any role that involves structured data analysis or ETL processes.
How much does an SQL professional earn in the USA?
In the USA, SQL professionals earn between $70,000 to $120,000 per year depending on experience, industry, and location. Entry-level analysts may start around $65,000, while senior data engineers or DBAs can earn $130,000 or more, especially in tech-heavy cities like Seattle, San Francisco, and Austin.
Which companies commonly hire for SQL-related roles?
Top companies hiring SQL professionals include Google, Amazon, Microsoft, Facebook, Accenture, IBM, Deloitte, JPMorgan Chase, Walmart, and Netflix. These roles span across domains like finance, e-commerce, healthcare, and IT consulting.
How should I prepare for an SQL interview?
Prepare by practicing SQL problems on platforms like LeetCode, Mode Analytics, or StrataScratch. Focus on writing optimized queries involving joins, aggregations, window functions, and case statements. Review database normalization, indexing, and real-world reporting scenarios. Mock interviews and timed query writing can help build confidence.
Do certifications help in getting SQL jobs?
Certifications like Microsoft’s SQL Server, Google’s Data Analytics Certificate, and Oracle SQL Certification can enhance your profile, especially if you’re new to the field. However, practical query-writing skills and a strong understanding of data are usually more valued by hiring managers during SQL interviews.
Conclusion
We have already shared SQL interview questions and answers for all levels, from freshers to experienced. A PDF download is also available for easy access.