Top 100 SQL Query Interview Questions and Answers
Introduction
Structured Query Language, better known as SQL, is the standard language for managing and manipulating relational databases.
Whether you’re a fresher or an experienced professional, SQL is a must-have skill in your tech toolkit.
Most technical interviews for database roles, backend development, data analytics, and QA testing include a set of SQL query questions to evaluate how well you can retrieve, analyze, and manage data.
In this guide, we’ve compiled the top 100 SQL query interview questions with their detailed answers, syntax examples, and real-world use cases to help you ace your next interview.
This comprehensive resource is updated for 2025 and covers everything from basic queries to complex subqueries and performance tuning.
Why SQL Query Knowledge Is Crucial for Interviews
SQL remains one of the most in-demand skills in data-related jobs. Here’s why knowing SQL is important:
Data Retrieval & Manipulation: Almost every application interacts with data. SQL lets you fetch, insert, update, and delete data efficiently.
Data Analysis: SQL is a core tool for analysts to make business decisions.
Job Versatility: SQL is required for roles like data analyst, business analyst, backend developer, database administrator (DBA), QA engineer, and more.
Interview Edge: Strong SQL skills can give you a competitive edge in interviews at top tech companies.
🔥 What You’ll Learn in This Post:
Commonly asked SQL interview questions (with answers)
Real-world SQL query examples
Differences between similar SQL clauses/functions
Tips for answering SQL interview questions effectively
✅ Basic SQL Query Interview Questions
1. What is SQL?
SQL (Structured Query Language) is used to manage and manipulate relational databases. It is used for creating, updating, retrieving, and deleting data.
2. What is a table in SQL?
A table is a collection of related data organized in rows and columns.
3. How to retrieve all data from a table?
SELECT * FROM table_name;
4. How to select specific columns?
SELECT column1, column2 FROM table_name;
5. How to filter records in SQL?
SELECT * FROM employees WHERE department = 'HR';
6. What is the use of WHERE clause?
It is used to filter records based on conditions.
7. What is the difference between WHERE and HAVING?
WHERE
: used before grouping.HAVING
: used afterGROUP BY
.
8. What is a primary key?
A column or set of columns that uniquely identifies each row.
9. What is a foreign key?
A foreign key is a field in one table that refers to the primary key in another table.
10. What is a NULL value?
NULL represents missing or undefined data.
✅ Intermediate SQL Query Interview Questions
11. How to sort records in ascending order?
SELECT * FROM employees ORDER BY name ASC;
12. How to sort records in descending order?
SELECT * FROM employees ORDER BY salary DESC;
13. How to use the IN operator?
SELECT * FROM employees WHERE department IN ('HR', 'Finance');
14. What is the LIKE operator?
Used for pattern matching.
SELECT * FROM employees WHERE name LIKE 'A%';
15. What is BETWEEN in SQL?
SELECT * FROM employees WHERE salary BETWEEN 50000 AND 100000;
16. How to count records?
SELECT COUNT(*) FROM employees;
17. How to find maximum salary?
SELECT MAX(salary) FROM employees;
18. How to find average salary?
SELECT AVG(salary) FROM employees;
19. What does GROUP BY do?
Groups rows with the same values in specified columns.
20. How to group data and get count?
SELECT department, COUNT(*) FROM employees GROUP BY department;
✅ Joins in SQL Interview Questions
21. What is an INNER JOIN?
Returns records that have matching values in both tables.
SELECT e.name, d.name
FROM employees e
INNER JOIN departments d ON e.dept_id = d.id;
22. What is a LEFT JOIN?
Returns all records from the left table and matching records from the right table.
23. What is a RIGHT JOIN?
Opposite of LEFT JOIN.
24. What is a FULL JOIN?
Returns all records from both tables.
25. What is a SELF JOIN?
A join of a table with itself.
✅ Advanced SQL Query Questions
26. How to find duplicate records?
SELECT name, COUNT(*)
FROM employees
GROUP BY name
HAVING COUNT(*) > 1;
27. How to delete duplicates but keep one?
DELETE FROM employees
WHERE id NOT IN (
SELECT MIN(id)
FROM employees
GROUP BY name, salary
);
28. What is a subquery?
A query inside another query.
29. Example of correlated subquery?
SELECT name
FROM employees e
WHERE salary > (
SELECT AVG(salary)
FROM employees
WHERE department = e.department
);
30. How to fetch the second highest salary?
SELECT MAX(salary)
FROM employees
WHERE salary < (
SELECT MAX(salary) FROM employees
);
✅ SQL Functions and Clauses
31. What are aggregate functions in SQL?
SUM()
,AVG()
,COUNT()
,MIN()
,MAX()
32. What is the difference between CHAR and VARCHAR?
CHAR | VARCHAR |
---|---|
Fixed length | Variable length |
Takes up full size | Optimized space |
33. What are string functions in SQL?
UPPER()
,LOWER()
,LENGTH()
,SUBSTRING()
,TRIM()
34. How to update records in SQL?
UPDATE employees SET salary = salary + 5000 WHERE department = 'HR';
35. How to delete records?
DELETE FROM employees WHERE salary < 30000;
36. How to insert new records?
INSERT INTO employees (name, department, salary) VALUES ('Ankit', 'IT', 55000);
37. How to add a new column?
ALTER TABLE employees ADD COLUMN age INT;
38. How to change column data type?
ALTER TABLE employees MODIFY age VARCHAR(10);
39. What is a view in SQL?
A virtual table based on the result-set of a query.
40. How to create a view?
CREATE VIEW high_salary AS
SELECT name, salary FROM employees WHERE salary > 100000;
✅ SQL Query-Based Interview Scenarios
41. List top 5 highest-paid employees.
SELECT * FROM employees ORDER BY salary DESC LIMIT 5;
42. Find employees whose name starts with ‘S’ and ends with ‘h’.
SELECT * FROM employees WHERE name LIKE 'S%h';
43. Count number of employees in each department.
SELECT department, COUNT(*) FROM employees GROUP BY department;
44. Find employees hired in the last 3 months.
SELECT * FROM employees WHERE hire_date >= CURDATE() - INTERVAL 3 MONTH;
45. Find all departments without any employees.
SELECT *
FROM departments d
LEFT JOIN employees e ON d.id = e.dept_id
WHERE e.id IS NULL;
✅ Top SQL Interview Questions for Experienced Professionals
46. What are window functions?
They perform calculations across a set of table rows related to the current row.
SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees;
47. Difference between RANK(), DENSE_RANK(), and ROW_NUMBER()
Function | Gaps in Rank | Use Case |
---|---|---|
RANK() | Yes | Ranking with gaps |
DENSE_RANK() | No | Ranking without gaps |
ROW_NUMBER() | Unique | Row indexing |
48. How to perform case-insensitive search?
SELECT * FROM employees WHERE LOWER(name) = 'john';
49. What is indexing in SQL?
Indexing improves the speed of data retrieval but may slow down inserts/updates.
50. Types of indexes?
Primary
Unique
Composite
Full-text
51. What is a CTE (Common Table Expression)?
A CTE is a temporary result set used to simplify complex joins and subqueries.
WITH TopSalaries AS (
SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 3
)
SELECT * FROM TopSalaries;
52. What is the difference between UNION and UNION ALL?
UNION
: Removes duplicates.UNION ALL
: Keeps duplicates.
53. How to get the highest salary per department?
SELECT department, MAX(salary)
FROM employees
GROUP BY department;
54. How to find all employees who report to the same manager?
SELECT manager_id, COUNT(*) FROM employees GROUP BY manager_id;
55. What is normalization?
It is the process of organizing data to reduce redundancy and improve integrity.
56. What are the different normal forms?
1NF: Atomic columns
2NF: Remove partial dependency
3NF: Remove transitive dependency
57. What is denormalization?
A process to improve read performance by combining tables.
58. How to find records that exist in one table but not in another?
SELECT * FROM orders o
WHERE NOT EXISTS (
SELECT 1 FROM payments p WHERE o.id = p.order_id
);
59. What is the difference between EXISTS and IN?
EXISTS
: Stops on the first match (faster in many cases)IN
: Loads all values before matching
60. How to transpose rows into columns?
Using conditional aggregation:
SELECT department,
MAX(CASE WHEN gender = 'M' THEN name END) AS male,
MAX(CASE WHEN gender = 'F' THEN name END) AS female
FROM employees
GROUP BY department;
61. How to find Nth highest salary?
SELECT salary FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees
) tmp WHERE rnk = 3;
62. What is the difference between DELETE and TRUNCATE?
DELETE
: Logs each row, can have WHERE clauseTRUNCATE
: Faster, cannot rollback in some DBs
63. How to fetch alternate rows from a table?
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY id) as rn FROM employees
) tmp WHERE MOD(rn, 2) = 1;
64. How to get cumulative sum in SQL?
SELECT name, salary,
SUM(salary) OVER (ORDER BY id) AS cumulative_salary
FROM employees;
65. How to find gaps in a sequence?
SELECT id + 1 AS missing_id
FROM employees e
WHERE NOT EXISTS (
SELECT 1 FROM employees WHERE id = e.id + 1
);
66. Difference between RANK, DENSE_RANK, and ROW_NUMBER?
Function | Gaps | Same Rank? |
---|---|---|
RANK | Yes | Yes |
DENSE_RANK | No | Yes |
ROW_NUMBER | No | No |
67. How to use CASE in SQL?
SELECT name,
CASE
WHEN salary > 100000 THEN 'High'
WHEN salary BETWEEN 50000 AND 100000 THEN 'Medium'
ELSE 'Low'
END AS salary_range
FROM employees;
68. What is a surrogate key?
An artificial key used to uniquely identify a row (like an auto-increment ID).
69. How to get records from the last 7 days?
SELECT * FROM orders WHERE order_date >= CURDATE() - INTERVAL 7 DAY;
70. How to check if a table exists?
SELECT * FROM information_schema.tables WHERE table_name = 'employees';
71. How to find common records in two tables?
SELECT * FROM table1
INTERSECT
SELECT * FROM table2;
72. How to remove duplicates from a table?
Use ROW_NUMBER()
and delete where row > 1.
73. How to rename a column in SQL?
ALTER TABLE employees RENAME COLUMN old_name TO new_name;
74. How to handle NULL in aggregate functions?
Use COALESCE()
SELECT AVG(COALESCE(salary, 0)) FROM employees;
75. How to check if a column has only unique values?
SELECT COUNT(column), COUNT(DISTINCT column) FROM table;
76. How to get top 3 salaries department-wise?
Use DENSE_RANK()
partitioned by department.
77. How to implement pagination in SQL?
SELECT * FROM employees LIMIT 10 OFFSET 20;
78. What is ACID in SQL?
Atomicity
Consistency
Isolation
Durability
79. What is a transaction?
A set of SQL operations performed as a single unit.
80. What are isolation levels?
Read Uncommitted
Read Committed
Repeatable Read
Serializable
81. How to check duplicate emails?
SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1;
82. What is the difference between HAVING and WHERE?
WHERE
: filters before aggregationHAVING
: filters after aggregation
83. What is a stored procedure?
A saved SQL code that you can reuse.
84. How to execute a stored procedure?
CALL procedure_name();
85. How to pass parameters to procedures?
CALL get_employees_by_dept('HR');
86. What is an alias?
A temporary name for a column or table.
SELECT name AS employee_name FROM employees;
87. What is a schema?
Logical structure of the database.
88. What is a composite key?
A key made from two or more columns.
89. What is a constraint?
Rules applied to table columns (e.g., NOT NULL, UNIQUE)
90. How to change a table name?
ALTER TABLE old_name RENAME TO new_name;
91. How to find max salary of each job title?
SELECT job_title, MAX(salary) FROM employees GROUP BY job_title;
92. How to fetch even rows from a table?
Using MOD or %
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER () as rn FROM employees
) tmp WHERE rn % 2 = 0;
93. What is a cross join?
Returns Cartesian product of two tables.
94. How to find departments with more than 5 employees?
SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 5;
95. How to use INSTR and SUBSTRING?
SELECT SUBSTRING(name, 1, 3), INSTR(name, 'a') FROM employees;
96. How to get current date/time in SQL?
SELECT NOW();
97. What is the difference between NOW() and GETDATE()?
NOW(): MySQL
GETDATE(): SQL Server
98. How to convert string to date?
SELECT STR_TO_DATE('25-06-2025', '%d-%m-%Y');
99. What is COALESCE()?
Returns first non-null value.
100. How to export query results to CSV?
In MySQL:
SELECT * FROM employees
INTO OUTFILE '/tmp/employees.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
✅ Final Words: Master SQL to Crack Your Next Interview
These top 100 SQL query interview questions cover everything from beginner concepts to advanced-level query handling. By practicing these questions, you’ll not only be better prepared for interviews but also sharpen your real-world SQL skills.
💡 Pro Tips:
Practice on real databases like MySQL, PostgreSQL, or SQL Server.
Try to write queries without looking at answers.
Use platforms like LeetCode, Hackerrank for SQL-based challenges.
If you’re preparing for interviews , bookmark this page and revise these questions regularly. Want more such content? Visit TopInterviewQuestions.in for more in-depth guides.