A subquery is a query nested inside another query. It helps to filter or calculate values based on the results of the inner query.
Subqueries can be used in WHERE to filter rows, in FROM to create temporary tables, and in SELECT to compute values.
SELECT employee_id FROM employees WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = 10);
The subquery calculates the average salary for department 10. The outer query selects employees whose salary is greater than this average.
SELECT e1.employee_id FROM employees e1 WHERE salary > (SELECT AVG(salary) FROM employees e2 WHERE e1.department_id = e2.department_id);
What error or issue will this query produce?
This is a correlated subquery comparing each employee's salary to the average salary of their department. It runs correctly and returns expected results.
- departments(department_id, department_name)
- employees(employee_id, department_id, salary)
What is the number of rows returned by this query?
SELECT department_id FROM departments WHERE department_id IN (SELECT department_id FROM employees WHERE salary > 50000);
The subquery returns department IDs where employees earn more than 50000. The outer query returns those departments only, so the count equals departments with such employees.
