SQL Subquery Basics
Learn SQL through interactive, bite-sized lessons. Master database queries and data manipulation.
Start SQL Journey →Subqueries are a powerful feature in SQL that allow you to nest one query within another. They provide a way to perform complex operations and retrieve data based on the results of another query.
What is a Subquery?
A subquery, also known as a nested query or inner query, is a SELECT statement embedded within another SQL statement. It can be used in various parts of a main query, such as the SELECT, FROM, or WHERE clauses.
Basic Syntax
The general structure of a subquery is as follows:
SELECT column1, column2, ...
FROM table_name
WHERE column_name operator (SELECT column_name FROM table_name WHERE condition);
The subquery is enclosed in parentheses and typically appears on the right side of a comparison operator.
Types of Subqueries
1. Single-row Subquery
Returns only one row and can be used with single-row operators like =, >, <, >=, <=, and <>.
2. Multiple-row Subquery
Returns multiple rows and is used with multiple-row operators such as IN, ANY, or ALL.
3. Correlated Subquery
References columns from the outer query and is executed once for each row in the outer query.
Examples
Example 1: Single-row Subquery
SELECT employee_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
This query selects employees whose salary is above the average salary.
Example 2: Multiple-row Subquery
SELECT product_name, price
FROM products
WHERE product_id IN (SELECT product_id FROM orders WHERE order_date = '2023-05-01');
This query retrieves products that were ordered on a specific date.
Best Practices
- Use subqueries sparingly, as they can impact performance on large datasets.
- Consider using SQL joins as an alternative when appropriate.
- Ensure that the subquery returns the expected number of rows (single or multiple).
- Test subqueries independently before incorporating them into the main query.
Common Use Cases
Subqueries are particularly useful for:
- Filtering data based on aggregate results
- Performing complex comparisons
- Creating derived tables in the FROM clause
- Implementing dynamic filtering conditions
Limitations and Considerations
While subqueries are versatile, they have some limitations:
- Performance may degrade with deeply nested subqueries
- Some databases have restrictions on subquery placement or depth
- Correlated subqueries can be slow on large datasets
Understanding these basics will help you leverage subqueries effectively in your SQL queries, enabling more complex and powerful data retrieval operations.