Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Unit 2: Introduction to Nested and Correlated Queries

Lesson 23 of 28 in the free Database Management Systems notes on Siksha Sarovar, written by Rohit Jangra.

23.1 What is a Subquery?

A Subquery (or Nested Query) is a query within another SQL query. It is typically used to provide a value or a set of values to the outer query.

23.2 Types of Nested Queries

1. Independent (Non-Correlated) Subquery

The inner query is independent of the outer query. It runs once, returns a result, and the outer query uses that result.

  • Example: "Find employees whose salary is more than the average salary."
    SELECT Name FROM Emp 
    WHERE Salary > (SELECT AVG(Salary) FROM Emp);

2. Correlated Subquery

The inner query refers to a column from the outer query. The inner query is executed once for every row processed by the outer query.

  • Example: "Find employees who earn more than the average salary in their department."
    SELECT e1.Name FROM Emp e1 
    WHERE e1.Salary > (SELECT AVG(e2.Salary) FROM Emp e2 WHERE e2.DeptID = e1.DeptID);

23.3 Set-Comparison Operators

When a subquery returns multiple rows, we use special operators:

OperatorMeaning
INEqual to any member in the list.
ANY / SOMECompares a value to each value in the list (e.g., > ANY means greater than the minimum).
ALLCompares a value to every value in the list (e.g., > ALL means greater than the maximum).
EXISTSTrue if the subquery returns at least one row.