Skip to content

NESTED QUERY

A nested SELECT is a query within a query, i.e. when a SELECT statement within the main SELECT.

SQL sub queries are a powerful tool. They allow us to perform tasks more efficiently by having only one query instead of several.

  • Sub queries can return single values or tables (with one or many rows and columns).
  • also include a sub query:

In the WHERE clause, to filter data.

In the FROM clause, to specify a new table.

In the SELECT clause, to specify a certain column.

In the HAVING clause, as a group selector.

  • Sub queries should always be enclosed in parentheses ().
  • Different database management systems have certain limitations on the number of sub query levels (e.g. up to 32 levels in SQL Server).
  • Sub queries are often computationally inefficient. Thus, I recommend avoiding nested queries when other options are available (e.g. JOINs).

Students

IdNameclassIDMarks
1Sagar32.4
2Shikha31.44
3Jasmeen13.24
4Deepika22.67
5Daljit24.56

Teachers

IdNameSubjectclassIDSalary
1BhanuComputer35000
2RekhaScience15000
3SiriSocialNULL4500
4KittuMaths25500

Classes

IdGradeteacherIDNo.ofstudents
18220
29340
310138

Example Of Nested Query

SELECT * FROM student

WHERE classID = (

   SELECT id

   FROM class

   WHERE noofstudents = (

      SELECT MAX(noofstudents)

      FROM class));

Output

4|Deepika  |2|2.67

5|Daljit   |2|4.56