In SQL, subqueries allow you to retrieve data from nested queries. Subqueries, also known as nested queries or inner queries, are queries embedded within another query. They can be used in various parts of a SQL statement, such as the SELECT, FROM, WHERE, and HAVING clauses. Here’s an overview of how to use subqueries to retrieve data from nested queries.
Table of Contents
ToggleSubqueries in the SELECT Clause
You can use subqueries within the SELECT clause to retrieve data based on the results of another query. The subquery is enclosed within parentheses and can be used as a column expression.
SELECT column1, (SELECT MAX(column2) FROM table2) AS max_value
FROM table1;
In this example, a subquery is used to retrieve the maximum value from “column2” of “table2”. The result of the subquery is included as a column named “max_value” in the main query’s result set.
Subqueries in the FROM Clause
You can use subqueries in the FROM clause to create a derived table, which is a temporary table constructed from the result of the subquery. The derived table can then be used as a data source for the main query.
SELECT t1.column1, t2.column2
FROM (SELECT column1 FROM table1) AS t1
JOIN (SELECT column2 FROM table2) AS t2 ON t1.id = t2.id;
In this query, two subqueries are used to create derived tables “t1” and “t2”. The derived tables are then joined based on a common column “id”.
Subqueries in the WHERE Clause
Subqueries can be used in the WHERE clause to filter data based on the results of another query. The subquery is typically used with comparison operators to perform the filtering.
SELECT column1, column2
FROM table1
WHERE column1 IN (SELECT column3 FROM table2);
The subquery retrieves values from “column3” of “table2”. The main query then selects rows from “table1” where “column1” matches any value returned by the subquery.
Subqueries in the HAVING Clause
You can use subqueries in the HAVING clause to filter grouped data based on the results of a subquery. The subquery is used to calculate aggregate values, which are then used in the HAVING clause for comparison.
SELECT column1, COUNT(column2) AS count
FROM table1
GROUP BY column1
HAVING COUNT(column2) > (SELECT AVG(column2) FROM table1);
The subquery calculates the average value of “column2” from “table1”. The HAVING clause filters groups based on the count of “column2” being greater than the average value returned by the subquery.
Subqueries provide a powerful way to retrieve data from nested queries and perform complex operations within SQL statements. They allow you to leverage the results of one query in another query, enabling you to manipulate and analyze data in a flexible and efficient manner.