Table of Contents
ToggleAn SQL Subquery, is a SELECT query within another query. It is also known as Inner query or Nested query and the query containing it is the outer query.
The outer query can contain the SELECT, INSERT, UPDATE, and DELETE statements. We can use the subquery as a column expression, as a condition in SQL clauses, and with operators like =, >, <, >=, <=, IN, BETWEEN, etc.
Following are the rules to be followed while writing subqueries −
Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −
Example
In the following query, we are creating a table named CUSTOMERS −
Here, we are inserting records into the above-created table using INSERT INTO statement −
The table is displayed as −
| ID | NAME | AGE | ADDRESS | SALARY |
|---|---|---|---|---|
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | Kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | Hyderabad | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
Now, let us check the following subquery with a SELECT statement.
This would produce the following result −
| ID | NAME | AGE | ADDRESS | SALARY |
|---|---|---|---|---|
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
We can also use the subqueries along with the INSERT statements. The data returned by the subquery is inserted into another table.
The basic syntax is as follows −
Example
In the following example, we are creating another table CUSTOMERS_BKP with similar structure as CUSTOMERS table −
Now to copy the complete records of CUSTOMERS table into the CUSTOMERS_BKP table, we can use the following query −
The above query produces the following output −
Using the SELECT statement, we can verify whether the records from CUSTOMERS table have been inserted into CUSTOMERS_BKP table or not −
The table will be displayed as −
| ID | NAME | AGE | ADDRESS | SALARY |
|---|---|---|---|---|
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | Kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | Hyderabad | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
