Types of Subqueries in SQL

Learn via video course
FREE
View all courses
DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
by Srikanth Varma
1000
5
Start Learning
DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
by Srikanth Varma
1000
5
Start Learning
Topics Covered

Overview

Subqueries are queries that are nested inside another SQL query. They help us target specific rows to perform various operations in SQL. They are used to SELECT, UPDATE, INSERT and DELETE records in SQL. There are different types of SQL subquery, like Single-row subquery, multiple row subquery, multiple column subquery, correlated subquery, and nested subquery. Each type performs different roles, and their result is used depending on the user's requirement.

Introduction

Subqueries are queries that are nested within another SQL query. A subquery can contain more than one query inside it, one after another. They allow us to select specific rows that satisfy certain conditions at the run time. They are also known as the inner query or inner select, and the query that contains them is known as the outer query or outer select.

  • Subqueries are nested inside statements like SELECT, INSERT, UPDATE, DELETE, or any other subquery.
  • Subqueries are present in the WHERE clause, FROM clause, or HAVING clause of the PARENT SQL query.
  • They are used with comparison operators and logical operators like >, <, >=, <>, <=, SOME, ANY, ALL, and IN.
  • They execute before the outer query at the run time and pass the result to complete the statement.
  • Subqueries are used to compare an expression to the output and check if any row gets selected.

A maximum of 255 subquery levels can be nested in a WHERE clause. The FROM clause has no limit in nesting subqueries. In the real world, we encounter not more than five subqueries. So, 255 is too large to be set as a limit.

Syntax

In this article, we will take you through different types of subqueries and some of their useful examples.

Types of Subqueries in SQL

Imagine that we are famous artists who sell their artworks in art galleries all over the world. Let's see what the tables in our database look like:

Galleries

idcity
1Jaipur
2Kolkata
3Madhubani

paintings

idnamegallery_idprice
1Patterns35000
2Ringer14500
3Gift13200
4Violin Lessons26700
5Curiosity29800

sales_agents

idlast_namefirst_namegallery_idagency_fee
1BrownDenis22250
2WhiteKate33120
3BlackSarah21640
4SmithHelen14500
5StewartTom32130

managers

idgallery_id
12
23
41

Single Row Subquery

Subqueries that return a single row as an output to their parent query are called single-row subqueries. Single-row subqueries are used in a SQL SELECT statement with HAVING clause, WHERE clause, or a FROM clause and a comparison operator. Single-row subqueries are used in the SELECT statement. Let's see it with an example.

The above SQL query displays the average price of all paintings besides their original price. The result looks like this:

paintingpriceavg_price
Patterns50005840
Ringer45005840
Gift32005840
Violin Lessons67005840
Curiosity98005840

The subquery returns the average price of 5840, which is a single value. It gets added to each row of the table.

Note: The inner query is independent of the outer query and gives a meaningful result by running on its own.

Single-row subqueries can also be used with the WHERE clause in the SELECT statement to filter the results of the outer query. Let's see an example of it.

The above SQL query shows the records of the sales agents whose agency fee is greater than the average of all the fees. The subquery present in the statement calculates the average agency fee, which is 2728. The parent statement then uses the returned value to filter out the information of those sales agents with higher-than-average agency fees. The result looks like the following table:

idlast_namefirst_namegallery_idagency_fee
2WhiteKate33120
4SmithHelen14500

Multiple Row Subquery

Subqueries that return multiple rows as an output to their parent query are called multiple-row subqueries. Multiple row subqueries can be used in a SQL SELECT statement with a HAVING clause, WHERE clause, a FROM clause, and a logical operator(ALL, IN, NOT IN, and ANY). Let's explore it using an example.

The above SQL Query calculates the average agency fee of all the sales agents who are not managers. The subquery returns the list of IDs of all managers. Then the outer query filters the table to find the records of the sales agents who are not managers and calculates the average agency fee of those agents. It returns a single average value of the agency fee. The output looks like the following:

agency_fee
1885

Multiple Column Subqueries

Subqueries that return multiple columns as an output to their parent query are called multiple-column subqueries. Let's see it through an example.

The above SQL Query retrieves the painting with the lowest price. The inner subquery returns the record of the painting with the lowest price. The outer query compares all the records using the IN operator and returns the one with the minimum price.

It gives the following output:

idnamegallery_idprice
3Gift13200

Correlated Subqueries

Subqueries that return multiple columns as output depending on the information obtained from the parent query are called correlated subqueries. The interdependence of the inner and outer query makes it complicated to understand.

Correlated subqueries can be used in SELECT statements using WHERE and FROM clauses. Let's understand it better using an example.

The above SQL query calculates the number of paintings found in each gallery. The subquery returns a single value for the total number of paintings in the corresponding query. The outer query returns the details of each painting with the city of the art gallery it is present.

The output of the following is:

citytotal_paintings
Jaipur2
Kolkata2
Madhubani1

You can get the same result using JOIN in SQL. Let's see how!

Note: Generally, JOINS performs faster than subqueries, but you can use them if you find it more intuitive.

Correlated subqueries are also used in SQL statements with WHERE clauses.

Let's check out an example of it.

The above SQL Query shows us the information of those sales agents whose agency fee is greater than or equal to the agency fee of their gallery. The subquery returns the average of the agency fee of the respective sales agent. The outer query returns the information of those sales agents whose agency fee is greater than or equal to the average of the galleries.

The result of the above query is as follows:

last_namefirst_nameagency_fee
BrownDenis2250
WhiteKate3120
SmithHelen4500

Nested Subqueries

Subqueries that are inside another subquery are called nested subqueries. Subqueries are executed level by level. The innermost is executed first, and then the outer ones. Let's see some examples.

The above SQL query is to display the average price of paintings whose price is greater than 5000 than their original price. The result looks like this:

The output of the following query looks like this:

paintingpriceavg_price
Patterns50007166.66
Violin Lessons67007166.66
Curiosity98007166.66

The above example has three subqueries that are nested subquery, inner subquery, and outer subquery. The code in this example gets departed part by part. Let's break them down one by one to understand the results clearly.

At first, the nested query runs as follows:

This nested query retrieves the price of the paintings whose value is greater than or equal to 5000.

The output of the following query is:

price
5000
6700
9800

The inner subquery looked like this:

After receiving the output from the nested subquery, it internally transforms to:

The subquery returns the average price of paintings of those returned by the nested subquery (i.e., 5000, 6700, 9800). The result of the subquery is a single average value of 7166.66.

Output:

AVG(price)
7166.66

The outer query is transformed by receiving the result from the subquery and the nested query.

The query internally works as follows:

The outer query returns the name of paintings whose price is greater than or equal to 5000, with their original and average price beside them.

The following is the final output:

paintingpriceavg_price
Patterns50007166.66
Violin Lessons67007166.66
Curiosity98007166.66

Other Examples

Let's consider the following table for the below examples:

ORD_NUMORD_AMOUNTADVANCE_AMTORD_DATECUST_CODEAGENT_CODEORD_DESCRIPTION
2001143500200015-AUG-08C00002A008
200122250040016-SEP-08C00003A004
20011850010020-JUL-08C00023A006
200119400070016-SEP-08C00007A010
200121150060023-SEP-08C00008A004
200130250040030-JUL-08C00025A011
2001344200180025-SEP-08C00004A005
200108400060015-FEB-08C00008A004
200103150070015-MAY-08C00021A005
200105250050018-JUL-08C00025A011
200109350080030-JUL-08C00011A010
2001013000100015-JUL-08C00001A008
200111100030010-JUL-08C00020A008
200104150050013-MAR-08C00006A004
200106250070020-APR-08C00005A002
200125200060010-OCT-08C00018A005

Subqueries with INSERT statement

Subqueries are used to insert statements to insert selective rows from one table to another.

Syntax

Let us see an example of inserting records in SQL using subqueries.

The above SQL Query will insert those orders into the neworder table whose ADVANCE_AMOUNT is 2000 or 1800 in the orders table.

Subqueries with the UPDATE statement

Subqueries are used in an UPDATE statement to set new values to a column that the returned by the subquery as output.

Syntax

Let's update a record using subqueries in SQL.

The following SQL query updates the ord_date in the neworder table to 15-JAN-10 of the records whose difference between the order amount and advance amount is less than the minimum order amount in the orders table.

Subqueries with DELETE statement

Subqueries are used in a DELETE statement to delete specific rows that is returned as a result of the subquery.

Syntax

Let's delete some rows using subqueries in SQL.

The above code deletes those orders from the neworder table whose advance amount is less than the maximum amount in the orders table.

Conclusion

  • In this article, we have learned that there are many types of subqueries.
  • The subqueries we use to SELECT, DELETE, UPDATE, and INSERT our records depend on our needs. We can use single-row subqueries for returning single rows, multiple-row subqueries for returning multiple rows, correlated subqueries for returning multiple columns depending on the parent query, and nested subqueries to return a subquery to another one. We have seen examples of all of them one by one.
  • Now, it's time for you to practice more and more, to become a great SQL learner!!

Additional Resources

  1. Online SQL Syntax Checker
  2. Interview Question for SQL Query