What is a SQL Query Subquery?
A subquery (also known as an inner select or nested query) is a query nested inside another SQL query. It allows you to build more complex queries by embedding one SELECT
statement within another. Subqueries can help solve problems that require multiple steps or aggregations, and they enable you to retrieve data dynamically based on the results of the subquery.
In this blog post, we’ll explore what a subquery is, how it works, and provide practical examples to illustrate its usefulness.
How Does a Subquery Work?
A subquery is simply a SELECT
statement enclosed in parentheses and used within another SQL query. The result of the subquery is passed on to the outer query for further processing.
Here’s a basic structure of a query using a sql query subquery:
SELECT column1, column2FROM table1WHERE column1 IN (SELECT column1 FROM table2 WHERE condition);
In this example:
- The subquery retrieves values from
table2
that match a certain condition. - The outer query then uses the results of the subquery to filter records from
table1
.
Practical Use Cases for Subqueries
Let’s look at some real-world scenarios where subqueries come in handy.
Example 1: Filtering Results Based on Another Query
Suppose you have two tables:
- Employees: Contains information about employees in a company.
- Departments: Contains department data, such as department names and IDs.
You want to retrieve all employees who work in the “Sales” department. One way to achieve this is by using a subquery.
SELECT employee_nameFROM EmployeesWHERE department_id = (SELECT department_id FROM Departments WHERE department_name = 'Sales');
In this query:
- The subquery retrieves the
department_id
where thedepartment_name
is “Sales”. - The outer query selects all employees from the
Employees
table whosedepartment_id
matches the result of the subquery.
This is particularly useful when the department ID is unknown and needs to be looked up dynamically.
Example 2: Aggregating Data with a Subquery
Subqueries are also helpful when calculating aggregates to use in the outer query. For example, let’s say you want to list all employees who earn more than the average salary.
SELECT employee_name, salaryFROM EmployeesWHERE salary > (SELECT AVG(salary) FROM Employees);
In this case:
- The subquery calculates the average salary of all employees.
- The outer query retrieves the names and salaries of employees whose salary exceeds that average.
Here, the subquery is performing an aggregate function (AVG
) on the same table (Employees
), but in a different context.
Example 3: Using Subqueries in the FROM
Clause
A subquery can also be used in the FROM
clause of an SQL statement, effectively treating the result of the subquery as a derived table. This is useful for breaking down complex data manipulations.
Let’s say you want to find the highest salary in each department, and also retrieve the department names along with that information. You could write the query like this:
SELECT d.department_name, max_salaries.max_salaryFROM Departments dJOIN ( SELECT department_id, MAX(salary) AS max_salary FROM Employees GROUP BY department_id) max_salariesON d.department_id = max_salaries.department_id;
In this example:
- The SQL query subquery calculates the maximum salary per department.
- The outer query joins this result with the
Departments
table to get the corresponding department names.
Using subqueries in the FROM
clause allows for cleaner, more modular queries, especially when dealing with complex aggregations or derived data sets.
When Should You Use a Subquery?
While subqueries are powerful, there are a few things to consider:
- Performance: Depending on the size and complexity of the data, subqueries can sometimes impact performance. In such cases, using joins or indexing may offer better results.
- Readability: Subqueries can make queries more complex. It’s important to ensure that your SQL remains readable and maintainable, particularly when combining multiple subqueries.
- Specific Use Cases: Subqueries are particularly useful when you need to generate results dynamically, such as when working with aggregate functions or retrieving data based on conditions from another query.
Conclusion SQL Query Subquery
Subqueries are a fundamental feature in SQL, enabling the creation of complex queries by nesting one query within another. Whether you need to filter results, perform aggregations, or create derived tables, subqueries give you flexibility and power in your SQL queries.
Want to learn more about TSQL programming and SQL Server?
Take a look at our SQL Server courses available at Stedmans SQL School.
Thanks and have a great day!
Steve Stedman
Founder/Owner — Stedman Solutions, LLC.
SQL Server DBA Services
Looking to schedule a meeting with me? Here is my availability: https://Stedman.us/schedule