What is a Subquery in SQL & How to write Subquery SQL with example

In this article, we will explain What is a subquery SQL and how to use subqueries in SQL Server (Transact-SQL) with syntax and example
Furthermore, in SQL Server, a subquery is a query within a query. you are free to create subqueries within your SQL statements. therefore, these subqueries can reside in the SELECT clause, WHERE clause, and the FROM Clause.

.
Note: In SQL Server (Transact-SQL), a subquery is also called an INNER SELECT or INNER QUERY.
In SQL Server (Transact-SQL), the main query that contains the subquery is also called the OUTER SELECT or OUTER QUERY.

A subquery SQL is a SQL query nested inside a larger query.

The subquery SQL may occur in :

A SELECT clause
A FROM clause
A WHERE clause

.
Note: The subquery in SQL can be nested inside a SELECT, INSERT, DELETE, or UPDATE statement or inside another subquery.
A subquery SQL is mainly added within the WHERE Clause of another SQL SELECT statement.
A subquery is also Know as an inner query or inner select, while the statement containing a subquery is also known as an outer query or outer select.
You can also use the comparison operators, like as =, >, or <. The comparison operator can also be a multiple-row operator, such as ALL, ANY, or IN.
The inner query executes first before its parent query so that the results of an inner query can be passed to the outer query.

Therefore, you’ll be able to use a subquery in a SELECT, INSERT, UPDATE, or DELETE statement to perform the subsequent tasks:
To compare an expression to the result of the query.
Determine if an expression is included within the results of the query.
Check whether or not the query selects any rows.

Syntax :

syntax of subquery in sql
Here, the subquery (inner query) executes once before the main query (outer query) executes.
The main query (outer query) uses the subquery result.

SELECT clause

A subquery can also be found within the SELECT clause. These are used when you would like to retrieve a calculation using an aggregate function such as the MIN, MAX, SUM, or COUNT function, furthermore, you do not want the aggregate function to apply to the main query.
Example

Therefore, in this example, we’ve created a subquery in the SELECT clause such as follows:

here, the subquery has been aliased with the name such as subquery2. furthermore, this will be the name used to reference this subquery or any of its fields.
therefore, the trick to placing a subquery in the select clause is that the subquery must return a single value. so, this is why an aggregate function such as the MIN, MAX, SUM, or COUNT function is commonly used in the subquery.

FROM clause

A subquery also can be found in the FROM clause that why it is also called inline views.
Example:

Therefore In the example, we’ve created a subquery in the FROM clause such as follows:

Therefore, as you see, this subquery has been aliased with the name subquery1. so, this will be the name used to reference this subquery or any of its fields.

WHERE clause

Therefore, Most often, the subquery will be found in the WHERE clause. so, these subqueries are also known as nested subqueries.

as in the above, the subquery portion of the SELECT statement is:

Therefore, as per the Subquery SQL Code, this subquery allows you to find all products_id values from the inventory table that have a quantity greater than 20.
so, the subquery is then used to filter the results from the main query using the IN condition.
furthermore, this subquery could have alternatively been written such as an INNER join as follows:

Therefore, These INNER joins would run more efficiently than the original subquery. so, it is important to note, though, that not all subqueries can be rewritten using joins

Subquery SQL Example

Let’s see the Subquery in SQL example, you will learn the requirements of using subqueries. therefore, We have the following two tables 'Employee' and 'Salary' with common field 'EmployeeID'.

Table: Employee

EmployeeID Name
E111 Mark Josheph
E112 Nitin Kumar Singh
E113 Pramod jain
E114 Nimisha Mishra
E115 Anand Kumar Singh
E116 satish Mishra
E117 Mahi Kashyap
E118 Ankit kumar Parihar
E119 Prakash Kumar Shukla
E120 Mukesh Jain
E121 Dinesh Sharma
E122 Ramu dwevedi
E123 Kapil Kumar Sharma
E124 Anoop Kumar Dubey
E125 Roshan Kumar Singh
Table: Salary

EmployeeID Total_Salary
E111 10000
E112 9000
E113 8000
E114 11000
E115 10000
E116 11000
E117 12000
E118 18000
E119 13000
E120 14000
E121 9000
E122 11000
E123 18000
E124 14000
E125 15000

As per given above both tables, now we want to write a query to identify all Employee who gets a better salary than that of the employee who’s EmployeeID is ‘E115’, but we do not know the Salary of ‘E115’.
Furthermore, to solve the problem, here, we require two queries. such as One query returns the salary (stored in Salary field) of ‘E115’ and a second query identifies the Employee who gets a better salary than the result of the first query.

SQL Query


subquery sql
The result of the above query is 10000.
Therefore, Using the result of this query, here we have need to written another query to identify the Employee who get better Salary than 10000. so,here is the query as given below :

Second Query


Betwwen SQL second query output
Therefore, as you see, the above two queries identified Employees who get a better salary than the Employee who’s EmployeeID is ‘E115’ (Anand Kumar Singh).

furthermore, we combine the above two queries by placing one query inside the other. so, the subquery (also called the ‘inner query’) is the query inside the parentheses. furthermore, let see the following code and query Output result :

SQL Query


between sub query output

Subquery SQL: General Rules

A subquery SELECT statement, which is almost similar to the SELECT statement, and it is used to begin an outer or regular query.
Therefore, given below is the syntax of a subquery:

General Syntax:

Type of SQL Subquery

First: Single row subquery: its returns zero or one row.
Second: Multiple row subquery: it, returns one or more rows.
Third: Multiple column subqueries: it, returns one or more columns.
Fourth: Correlated subqueries: The reference one or more columns in the outer SQL statement. so, the subquery is called a correlated subquery because the subquery is related to the outer SQL statement.
Fifth: Nested subqueries: The Subqueries are placed within another subquery.

Subquery SQL: Guidelines

There are some important guidelines to consider when using subqueries :

  • A subquery must be enclosed in parentheses and subquery must be placed on the right side of the comparison operator.
  • The subqueries cannot manipulate their results internally, therefore ORDER BY clause cannot be added into a subquery.
    so, You can use an ORDER BY clause in the main SELECT statement (outer Query) which will be the last clause. use the single-row operators with single-row subqueries.
  • If a subquery (inner-Query) returns a null value to the outer query, then the outer query does not return any rows once using comparison operators in a WHERE clause.

you can use a subquery inside INSERT, DELETE and UPDATE statement. let’s discuss in a breif:

Subqueries with INSERT statement

Therefore, INSERT statement can be used with subqueries. furthermore, there are the syntax and an example of subqueries using INSERT statement.

General Syntax:

If we want to insert those salary from 'Salary_Details' table which have the advance_salary 4000 or 9000
into 'advanced_amount' table the following SQL can be used:

Sample table: Salary_Details

EmployeeID Name Total_Salary Advance_Salary Salary_Date Dept_Code
E111 Mark Josheph 10000 4000 2016-01-02 M221
E112 Nitin Kumar Singh 9000 4000 2016-02-23 M223
E113 Pramod Jain 8000 3000 2016-02-22 M225
E114 Nimisha Mishra 11000 6000 2016-03-25 M226
E115 Anand Kumar singh 10000 3000 2016-03-28 M227
E116 Satish Mishra 11000 5000 2016-03-30 M228
E117 Mahi Kashyap 12000 4000 2016-04-01 M229
E118 Ankit Kumar parihar 18000 7000 2016-04-06 M230
E119 Prakash Kumar shukla 13000 3000 2016-04-08 M232
E120 Mukesh jain 14000 4000 2016-04-14 M235
E121 Dinesh Sharma 25000 9000 2016-04-18 M236
E122 Ramu Dwevedi 24000 10000 2016-04-21 M238
E123 Kapil Kumar Kaushik 22000 8000 2016-04-27 M241
E124 Anoop Kumar Dubey 22000 11000 2016-05-04 M242
E125 Roshan Kumar Singh 25000 7000 2016-05-11 M244

SQL Code:


Subqueries with INSERT statement

Subqueries with UPDATE statement

Therefore, In an UPDATE statement, you can set a new column value equal to the result returned by a single row subquery. furthermore, there are given below syntax and an example of subqueries using the UPDATE statement.

General Syntax:

If we want to update that Salary_Date in ‘Advanced_Amount’ table with ‘2016-06-11’ which have the difference of Total_Salary and Advance_Salary is less than
the minimum Total_Salary of ‘Salary_Details’ table the following SQL can be used:

Sample table: Advanced_Amount

EmployeeID Name Total_Salary Advanced_Salary Salary_Date Dept_Code
E111 Mark Josheph 10000 4000 2016-01-02 M221
E112 Nitin Kumar Singh 9000 4000 2016-02-23 M223
E117 Mahi Kashyap 12000 4000 2016-04-01 M229
E120 Mukesh jain 14000 4000 2016-04-14 M235
E121 Dinesh Sharma 25000 9000 2016-04-18 M236

SQL Code:


Subqueries with UPDATE statement

Subqueries with DELETE statement

The DELETE statement can be used with subqueries. therefore, there are the given below syntax and an example of subqueries using the DELETE statement.

General Syntax:

If we want to delete those salary from ‘Advanced_Amount’ table which Advanced_Salary are less than the maximum Advanced_Salary of ‘Salary_Details’ table, therefore, the following SQL can be used:

Sample table: Advanced_Amount

EmployeeID Name Total_Salary Advanced_Salary Salary_Date Dept_Code
E111 Mark Josheph 10000 4000 2016-01-02 M221
E112 Nitin Kumar Singh 9000 4000 2016-02-23 M223
E117 Mahi Kashyap 12000 4000 2016-04-01 M229
E120 Mukesh jain 14000 4000 2016-04-14 M235
E121 Dinesh Sharma 25000 9000 2016-04-18 M236

SQL Code:


Subqueries with DELETE statement

.
Subquery Notes: Nested Subquery: You can nest as many queries if you want furthermore, but it is recommended not to nest more than 16 subqueries in oracle
Subquery Errors: Minimize subquery errors: therefore, use drop and drag and, copy and paste to avoid running subqueries with spelling and database typos. furthermore, Watch your multiple field SELECT comma use, extra or to few getting SQL error message “Incorrect syntax”.
Non-Corelated Subquery: If a subquery is not dependent on the outer query then it is known a non-correlated subquery
SQL Subquery Comments: Adding SQL Subquery comments are good habit (/* your command comment */) which can save you time, furthermore, but clarify your previous work results in fewer SQL headaches