Show List
Subqueries
A subquery in SQL is a query that is nested inside another query. It is used to retrieve data that will be used in the main query as a condition. Subqueries can be used in several parts of a SQL statement, such as the SELECT
, FROM
, WHERE
, and HAVING
clauses.
Here are a few examples of using subqueries in SQL:
Using a subquery in the
FROM
clause:
vbnetCopy code
SELECT column1, column2
FROM (SELECT column3, column4
FROM table2) AS subquery_alias
WHERE column1 = 'value';
Using a subquery in the WHERE
clause:
sqlCopy code
SELECT column1, column2
FROM table1
WHERE column1 = (SELECT column3
FROM table2
WHERE column4 = 'value');
Using a subquery in the SELECT
clause:
sqlCopy code
SELECT column1,
(SELECT AVG(column3)
FROM table2
WHERE table2.column4 = table1.column2) AS avg_column3
FROM table1;
Using multiple subqueries in a single SQL statement:
sqlCopy code
SELECT column1, column2, column3,
(SELECT COUNT(*)
FROM table3
WHERE table3.column4 = table1.column2) AS count_column4,
(SELECT AVG(column5)
FROM table4
WHERE table4.column6 = table2.column3) AS avg_column5
FROM table1
INNER JOIN table2
ON table1.column1 = table2.column1;
Leave a Comment