- Subqueries (also known as inner queries or nested queries) are “a tool for performing operations in multiple steps”.
- For example, if you wanted to take the sums of several columns, then average all of those values, you’d need to do each aggregation in a distinct step.
Sure! Here’s an example of a subquery in SQL:
Let’s say we have two tables: “Employees” and “Departments.” The “Employees” table contains information about employees, including their names and department IDs. The “Departments” table contains information about departments, including their names and department IDs.
We want to retrieve the names of all employees who work in the “Sales” department. We can achieve this using a subquery. Here’s how the SQL query would look like:
<span class="hljs-keyword">SELECT</span> name
<span class="hljs-keyword">FROM</span> Employees
<span class="hljs-keyword">WHERE</span> department_id <span class="hljs-operator">=</span> (
<span class="hljs-keyword">SELECT</span> department_id
<span class="hljs-keyword">FROM</span> Departments
<span class="hljs-keyword">WHERE</span> department_name <span class="hljs-operator">=</span> <span class="hljs-string">'Sales'</span>
);
In this example, the subquery (SELECT department_id FROM Departments WHERE department_name = 'Sales') retrieves the department ID for the “Sales” department from the “Departments” table. The outer query then uses this department ID to retrieve the names of employees from the “Employees” table who belong to that department.
The result of this query will be the names of all employees who work in the “Sales” department.
