Loading, please wait...

Sub Queries

How To Use Sub Queries In SQL

Introduction:
Today, in this article, you will learn what is Sub Queries and how to use Sub Queries in SQL.

In the SQL subpart of a query is called Subquery. The subquery is also called Inner query or Nested query. It gives individual values or a list of records.

 

Subqueries are fixed inside a Select, Insert, Update, Delete statement or another subquery. Subquery does not allow the Order By clause. We can use Group By clause as the Order By clause. We cannot use the Between operator with a subquery but we can use this within the subquery.

 

A Subquery, which gives the output in one or many rows only used with different value operators. A subquery allows the use of expression and we can use this an anyplace. Subqueries can be used with these operators =, <, >, >=, <= etc.

 

Here, we have an Employee table for applying the subqueries:

 

 

 

Select Statement in Sub Queries:

Subqueries are generally used with the Select statement.

 

Syntax:

The basic syntax of SELECT Statement in Subqueries is as follows:

seletc column_name, column_name from table1, table2 where column_name operater (select column_name1, column_name2 from table1, table2 [where condition]);

 

Example:

Step 1: first we write the query for Select Statement in Subquery.

 

 

 

Now, select and execute this query.

 

Step 2: And the output of this query is:

 

 

 

Insert Statement in Subqueries :

This Insert statement provides the data into other tables as a subquery. In the subquery we can b,e change our records with any functions.

 

Syntax:

The basic syntax of Insert Statement in Subqueries is as follows:

insert into table_name [column1 column2..] select * [column1 column2..] from table1, table2 [where value operator];

 

Example:

we write the query for Insert Statement in Subquery.

 

 

 

Update Statement in Subqueries :

We use these queries in conjunction with the Update statement. We update many columns with the help of Update Statement in Subqueries.

 

Syntax:

The basic syntax of Update Statement in Subqueries is as follows:

update table set column_name = new_value [where operator [value] (select column_name from table_name) [where];

 

Example:

Step 1: first we write the query for Update Statement in Subquery.

 

 

 

Now, select and execute this query.

 

Step 2: And the output of this query is:

 

 

 

Delete Statement in Subqueries :

we use these queries in conjunction with the Delete statement.

 

Syntax:

The basic syntax of Delete Statement in Subqueries is as follows:

delete from table_name [where operator [value] (select column_name from table_name) [where];

 

Example:

Step 1: first we write the query for Delete Statement in Subquery.

 

 

 

Now, select and execute this query.

 

Step 2: And the output of this query is:

 

 

 

Summary:
Thus, we learned that sub query gives unique values or a list of records and also learn it's use in SQL.