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
.
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
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 :
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
1 2 3 4 5 |
SELECT w1.first_name, w1.last_name, (SELECT MIN(salary) FROM worker w2 WHERE w1.worker_id = w2.worker_id) subquery2 FROM worker w1; |
Therefore, in this example, we’ve created a subquery in the SELECT clause such as follows:
1 2 3 |
(SELECT MIN(salary) FROM worker w2 WHERE w1.worker_id = w2.worker_id) subquery2 |
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:
1 2 3 4 5 6 |
SELECT vendors.vendor_name, subquery1.total_amount FROM vendors, (SELECT vendor_id, SUM(order.amount) AS total_amount FROM order GROUP BY vendor_id) subquery1 WHERE subquery1.vendor_id = vendors.vendor_id; |
Therefore In the example, we’ve created a subquery in the FROM clause such as follows:
1 2 3 |
(SELECT vendor_id, SUM(order.amount) AS total_amount FROM order GROUP BY vendor_id) subquery1 |
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.
1 2 3 4 5 6 |
SELECT p.products_id, p.products_name FROM products p WHERE p.products_id IN (SELECT inv.products_id FROM inventory inv WHERE inv.quantity > 20); |
as in the above, the subquery portion of the SELECT statement is:
1 2 3 |
(SELECT inv.products_id FROM inventory inv WHERE inv.quantity > 20); |
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:
1 2 3 4 5 |
SELECT p.products_id, p.products_name FROM products p INNER JOIN inventory inv ON p.products_id = inv.products_id WHERE inv.quantity > 20; |
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'
.
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 |
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
1 2 3 |
SELECT * FROM Salary WHERE EmployeeID = 'E115'; |
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
1 2 3 4 |
SELECT a.EmployeeID, a.Name, b.Total_Salary FROM Employee a, Salary b WHERE a.EmployeeID = b.EmployeeID AND b.Total_Salary >10000; |
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
1 2 3 4 5 6 |
SELECT a.EmployeeID, a.Name, b.Total_Salary FROM Employee a, Salary b WHERE a.EmployeeID = b.EmployeeID AND b.Total_Salary > (SELECT Total_Salary FROM Salary WHERE EmployeeID = 'E115'); |
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:
1 2 3 4 5 6 |
(SELECT [DISTINCT] subquery_select_argument FROM {table_name | view_name} {table_name | view_name} ... [WHERE search_conditions] [GROUP BY aggregate_expression [, aggregate_expression] ...] [HAVING search_conditions]) |
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:
1 2 3 4 |
INSERT INTO table_name [ (column1 [, column2 ]) ] SELECT [ *|column1 [, column2 ] FROM table1 [, table2 ] [ WHERE VALUE OPERATOR ]; |
'Salary_Details'
table which have the advance_salary
4000 or 9000into
'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:
1 2 3 |
INSERT INTO Advanced_Amount SELECT * FROM Salary_Details WHERE Advance_Salary in(4000,9000); |
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:
1 2 3 4 5 |
UPDATE table SET column_name = new_value [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ] |
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:
1 2 3 4 |
UPDATE Advanced_Amount SET Salary_Date='2016-06-11' WHERE Total_Salary-Advance_Salary< (SELECT MIN(Total_Salary) FROM Salary_Details); |
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:
1 2 3 4 5 |
DELETE FROM TABLE_NAME [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ] |
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:
1 2 3 |
DELETE FROM Advanced_Amount WHERE Advance_Salary< (SELECT MAX(Advance_Salary) FROM Salary_Details); |
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