A subquery is a query nested within another query to provide intermediate results for the main query.
Subqueries can appear in the:
SELECT clause: To compute derived columns.
FROM clause: To use as a temporary table or result set.
WHERE clause: To filter data using conditions derived from another query.
Subqueries are enclosed in parentheses (). There are different types of subqueries,
Single-row Subquery: Returns one row.
Multi-row Subquery: Returns multiple rows.
Correlated Subquery: References columns from the outer query, making it dependent on the outer query's execution.
Non-correlated Subquery: Independent of the outer query.
Lets look at an example to better understand this. We are going to use the same data we’ve used in the previous articles. Please refer to https://themathlab.hashnode.dev/exploring-sql-concepts-for-beginners.
Lets say we want to see the employees who are earning more than the average salary of the company.
SELECT name, salary, department
FROM employees
WHERE salary > (SELECT AVG(Salary) from employees);
Lets look at a bit more complex question. Lets say you want to show the employee records along with the average salary of their respective department.
SELECT e.name, e.salary, e.department, d.avg_salary AS Average_Department_Salary
FROM employees e
JOIN (SELECT department, AVG(salary) AS avg_salary FROM employees GROUP BY department) d
ON e.department=d.department;
That’s all for SQL subqueries. You can access my notes on my GitHub Repository at https://github.com/isuri-balasooriya2/TheMathLab/.