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.
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.
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.
Returns only one row and can be used with single-row operators like =, >, <, >=, <=, and <>.
Returns multiple rows and is used with multiple-row operators such as IN, ANY, or ALL.
References columns from the outer query and is executed once for each row in the outer query.
SELECT employee_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
This query selects employees whose salary is above the average salary.
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.
Subqueries are particularly useful for:
While subqueries are versatile, they have some limitations:
Understanding these basics will help you leverage subqueries effectively in your SQL queries, enabling more complex and powerful data retrieval operations.