×

SQL SubQuery

The Sub-query in the SQL is the inner query placed or positioned inside another query, which is also known is the outer query. The inner query is embedded in the Where clause of the SQL Query.

There are certain rules for executing the Subqueries in the SQL are as follows:

  1. We can use SQL Sub-query along with SELECT Statement, UPDATE Statement, INSERT Statement and DELETE Statement in the SQL statement.
  2. When we use Subqueries in the SQL statement, the nested inner query will get executed first, then the outer query, which is the main query executed at the end.
  3. A comparison operator can also be used.
  4. The inner query is closed within the parenthesis, and the inner query is placed on the right side of the comparison operator.
  5. You cannot use the ORDER BY clause in the Sub-query but can use the GROUP BY clause.
  6. The Sub-query with FROM clause can be used, WHERE clause, and HAVING clause.

Let's understand the SQL Sub-Query with the help of examples.

Consider the already existing table, which has the following data:

Table Number 1: - D_Students

Student_IdStudent_NameFirst_SemSecond_SemThird_SemFourth_SemFifth_SemSixth_SemTotalDepartment_Id
202111Vaishnavi Patil949188859592911
202112Vaibhav Lokhande859092808582862
202113Yash Dhull908894878590893
202114Sonali Patole959092889290914
202115Axar Patel858082869284851
202116Meena Mishra787580748577783
202117Mahesh Kumbhar758075788076775
202118Sakshi Patil807874788077782
202119Sopan Bhore706875758080752
202220Prajwal Lokhande808585757880814
202221Anuja Wanare858886828485855
202222Venkatesh Iyer908987909291903
202223Anushka Sen707571748078751
202224Aakash Jain807572748580784
202225Akshay Agarwal858078889082845
202226Shwetali Bhagwat908085889080861
202227Mayuri Wagh808085808285824
202228Utkarsh Rokade858080908484845
202229Manthan Koli857584788280812
202230Mayur Jain808887909290881

Table Number 2: Department

Department_IdDepartment_Name
1Computer Engineering
2Information Technology
3Mechanical Engineering
4Automobile Engineering
5Civil Engineering
6Electrical Engineering
7Electronics and Telecommunication Engineering
8Chemical Engineering

1. Subquery with the SELECT Statement

The SELECT Statement is used with the subqueries to display the data from the tables.

The syntax of the Subquery with the SELECT statement is as follows:

SELECT * FROM Table_Name WHERE Column_Name Expression Operator (SELECT * FROM Table_Name);

Example 1: Execute a query to display the student's information where student department names are 'Computer Engineering', 'Information Technology', and 'Automobile Engineering'. 

SELECT * FROM D_Students WHERE Department_Id IN (SELECT Department_Id FROM Department WHERE Department_Name IN ('Computer Engineering', 'Information Technology','Automobile Engineering'));

In the above query example, we display the student's information where student department names are 'Computer Engineering', 'Information Technology', and 'Automobile Engineering'.

First, SELECT Department_Id FROM Department WHERE Department_Name IN ('Computer Engineering', 'Information Technology', 'Automobile Engineering'); gets executed, and the output of this inner query is

Department_Id
1
2
4

As the inner query output is calculated, the output is represented as input for the main query. The main query is executed as SELECT * FROM D_Students WHERE Department_Id IN (1, 2, 4);

The output of the above query is as follows:

SQL SubQuery
Student_IdStudent_NameFirst_SemSecond_SemThird_SemFourth_SemFifth_SemSixth_SemTotalDepartment_Id
202111Vaishnavi Patil949188859592911
202115Axar Patel858082869284851
202223Anushka Sen707571748078751
202226Shwetali Bhagwat908085889080861
202230Mayur Jain808887909290881
202112Vaibhav Lokhande859092808582862
202118Sakshi Patil807874788077782
202119Sopan Bhore706875758080752
202229Manthan Koli857584788280812
202114Sonali Patole959092889290914
202220Prajwal Lokhande808585757880814
202224Aakash Jain807572748580784
202227Mayuri Wagh808085808285824
SQL SubQuery

Example 2: Execute a query to display the student’s information where the student’s department name is ‘Computer Engineering’

SELECT * FROM D_Students WHERE Department_Id = (SELECT Department_Id FROM Department WHERE Department_Name = 'Computer Engineering');

We display the student's information where the department name is 'Computer Engineering' in the above query. The query execution is the same as explained in the above example.

The output of the above query is as follows:

Student_IdStudent_NameFirst_SemSecond_SemThird_SemFourth_SemFifth_SemSixth_SemTotalDepartment_Id
202111Vaishnavi Patil949188859592911
202115Axar Patel858082869284851
202223Anushka Sen707571748078751
202226Shwetali Bhagwat908085889080861
202230Mayur Jain808887909290881
SQL SubQuery

2. Subquery with the UPDATE Statement

The UPDATE statement is used with the subqueries to modify the data.

The Syntax of the Subquery with the UPDATE statement is as follows:

UPDATE Table_Name SET Column_Name = Values WHERE Column_Name Conditions operator (SELECT * FROM Table_Name WHERE Column_Name Conditions);

Example 1: Execute a query to modify the student's information where the student's first-semester percentage is greater than 85, and the department name is 'Computer Engineering'.

UPDATE D_Students SET DEpartment_Id = '6' WHERE First_Sem > 85 AND Department_Id = (SELECT Department_Id FROM Department WHERE Department_Name = 'Computer Engineering');

In the above query, we are modifying the student information of those students where the first-semester percentage is greater than 85, and the department name is 'Computer Engineering’.

First, SELECT Department_Id FROM Department WHERE Department_Name = 'Computer Engineering'; gets executed, and the output of this inner query is

Department_Id
1

As the inner query output is calculated, the output is represented as input for the main query. The main query is executed as UPDATE D_Students SET Department_Id = 6 WHERE First_Sem > 85 AND Department_Id = 1;

We will execute the SELECT statement to check whether the data is modified or not.

SELECT * FROM D_Students;

The output of the above query is as follows:

Student_IdStudent_NameFirst_SemSecond_SemThird_SemFourth_SemFifth_SemSixth_SemTotalDepartment_Id
202111Vaishnavi Patil949188859592916
202112Vaibhav Lokhande859092808582862
202113Yash Dhull908894878590893
202114Sonali Patole959092889290914
202115Axar Patel858082869284851
202116Meena Mishra787580748577783
202117Mahesh Kumbhar758075788076775
202118Sakshi Patil807874788077782
202119Sopan Bhore706875758080752
202220Prajwal Lokhande808585757880814
202221Anuja Wanare858886828485855
202222Venkatesh Iyer908987909291903
202223Anushka Sen707571748078751
202224Aakash Jain807572748580784
202225Akshay Agarwal858078889082845
202226Shwetali Bhagwat908085889080866
202227Mayuri Wagh808085808285824
202228Utkarsh Rokade858080908484845
202229Manthan Koli857584788280812
202230Mayur Jain808887909290881
SQL SubQuery

Example 2: Execute a query to modify the student's information where the student name starts with the letter 'A' and department names are 'Automobile Engineering' and 'Civil Engineering'.

UPDATE D_Students SET Department_Id = '7' WHERE Student_Name LIKE 'A%' AND Department_Id IN (SELECT Department_Id FROM Department WHERE Department_Name IN ('Automobile Engineering','Civil Engineering'));

In the above query, we modify those students' information where student_name starts with the letter 'A' and department names are 'Automobile Engineering' and 'Civil Engineering'. The query execution is the same as explained in the above example.

We will execute the SELECT statement to check whether the data is modified or not.

SELECT * FROM D_Students;

The output of the above query is as follows:

Student_IdStudent_NameFirst_SemSecond_SemThird_SemFourth_SemFifth_SemSixth_SemTotalDepartment_Id
202111Vaishnavi Patil949188859592916
202112Vaibhav Lokhande859092808582862
202113Yash Dhull908894878590893
202114Sonali Patole959092889290914
202115Axar Patel858082869284851
202116Meena Mishra787580748577783
202117Mahesh Kumbhar758075788076775
202118Sakshi Patil807874788077782
202119Sopan Bhore706875758080752
202220Prajwal Lokhande808585757880814
202221Anuja Wanare858886828485857
202222Venkatesh Iyer908987909291903
202223Anushka Sen707571748078751
202224Aakash Jain807572748580787
202225Akshay Agarwal858078889082847
202226Shwetali Bhagwat908085889080866
202227Mayuri Wagh808085808285824
202228Utkarsh Rokade858080908484845
202229Manthan Koli857584788280812
202230Mayur Jain808887909290881
SQL SubQuery

3. Subquery with the DELETE Statement

The DELETE statement is used with the subqueries to remove data from the table.

The Syntax of the Subquery with the DELETE statement is as follows:

DELETE FROM Table_Name WHERE Column_Name Conditions operator (SELECT * FROM Table_Name WHERE Column_Name Conditions);

Example: Execute a query to remove the student's information where department names are 'Civil Engineering’, ‘Electrical Engineering’, and ‘Electronics and Telecommunication Engineering’.

DELETE FROM D_Students WHERE Department_Id IN (SELECT Department_Id FROM Department WHERE Department_Name IN ('Civil Engineering', 'Electrical Engineering', 'Electronics and Telecommunication Engineering'));

In the above query, we removed the student's information from the D_Students table where department names are 'Civil Engineering’, ‘Electrical Engineering’, and ‘Electronics and Telecommunication Engineering’.

First, SELECT Department_Id FROM Department WHERE Department_Name IN ('Civil Engineering', 'Electrical Engineering', 'Electronics and Telecommunication Engineering'; gets executed, and the output of this inner query is

Department_Id
5
6
7

As the inner query output is calculated, the output is represented as input for the main query. The main query is executed as DELETE FROM D_Students WHERE Department_Id IN (5, 6, 7);

The main query removes the student’s information where department id is 5, 6, and 7 from the D_Students table.

We will execute the SELECT statement to check whether the data is removed or not.

SELECT * FROM D_Students;

The output of the above query is as follows:

Student_IdStudent_NameFirst_SemSecond_SemThird_SemFourth_SemFifth_SemSixth_SemTotalDepartment_Id
202112Vaibhav Lokhande859092808582862
202113Yash Dhull908894878590893
202114Sonali Patole959092889290914
202115Axar Patel858082869284851
202116Meena Mishra787580748577783
202118Sakshi Patil807874788077782
202119Sopan Bhore706875758080752
202220Prajwal Lokhande808585757880814
202222Venkatesh Iyer908987909291903
202223Anushka Sen707571748078751
202227Mayuri Wagh808085808285824
202229Manthan Koli857584788280812
202230Mayur Jain808887909290881
SQL SubQuery

Related Topics

SQL CREATE TABLE

In SQL tutorial, we learned and created different databases. To stores data in databases, we need to create a table. To create the table, we need to use CREATE TABLE...

5 minutes read.

SQL Between Operator

SQL Between operator is a logical operator in the Structured Query Language. The Between operator is used to retrieve data within the range specified in the condition in the query. The...

7 minutes read.

WEB SQL

What is Web SQL? In SQL we can create databases, read the data in the databases, insert the records into the databases, and delete the records from the databases. For storing...

4 minutes read.

SQL Handling Duplicate

Removing Duplicates using DISTINCT Keyword: By using the DISTINCT keyword in SQL we can remove duplicate characters from tables or databases. A table contains more duplicate values and duplicate values can cause...

4 minutes read.

SQL Data Manipulation Language

Data Manipulation Language manipulates/make changes in data present in a table. It only affects data/records of table, not on the schema/structure of table. INSERT, UPDATE, DELETE are the commands of DML. INSERT: Stores...

2 minutes read.

SQL Syntax

In this tutorial, we will help you understand about the different SQL Syntax concepts with the help of an example. Every Structured Query Language starts with Keywords like select, insert, update,...

5 minutes read.

SQL INSERT INTO Values

This article will help you in getting a better understanding of a very important SQL INSERT INTO VALUES function. INSERT INTO statement is used to insert or add a new record...

4 minutes read.

SET Operators in SQL

The operator used to join or combine two queries is none other than SET operators. Operators categorized into SET operators are as follows: UNION Operator.UNION ALL’ Operator.INTERSECT Operator.MINUS Operator. Rules to be...

8 minutes read.

SQL SELECT LIKE Operator

The SQL SELECT LIKE Operator tutorial helps us understand how to use the LIKE operator in the SELECT query with examples. The SQL SELECT LIKE Operator retrieves the records from the...

4 minutes read.

SQL Auto Increment

As we all know, In SQL for unique identification, we assign a column with the primary key. But in some tables, we find difficult to differentiate a column as a...

5 minutes read.

Trigger in SQL

In this article, we will learn about the concept of trigger in SQL and its implementation with the help of an example. A Trigger in Structured Query Language is a set...

4 minutes read.

SQL Wildcards

SQL WILDCARD CHARACTERS: SQL wild card character is used to substitute zero or more characters of a string. These characters are used with the “LIKE” operator. Wild Card Characters in SQL: %_[]^- “%” : It is...

3 minutes read.

How to Add Foreign Key in SQL?

How to Add Foreign Key in SQL Foreign key is an attribute or a set of attributes that references to primary key of same table or another table (relation). Foreign key creation along...

4 minutes read.

SQL HAVING Clause

In this tutorial, we will understand the HAVING clause concept in SQL with the help of examples. The HAVING Clause in the SQL is used as we cannot use the WHERE...

3 minutes read.

DML Commands in SQL

DML is an abbreviation of Data Manipulation Language. Data Manipulation Language commands in Structured Query Language manipulate the data in the database. DML commands are used to retrieve records, add records,...

4 minutes read.

Difference between SQL and NoSQL

SQL vs. NoSQL | Difference between SQL and NoSQL Choosing a database is the most fundamental decision that needs to be decided before starting a task. Relational and non-relational databases are...

3 minutes read.

SQL GROUP BY CLAUSE

The GROUP BY clause is used to arrange similar records into the groups in the Structured Query Language queries. The records are arranged with the help of functions which is...

4 minutes read.

Types of SQL JOIN

The SQL JOIN combines one or more than one tables based on their relationship. The SQL JOIN involves a parent table and a child table relationship. There are different types of...

10 minutes read.

SQL Insert multiple rows

This article will deal with a new insertion method in SQL which inserts multiple rows at a time. Multiple records can be inserted at a time into a specific table with...

4 minutes read.

SQL Data Types

In SQL DATA TYPES, each column holds value. Data types can be an integer type, character type, etc., and such data is stored in the database table. The data type is...

4 minutes read.