A nested query (also called a subquery) is a query embedded within another SQL query. The result of the inner query is used by the outer query to perform additional operations. Subqueries can be used in various parts of an SQL query such as SELECT, FROM or WHERE Clauses.
Nested queries are highly useful when:
To better understand nested queries, we will use the following sample tables: STUDENT, COURSE, and STUDENT_COURSE. These tables demonstrate a real-world scenario of students, courses and their enrollment details, which will be used in the examples below.
1. STUDENT TableThe STUDENT table stores information about students, including their unique ID, name, address, phone number, and age.
STUDENT TABLE 2. COURSE TableThe STUDENT_COURSE table maps students to the courses they have enrolled in. It uses the student and course IDs as foreign keys.
COURSE TABLE3. STUDENT_COURSE Table
This table maps students to the courses they have enrolled in, with columns for student ID (S_ID) and course ID (C_ID):
STUDENT COURSE TABLE Types of Nested Queries in SQLThere are two primary types of nested queries in SQL, Independent Nested Queries and Correlated Nested Queries. Each type has its own use case and benefits depending on the complexity of the task at hand.
1. Independent Nested QueriesIn an independent nested query, the execution of the inner query is independent of the outer query. The inner query runs first and its result is used directly by the outer query. Operators like IN, NOT IN, ANY and ALL are commonly used with independent nested query.
Example 1: Using INIn this Example we will find the S_IDs of students who are enrolled in the courses ‘DSA’ or ‘DBMS’. We can break the query into two parts:
Step 1: Find the C_IDs of the courses:This query retrieves the IDs of the courses named 'DSA' or 'DBMS' from the COURSE table.
SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'DBMS');
Output
Step 2: Use the result of Step 1 to find the corresponding S_IDs:The inner query finds the course IDs, and the outer query retrieves the student IDs associated with those courses from the STUDENT_COURSE table
SELECT S_ID FROM STUDENT_COURSE WHERE C_ID IN (
SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'DBMS')
);
Output
Explanation: In this example, the inner query retrieves the C_IDs
of the courses 'DSA' and 'DBMS', and the outer query retrieves the student IDs (S_IDs
) enrolled in those courses.
In correlated nested queries, the inner query depends on the outer query for its execution. For each row processed by the outer query, the inner query is executed. This means the inner query references columns from the outer query. The EXISTS keyword is often used with correlated queries.
Example 2: Using EXISTSIn this Example, we will find the names of students who are enrolled in the course with C_ID = 'C1':
SELECT S_NAME FROM STUDENT S
WHERE EXISTS (
SELECT 1 FROM STUDENT_COURSE SC
WHERE S.S_ID = SC.S_ID AND SC.C_ID = 'C1'
);
Output
Explanation:
For each student in the STUDENT table, the inner query checks if an entry exists in the STUDENT_COURSE table with the same S_ID and the specified C_ID. If such a record exists, the student’s name is included in the output.
Common SQL Operators for Nested QueriesSQL provides several operators that can be used with nested queries to filter, compare, and perform conditional checks.
1. IN OperatorThe IN operator is used to check whether a column value matches any value in a list of values returned by a subquery. This operator simplifies queries by avoiding the need for multiple OR conditions.
Example: Retrieve student names who enrolled in ‘DSA’ or ‘DBMS’:This query filters the students enrolled in the specified courses by chaining multiple nested queries.
2. NOT IN OperatorSELECT S_NAME FROM STUDENT
WHERE S_ID IN (
SELECT S_ID FROM STUDENT_COURSE
WHERE C_ID IN (
SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'DBMS')
)
);
The NOT IN operator excludes rows based on a set of values from a subquery. It is particularly useful for filtering out unwanted results. This operator helps identify records that do not match the conditions defined in the subquery.
Example: Retrieve student IDs not enrolled in ‘DSA’ or ‘DBMS’:This query excludes students who are enrolled in the courses 'DSA' or 'DBMS'.
SELECT S_ID FROM STUDENT
WHERE S_ID NOT IN (
SELECT S_ID FROM STUDENT_COURSE
WHERE C_ID IN (
SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'DBMS')
)
);
Output
3. EXISTS OperatorThe EXISTS operator checks for the existence of rows in a subquery. It returns true if the subquery produces any rows, making it efficient for conditional checks. This operator is often used to test for relationships between tables.
Example: Find student names enrolled in ‘DSA'The inner query checks for matching records in the STUDENT_COURSE table, and the outer query returns the corresponding student names.
4. ANY and ALL OperatorsSELECT S_NAME FROM STUDENT S
WHERE EXISTS (
SELECT 1 FROM STUDENT_COURSE SC
WHERE S.S_ID = SC.S_ID AND SC.C_ID = 'C1'
);
ANY
: Compares a value with any value returned by the subquery.ALL
: Compares a value with all values returned by the subquery.Example using ALL:SELECT S_NAME FROM STUDENT
WHERE S_AGE > ANY (
SELECT S_AGE FROM STUDENT WHERE S_ADDRESS = 'DELHI'
);
Advantages of Nested QueriesSELECT S_NAME FROM STUDENT
WHERE S_AGE > ALL (
SELECT S_AGE FROM STUDENT WHERE S_ADDRESS = 'DELHI'
);
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4