×

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 IN vs SQL EXISTS

SQL IN vs SQL EXISTS This article discusses in detail about the IN and the EXISTS operators in SQL. It is a common question between developers that what is the difference...

3 minutes read.

SQL Data Control Language

Data Control Language decides to whom should (which user) permit access privileges. GRANT and REVOKE are the commands of DCL. GRANT: It gives privileges to user. REVOKE: It takes back privileges from granted...

1 minute 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.

How to create a database in SQL?

How to create a database in SQL It is very necessary to create a database in order to store the data into the database.Database name must always be unique.SQL does not...

6 minutes read.

SQL VIEW

The SQL VIEW concept helps to hide the difficulty of the records and provides limitations to access to the database. The SQL view is similar to the SQL tables. In SQL...

7 minutes read.

SQL ORDER BY

SQL ORDER BY The SQL ORDER BY clause is used to sort the data stored in tables in the database. The sorting can be done in an ascending way, descending way,...

5 minutes read.

SQL SELECT WHERE Clause

In this SQL section, we will help you understand the concept of the SQL SELECT WHERE clause with a few examples. The WHERE clause in SELECT query displays those records as...

5 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 SELECT MAX

The SQL Max() function is an aggregate function in SQL. This function returns the values which are greater in the condition. The condition may be a number, or it may...

5 minutes read.

SQL CROSS Join

In this tutorial, we will help you understand the concept of the SQL CROSS Join clause with the few examples. The SQL CROSS Join query is used to join one or...

5 minutes read.

SQL Scalar Functions

TEACHER Table LCASE() Function The LCASE() function is used to return lower case values of specified column. Syntax: Select Lcase(column_name) from table_name; Example: Select Lcase(teacher_name) from teacher; Syntax: Select Lcase(column_name) from table_name [where condition]; Example: Select Lcase(teacher_name) from teacher where teacher_id=1; UCASE() Function The UCASE()...

1 minute read.

SQL Tutorial for Beginners

SQL tutorial provides basic and advanced concepts of Structured Query Language and how you deploy SQL to work with a relational database system. Our SQL tutorial is designed for beginners...

3 minutes read.

How to compare date in SQL

In this section, we will learn about how dates can be compared in SQL. We can compare any random date with another date stored in a column of a table.This comparison...

4 minutes read.

SQL INSERT Table

In this tutorial, we will help you to understand and learn how to add records to the table in SQL with the help of examples. SQL INSERT query is used to...

5 minutes read.

Grant Command in SQL

What is DCL (Data Control Language)? Data Control Language (DCL) is a computer programming language with syntax intended to manage access to data kept in databases. It is a part of...

3 minutes read.

How to remove duplicates in SQL

Introduction There are some specific rules that needs to be followed while creating the database objects. To improve the performance of a database, a primary key, clustered and non-clustered indexes, and...

9 minutes read.

SQL KEYS

SQL KEYS are single or multiple attributes used to get data from the table according to the requirement or condition. They can also be used to set up relationships amongst...

3 minutes read.

SQL Commands

SQL commands are classified into four groups on the basis of their nature. DDL (Data Definition Language) DML (Data Manipulation Language) DCL (Data Control Language) DQL (Data Query Language) NOTE: This...

1 minute read.

SQL Cast Operator

While writing SQL queries, we can see many values which are to be converted into another datatype for accessing them. In SQL this conversion is generally done by CAST function. CAST...

4 minutes read.

TCL Commands in SQL

In Structured Query Language, TCL is an abbreviation for Transaction Control Language. A single unit of work in a database is formed after the consecutive execution of commands is known...

6 minutes read.