+91-90427 10472
         
Dot net training in Chennai -Maria Academy

Subquery in SQL

29 Jul 2022

Query: A query is a request for data or information from one or more tables of a database.

Sub Query: In SQL language, we can place a Query inside another Query. This Query which is placed inside another query is called as subquery, also known as Nested Query

Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements along with the equality operator or comparison operator such as =, >, =, <= and Like operator.

Subquery must be enclosed in parentheses.

An ORDER BY command cannot be used in a subquery, but the main query can use an ORDER BY. The GROUP BY command can be used instead of ORDER BY in a subquery.

 

Subquery – SELECT Statement

Consider a Query

Select * from StudentDetails

When this query when executed, selects all rows of the table

Now consider an example with subquery Select

Select * from StudentDetails

where ID in (Select ID from StudentDetails where Percentage > 90);

When this set of queries gets executed,

Always the subquery gets executed first, selects the ID from StudentDetails table whose percentage is greater than 90, And then the outer query gets executed later, selecting the ID equal to the result of subquey

 

Subquery – INSERT Statement

Now consider an example with subquery Insert

Insert into StudentDetails_new

Select * from StudentDetails where ID in (Select ID from StudentDetails );

Here a new table with StudentDetails_new is created with the same structure as StudentDetails table, now to copy the datas of StudentDetails table to StudentDetails_new table , insert  statement can be used.

 

Subquery – UPDATE Statement

Now consider an example with subquery update

update StudentDetails

Set mark = mark + 5

Where mark in (Select mark from StudentDetails where mark >= 91);

Here in the table StudentDetails, the mark can be updated with a bonus of 5 marks for those who have scored mark of 91 and above using this update statement.

 

Subquery – DELETE Statement

Now consider an example with subquery delete

Delete from StudentDetails

Where mark in (Select mark from StudentDetails where mark < 50);

Here in the table StudentDetails, the datas with marks less than 50 can be removed using delete statement.

 

Social tagging: > >