Chapter 6 SQL Nested Queries
Chapter 6 SQL Nested Queries
1
Nested Queries in SQL
.
Covers
Common SQL Operators
for Nested Queries
2
Nested Queries in SQL
Θ The result of the inner query is used by the outer query to perform further
operations.
3
Key Characteristics of Nested Queries
Θ The inner query runs first, providing data for the outer query.
Θ The output query uses the results of the inner query for comparison or as
input.
Θ Nested queries are particularly useful for breaking down complex problems
into smaller, manageable parts, making it easier to retrieve specific results
4
Key Characteristics of Nested Queries
Θ To better understand nested queries, we will use the following sample tables: STUDENT,
COURSE, and STUDENT_COURSE. These tables simulate a real-world scenario of students,
courses, and their enrollment details.
1) STUDENT Table
create table STUDENT
S_ID S_NAME S_ADRESS S_PHONE S_AGE
(
S_ID varchar(5) primary key,
S_NAME varchar(20) NOT NULL, S1 Mahider Hawassa 915487598 28
S_ADRESS varchar(15) NOT NULL, S2 Yonas A.A 985874698 29
S_PHONE int,
S_AGE int S3 Dagim Diredawa 916857895 32
)
S4 Fikir Hawassa 941896584 25
insert into STUDENT values
('S1','Mahider','Hawassa',915487598,28),
('S2','Yonas','A.A',985874698,29),
('S3','Dagim','Diredawa',916857895,32),
('S4','Fikir','Hawassa',941896584,25)
5
Key Characteristics of Nested Queries
2) COURSE Table
• The STUDENT_COURSE table maps students to the courses they have enrolled in. It uses
the student and course IDs as foreign keys.
create table COURSE
(
C_ID varchar(5) primary key, C_ID C_NAME
C_NAME varchar(15) NOT NULL
) C1 DSA
('C3','OOP')
6
Key Characteristics of Nested Queries
3) 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):
create table STUDENT_COURSE
(
S_ID Varchar(5),
C_ID varchar(5),
primary key(S_ID,C_ID),
foreign key (S_ID) references STUDENT(S_ID),
foreign key (C_ID) references COURSE(C_ID)
) S_ID C_ID
insert into STUDENT_COURSE values S1 C1
('S1','C1'), S1 C3
('S1','C3'), S2 C1
('S2','C1'), S3 C2
('S3','C2'), S4 C2
('S4','C2'), S4 C3
('S4','C3') 7
Types of Nested Queries
ΘThere 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.
ΘIn 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.
8
Types of Nested Queries
Example 1: Using IN
Θ In this Example we will find the S_IDs of students who are enrolled in the courses ‘DSA’ or
‘OOP’. We can break the query into two parts:
Θ This query retrieves the IDs of the courses named ‘DSA’ or ‘OOP’ from the COURSE
table.
Θ Output C_ID
C1
C3
9
Types of Nested Queries
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', 'OOP')
);
S_ID
• Output
S1
S1
S2
S4
• Explanation: In this example, the inner query retrieves the C_IDs of the courses
‘DSA’ and ‘OOP’, and the outer query retrieves the student IDs (S_IDs) enrolled in
those courses.
10
Types of Nested Queries
ii. Correlated Nested Queries
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 EXISTS
• In this Example, we will find the names of students who are enrolled in the course with
C_ID = ‘C1’:
SELECT S_NAME FROM STUDENT WHERE EXISTS S_NAME
(
Mahider
SELECT 1 FROM STUDENT_COURSE SC
WHERE S.S_ID = SC.S_ID AND SC.C_ID = 'C1'
Yonas
);
• Output
11
Types of Nested Queries
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.
12
Common SQL Operators for Nested Queries
Θ SQL provides several operators that can be used with nested queries to filter, compare, and
perform conditional checks.
1) IN Operator
Θ The 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 ‘OOP’:
Θ This query filters the students enrolled in the specified courses by chaining multiple nested queries.
SELECT S_NAME FROM STUDENTWHERE S_ID IN
(
SELECT S_ID FROM STUDENT_COURSEWHERE C_ID IN
(
SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'OOP’)
)
) S_NAME
Mahider
Yonas
Fikir 13
Common SQL Operators for Nested Queries
2) NOT IN Operator
Θ 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 STUDENTWHERE S_ID NOT IN
(
SELECT S_ID FROM STUDENT_COURSEWHERE C_ID IN
(
SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'OOP’)
)
);
Θ Output
S_ID
S3
14
Common SQL Operators for Nested Queries
3) EXISTS Operator
Θ The 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.
Θ The inner query checks for matching records in the STUDENT_COURSE table, and the
outer query returns the corresponding student names.
SELECT S_NAME FROM STUDENT SWHERE EXISTS
(
SELECT 1 FROM STUDENT_COURSE SCWHERE S.S_ID = SC.S_ID AND SC.C_ID = 'C1'
);
S_NAME
Mahider
Yonas
15
Common SQL Operators for Nested Queries
4) ANY and ALL Operators
Θ ANY: Compares a value with any value returned by the subquery.
Θ ALL: Compares a value with all values returned by the subquery.
Θ Example using ANY:
17
Advantages of Nested Queries
Θ Simplifies complex queries: Nested queries allow us to divide complicated SQL tasks into
smaller, more manageable parts. This modular approach makes queries easier to write,
debug, and maintain.
Θ Enhances flexibility: By enabling the use of results from one query within another, nested
queries allow dynamic filtering and indirect joins, which can simplify query logic.
Θ Improves readability: When properly written, nested queries can make complex
operations more intuitive by encapsulating logic within inner queries.
18
Thank You!
19