SQL Query Interview Questions and Answers: 39 Practice Queries

Quick answer: These 39 SQL Query interview questions and answers cover what is asked most in data analyst, SQL developer and software engineer interviews: basic queries, aggregation and GROUP BY, joins, subqueries, window functions, and data modification and tricky queries, all on a simple employees, departments, customers and orders schema. Key answers include short code examples.

Read each answer, then close the page and explain it aloud in two or three sentences. That is exactly what interviewers check.

Contents

1. Basic Queries Interview Questions

Q1. Write a query to show all employees in the IT department, sorted by salary.

Filter with WHERE and sort with ORDER BY.

SELECT emp_id, name, salary
FROM employees
WHERE dept_id = 10
ORDER BY salary DESC;

Q2. Write a query to find employees whose name starts with 'A'.

Use LIKE with the % wildcard.

SELECT name FROM employees
WHERE name LIKE 'A%';

Q3. Write a query to find employees who joined in 2025.

Filter on a date range so an index on join_date can be used.

SELECT name, join_date FROM employees
WHERE join_date >= '2025-01-01'
  AND join_date <  '2026-01-01';

Q4. Write a query to find employees with no manager.

NULL must be tested with IS NULL, not = NULL.

SELECT name FROM employees
WHERE manager_id IS NULL;

Q5. Write a query to fetch the first 5 records.

LIMIT in MySQL and PostgreSQL, TOP in SQL Server, FETCH FIRST in standard SQL.

SELECT * FROM employees ORDER BY emp_id LIMIT 5;
-- SQL Server
SELECT TOP 5 * FROM employees ORDER BY emp_id;

Q6. Write a query to show unique department IDs.

DISTINCT removes duplicate values.

SELECT DISTINCT dept_id FROM employees;

2. Aggregation and GROUP BY Interview Questions

Q7. Write a query to count employees in each department.

GROUP BY with COUNT.

SELECT dept_id, COUNT(*) AS staff
FROM employees
GROUP BY dept_id;

Q8. Write a query to find departments with more than 5 employees.

Filter groups with HAVING.

SELECT dept_id, COUNT(*) AS staff
FROM employees
GROUP BY dept_id
HAVING COUNT(*) > 5;

Q9. Write a query to find the average, minimum and maximum salary per department.

Several aggregates in one GROUP BY query.

SELECT dept_id,
       ROUND(AVG(salary), 2) AS avg_sal,
       MIN(salary) AS min_sal,
       MAX(salary) AS max_sal
FROM employees
GROUP BY dept_id;

Q10. Write a query to find the total sales per month.

Group by year and month extracted from the date (MySQL functions shown).

SELECT YEAR(order_date) AS yr, MONTH(order_date) AS mon,
       SUM(amount) AS total_sales
FROM orders
GROUP BY YEAR(order_date), MONTH(order_date)
ORDER BY yr, mon;

Q11. Write a query to find duplicate email addresses.

Group by the column and keep groups with a count above 1.

SELECT email, COUNT(*) AS times
FROM users
GROUP BY email
HAVING COUNT(*) > 1;

Q12. Write a query to count male and female employees in one row.

Use conditional aggregation with CASE.

SELECT
  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;

3. Joins Interview Questions

Q13. Write a query to show employee names with their department names.

INNER JOIN on the department key.

SELECT e.name, d.dept_name
FROM employees e
JOIN departments d ON d.dept_id = e.dept_id;

Q14. Write a query to list all departments, including those with no employees.

Start from departments and LEFT JOIN employees.

SELECT d.dept_name, COUNT(e.emp_id) AS staff
FROM departments d
LEFT JOIN employees e ON e.dept_id = d.dept_id
GROUP BY d.dept_name;

Q15. Write a query to find customers who have never placed an order.

LEFT JOIN and keep rows with no match, or use NOT EXISTS.

SELECT c.name
FROM customers c
WHERE NOT EXISTS (
  SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);

Q16. Write a query to show each employee with their manager's name.

Self join the employees table.

SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.emp_id = e.manager_id;

Q17. Write a query to find employees who earn more than their manager.

Self join and compare salaries.

SELECT e.name, e.salary, m.name AS manager, m.salary AS mgr_salary
FROM employees e
JOIN employees m ON m.emp_id = e.manager_id
WHERE e.salary > m.salary;

Q18. Write a query to find products that were never ordered.

Anti-join between products and order items.

SELECT p.product_name
FROM products p
LEFT JOIN order_items oi ON oi.product_id = p.product_id
WHERE oi.product_id IS NULL;

Q19. Write a query to get total order value per customer, including customer name.

Join and aggregate.

SELECT c.name, SUM(o.amount) AS total_spent
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
ORDER BY total_spent DESC;
Preparing for a SQL Query interview? We run live one-to-one classes and mock interviews in SQL, Python and data analysis, arranged around your free time. Chat on WhatsApp.

4. Subqueries Interview Questions

Q20. Write a query to find the second highest salary.

Find the maximum salary below the overall maximum.

SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

Q21. Write a query to find employees who earn more than the company average.

Compare with a scalar subquery.

SELECT name, salary FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

Q22. Write a query to find employees who earn more than their department's average.

Use a correlated subquery.

SELECT e.name, e.dept_id, e.salary
FROM employees e
WHERE e.salary > (
  SELECT AVG(salary) FROM employees x WHERE x.dept_id = e.dept_id
);

Q23. Write a query to find the department with the highest total salary.

Aggregate, sort and take the first row.

SELECT dept_id, SUM(salary) AS total
FROM employees
GROUP BY dept_id
ORDER BY total DESC
LIMIT 1;

Q24. Write a query to find employees in departments located in Hyderabad.

Use IN with a subquery.

SELECT name FROM employees
WHERE dept_id IN (
  SELECT dept_id FROM departments WHERE location = 'Hyderabad'
);

5. Window Functions Interview Questions

Q25. Write a query to find the Nth highest salary (for example, 3rd).

DENSE_RANK handles ties correctly.

SELECT DISTINCT salary FROM (
  SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees
) t
WHERE rnk = 3;

Q26. Write a query to find the highest-paid employee in each department.

Rank within each department and keep rank 1.

SELECT dept_id, name, salary FROM (
  SELECT dept_id, name, salary,
         RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rnk
  FROM employees
) t
WHERE rnk = 1;

Q27. Write a query to get the top 3 earners in each department.

Same pattern with rank up to 3.

SELECT * FROM (
  SELECT dept_id, name, salary,
         DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rnk
  FROM employees
) t
WHERE rnk <= 3;

Q28. Write a query to calculate a running total of sales.

SUM as a window function ordered by date.

SELECT order_date, amount,
       SUM(amount) OVER (ORDER BY order_date) AS running_total
FROM orders;

Q29. Write a query to compare each month's sales with the previous month.

Use LAG to read the previous row.

WITH monthly AS (
  SELECT DATE_FORMAT(order_date, '%Y-%m') AS mon, SUM(amount) AS sales
  FROM orders GROUP BY DATE_FORMAT(order_date, '%Y-%m')
)
SELECT mon, sales,
       sales - LAG(sales) OVER (ORDER BY mon) AS change_from_prev
FROM monthly;

Q30. Write a query to number rows within each department.

ROW_NUMBER with PARTITION BY.

SELECT dept_id, name,
       ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY name) AS row_no
FROM employees;

Q31. Write a query to show each employee's salary as a percentage of their department total.

Divide by a windowed SUM.

SELECT name, dept_id, salary,
       ROUND(100.0 * salary / SUM(salary) OVER (PARTITION BY dept_id), 2) AS pct_of_dept
FROM employees;

6. Data Modification and Tricky Queries Interview Questions

Q32. Write a query to delete duplicate rows, keeping the one with the lowest ID.

A self join DELETE works in MySQL; ROW_NUMBER works in PostgreSQL and SQL Server.

-- MySQL
DELETE u1 FROM users u1
JOIN users u2
  ON u1.email = u2.email AND u1.id > u2.id;

Q33. Write a query to increase the salary of all IT employees by 10%.

UPDATE with a condition.

UPDATE employees
SET salary = salary * 1.10
WHERE dept_id = 10;

Q34. Write a query to copy the structure of a table without data.

Create a table from a query that returns no rows.

CREATE TABLE employees_backup AS
SELECT * FROM employees WHERE 1 = 0;

Q35. Write a query to find records present in one table but not in another.

Use NOT EXISTS (or EXCEPT in PostgreSQL and SQL Server).

SELECT id FROM table_a a
WHERE NOT EXISTS (SELECT 1 FROM table_b b WHERE b.id = a.id);

Q36. Write a query to find customers who ordered in every month of 2025.

Count distinct months per customer.

SELECT customer_id
FROM orders
WHERE order_date >= '2025-01-01' AND order_date < '2026-01-01'
GROUP BY customer_id
HAVING COUNT(DISTINCT MONTH(order_date)) = 12;

Q37. Write a query to find consecutive login days for each user.

Subtract a row number from the date: consecutive dates give the same group value (MySQL syntax).

WITH d AS (
  SELECT DISTINCT user_id, DATE(login_time) AS day FROM logins
), r AS (
  SELECT user_id, day,
         ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) AS rn
  FROM d
), g AS (
  SELECT user_id, day, DATE_SUB(day, INTERVAL rn DAY) AS grp FROM r
)
SELECT user_id, MIN(day) AS start_day, MAX(day) AS end_day, COUNT(*) AS streak
FROM g
GROUP BY user_id, grp
HAVING COUNT(*) >= 3;

Q38. Write a query to swap the values 'M' and 'F' in a gender column.

Use CASE inside UPDATE.

UPDATE employees
SET gender = CASE gender WHEN 'M' THEN 'F' WHEN 'F' THEN 'M' ELSE gender END;

Q39. What is the output of SELECT COUNT(*), COUNT(col) on a table with NULLs?

COUNT(*) counts all rows, while COUNT(col) skips rows where col is NULL. With 10 rows and 3 NULLs in col, the result is 10 and 7.

How to Prepare for a SQL Query Interview

  1. Write before you look: try each query yourself, then compare with the answer.
  2. Say your plan aloud: which tables, which join, which filter and which grouping.
  3. Watch for NULLs and duplicates: interviewers often test these edge cases.
  4. Learn two ways: for example, second highest salary with a subquery and with DENSE_RANK.
  5. Mention performance: indexes on join and filter columns.

Next steps: revise the concepts in our SQL interview questions, then try data science interview questions, and see all subjects on our interview questions page.

Want a mentor for your preparation? We teach SQL, Python and data analysis through live online classes arranged around your free time, with mock interviews before your placement. Message us on WhatsApp or email engineersrworld@gmail.com.

More interview preparation: see all interview questions, including Python, SQL, SQL query, Java, JavaScript, React, C++, .NET, Spring Boot, Node.js, DSA, OOPs, DBMS, operating system, networking, machine learning, data science, AI, Excel, Power BI, DevOps, manual testing, Selenium, cyber security and HR.

Frequently Asked Questions

Which SQL queries are asked most in interviews?

Second or Nth highest salary, duplicates, employees earning more than their manager, department-wise counts and averages, top N per group, customers with no orders, and running totals.

Which database syntax should I use in the interview?

Write standard SQL and mention differences when they matter, such as LIMIT versus TOP or date functions. Interviewers care more about logic than exact dialect.

How do I practise SQL queries?

Install MySQL or PostgreSQL, create a small employees, departments, customers and orders schema, and write each query on this page yourself before checking the answer.

Where can I learn the SQL theory behind these queries?

Read our SQL interview questions page for concepts such as keys, joins, normalization, indexes and transactions.

Scroll to Top