Open In App

Nested Queries in SQL

Prerequisites : Basics of SQL

Nested queries are a way to perform complex queries by embedding one query within another. The outer query can apply some conditions on the results of the inner query. Let usl use STUDENT, COURSE, STUDENT_COURSE tables for understanding nested queries.  



STUDENT

S_ID S_NAME S_ADDRESS S_PHONE S_AGE
S1 RAM DELHI 9455123451 18
S2 RAMESH GURGAON 9652431543 18
S3 SUJIT ROHTAK 9156253131 20
S4 SURESH DELHI 9156768971 18

COURSE



C_ID C_NAME
C1 DSA
C2 Programming
C3 DBMS

STUDENT_COURSE

S_ID C_ID
S1 C1
S1 C3
S2 C1
S3 C2
S4 C2
S4 C3

  There are mainly two types of nested queries:

EXAMPLE IN SQL CODE:

SELECT StudentName

FROM Students

WHERE StudentID IN (

SELECT StudentID

FROM Grades

WHERE Subject = ‘Mathematics’ AND Score > 90

);


Article Tags :