SQL questions and answers

Joins, grouping, subqueries and query output. Practise sql questions from the technical & programming section of placement tests, with a worked explanation after every answer. Practice is free and needs no sign-up.

Sample sql questions with worked answers

Question 1

Which SQL clause is used to filter groups formed by GROUP BY, for example to keep only departments whose average salary exceeds a limit?

  1. WHERE
  2. ORDER BY
  3. HAVING
  4. GROUP BY

Answer: C. HAVING

Explanation: WHERE filters individual rows before grouping, and HAVING filters groups after aggregation. A condition on an aggregate such as AVG(salary) belongs in HAVING.

Question 2

Using a table Employee(id, name, dept, salary), which of the following queries is INVALID in standard SQL?

  1. SELECT dept FROM Employee WHERE AVG(salary) > 40000 GROUP BY dept
  2. SELECT dept FROM Employee GROUP BY dept HAVING AVG(salary) > 40000
  3. SELECT dept, MAX(salary) FROM Employee GROUP BY dept
  4. SELECT COUNT(*) FROM Employee WHERE salary > 40000

Answer: A. SELECT dept FROM Employee WHERE AVG(salary) > 40000 GROUP BY dept

Explanation: WHERE is evaluated row by row before grouping, so aggregate functions are not allowed in it. The condition on AVG(salary) has to go in HAVING.

Question 3

Table Employee:
id | name | dept | salary
1 | Asha | HR | 30000
2 | Ravi | IT | 50000
3 | Neha | IT | 60000
4 | Karan | Sales | NULL
5 | Priya | HR | 45000
6 | Vikram | IT | 50000

Table Projects has one column emp_id with rows: 1, 3, NULL

What does this query return?

SELECT COUNT(*)
FROM Employee
WHERE id NOT IN (SELECT emp_id FROM Projects);
  1. 4
  2. 3
  3. 0
  4. 6

Answer: C. 0

Explanation: x NOT IN (1, 3, NULL) means x <> 1 AND x <> 3 AND x <> NULL. The comparison with NULL is UNKNOWN, so the condition is never TRUE and no rows qualify. The count is 0.

All 30 sql questions with answers

SQL: common questions

What are sql questions?

Joins, grouping, subqueries and query output. They appear in the technical & programming section of many placement tests.

Where can I practise sql questions with answers for free?

Right here on LogicWiz Exams. Every sql question has a worked explanation after you answer. Practice is free and needs no sign-up.

How should I practise sql?

Start with easy questions, then move to medium and hard. Read the explanation after each answer, and come back to the ones you missed.

Start practising

On this page you can start a fresh set of sql questions, choose easy, medium or hard, and time yourself if you want to. Or practise the whole subject: Technical & Programming practice.

More technical & programming topics

Other subjects

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge · Test from a job description · LogicWiz Open: free team quiz · Free interview prep