0% found this document useful (0 votes)
29 views12 pages

SQL Subqueries

Uploaded by

padma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views12 pages

SQL Subqueries

Uploaded by

padma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

SQL Subqueries

An 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.

Rules to be followed
Following are the rules to be followed while writing subqueries –

 Subqueries must be enclosed within parentheses.


 Subqueries can be nested within another subquery.
 A subquery must contain the SELECT query and the FROM clause always.
 A subquery consists of all the clauses an ordinary SELECT clause can contain:
GROUP BY, WHERE, HAVING, DISTINCT, TOP/LIMIT, etc. However, an ORDER
BY clause is only used when a TOP clause is specified. It can't include
COMPUTE or FOR BROWSE clause.
 A subquery can return a single value, a single row, a single column, or a
whole table. They are called scalar subqueries.

Subqueries with the SELECT Statement


Subqueries are most frequently used with the SELECT statement. The basic
syntax is as follows −

SELECT column_name [, column_name ]


FROM table1 [, table2 ]
WHERE column_name
OPERATOR (SELECT column_name [,column_name ] FROM table1 [, table2 ]
[WHERE]);

Example
In the following query, we are creating a table named CUSTOMERS −

Open Compiler
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

Here, we are inserting records into the above-created table using INSERT
INTO statement −

Open Compiler
INSERT INTO CUSTOMERS VALUES
(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);

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.

Open Compiler
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 4500);

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

Subqueries with the INSERT Statement


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 −

INSERT INTO table_name [ (column1 [, column2 ]) ]


SELECT [ *|column1 [, column2 ] FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]

Example
In the following example, we are creating another table CUSTOMERS_BKP
with similar structure as CUSTOMERS table −

Open Compiler
CREATE TABLE CUSTOMERS_BKP (
ID INT NOT NULL,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

Now to copy the complete records of CUSTOMERS table into the


CUSTOMERS_BKP table, we can use the following query −

Open Compiler
INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS);

The above query produces the following output −


Query OK, 7 rows affected (0.01 sec)
Records: 7 Duplicates: 0 Warnings: 0

Verification
Using the SELECT statement, we can verify whether the records from
CUSTOMERS table have been inserted into CUSTOMERS_BKP table or not −

Open Compiler
SELECT * FROM CUSTOMERS_BKP;

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

Subqueries with the UPDATE Statement


A subquery can also be used with the UPDATE statement. You can update
single or multiple columns in a table using a subquery.

The basic syntax is as follows −

UPDATE table
SET column_name = new_value
[WHERE OPERATOR [VALUE](SELECT COLUMN_NAME FROM TABLE_NAME
[WHERE]);

Example
We have the CUSTOMERS_BKP table available which is backup of
CUSTOMERS table. The following example updates SALARY by 0.25 times in
the CUSTOMERS table for all the customers whose AGE is greater than or
equal to 27.

Open Compiler
UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 );

Following is the output of the above query −

Query OK, 2 rows affected (0.01 sec)


Rows matched: 2 Changed: 2 Warnings: 0

Verification
This would impact two rows and if you verify the contents of the CUSTOMERS
using the SELECT statement as shown below.

Open Compiler
SELECT * FROM CUSTOMERS;

The table will be displayed as −

ID NAME AGE ADDRESS SALARY

1 Ramesh 32 Ahmedabad 500.00

2 Khilan 25 Delhi 1500.00

3 kaushik 23 Kota 2000.00

4 Chaitali 25 Mumbai 6500.00

5 Hardik 27 Bhopal 2125.00

6 Komal 22 Hyderabad 4500.00

7 Muffy 24 Indore 10000.00

Subqueries with the DELETE Statement


The subquery can be used with the DELETE statement as well; like with any
other statements mentioned above.

The basic syntax is as follows −

DELETE FROM TABLE_NAME


[WHERE OPERATOR [ VALUE ](SELECT COLUMN_NAME FROM TABLE_NAME)
[WHERE)];

Example
We have a CUSTOMERS_BKP table available which is a backup of the
CUSTOMERS table. The following example deletes the records from the
CUSTOMERS table for all the customers whose AGE is greater than or equal to
27.

Open Compiler
DELETE FROM CUSTOMERS
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 );

The above query generate the following output −

OK, 2 rows affected (0.01 sec)

Verification
If you verify the contents of the CUSTOMERS table using the SELECT
statement as shown below.

Open Compiler
SELECT * FROM CUSTOMERS;

The table will be displayed as −

ID NAME AGE ADDRESS SALARY

2 Khilan 25 Delhi 1500.00

3 kaushik 23 Kota 2000.00

4 Chaitali 25 Mumbai 6500.00

6 Komal 22 Hyderabad 4500.00

7 Muffy 24 Indore 10000.00

A subquery in SQL is a query nested inside another SQL query. It allows


complex filtering, aggregation and data manipulation by using the result of
one query inside another. They are an essential tool when we need to
perform operations like:
 Filtering: selecting rows based on conditions from another query.
 Aggregating: applying functions like SUM, COUNT, AVG with dynamic
conditions.
 Updating: modifying data using values from other tables.
 Deleting: removing rows based on criteria from another query.
While there is no universal syntax for subqueries, they are commonly used
in SELECT statements as follows.
Syntax:
SELECT column_name
FROM table_name
WHERE column_name expression operator
(SELECT column_name FROM table_name WHERE ...);
Common SQL Clauses for Subqueries
Clauses that can be used with subqueries are:
 WHERE: filter rows based on subquery results.
 FROM: treat subquery as a temporary (derived) table.
 HAVING: filter aggregated results after grouping.
Types of Subqueries
1. Single-Row Subquery
 Returns exactly one row as the result.
 Commonly used with comparison operators such as =, >, <
Example:
SELECT * FROM Employees
WHERE Salary = (SELECT MAX(Salary) FROM Employees);
Output: Returns the employee(s) with the highest salary.
2. Multi-Row Subquery
 Returns multiple rows as the result.
 Requires operators that can handle multiple values, such as IN, ANY or
ALL
Example:
SELECT * FROM Employees
WHERE DepartmentID IN (SELECT DepartmentID FROM Departments
WHERE Location = 'New York');
Output: Fetches employees working in all New York departments.
3. Correlated Subquery
 A dependent subquery: it references columns from the outer query.
 Executed once for each row of the outer query, making it slower for
large datasets.
Example:
SELECT e.Name, e.Salary
FROM Employees e
WHERE e.Salary > (SELECT AVG(Salary)
FROM Employees
WHERE DepartmentID = e.DepartmentID);
Output: Returns employees earning more than the average salary of their
own department.
Examples of Using SQL Subqueries
These examples showcase how subqueries can be used for various
operations like selecting, updating, deleting or inserting data, providing
insights into their syntax and functionality. Through these examples, we will
understand flexibility and importance of subqueries in simplifying complex
database tasks.
Consider the following two tables:
Student Table
NAME ROLL_NO LOCATION PHONE_NUMBER

Ram 101 Chennai 9988775566

Raj 102 Coimbatore 8877665544

Sasi 103 Madurai 7766553344

Ravi 104 Salem 8989898989

Sumathi 105 Kanchipuram 8989856868


New_Student Table
NAME ROLL_NO SECTION

Ravi 104 A

Sumath
105 B
i

Raj 102 A

Example 1: Fetching Data Using Subquery in WHERE Clause


This example demonstrates how to use a subquery inside the WHERE
clause. The inner query retrieves roll numbers of students who belong to
section 'A' and the outer query fetches their corresponding details (name,
location and phone number) from the Student table.
Query:
SELECT NAME, LOCATION, PHONE_NUMBER
FROM Student
WHERE ROLL_NO IN (
SELECT ROLL_NO FROM New_Student WHERE SECTION = 'A'
);
Output
LOCATIO
NAME N PHONE_NUMBER

Ravi Salem 8989898989

Raj Coimbatore 8877665544

Explanation:
 The subquery SELECT ROLL_NO FROM New_Student WHERE
SECTION = 'A' finds roll numbers of students in section A.
 The outer query then uses these roll numbers to fetch details from the
Student table.
 Thus, only Ravi and Raj are returned, since they are in section A.
Example 2: Using Subquery with INSERT
Here we demonstrate how a subquery can be used with INSERT. Instead
of manually entering data, we copy data from another table
(Temp_Students) into the main Student table.
Temp_Students
ROLL_N
NAME O LOCATION PHONE_NUMBER

Ajay 201 Mumbai 9090901234

Meena 202 Delhi 8080805678


Query:
INSERT INTO Student
SELECT * FROM Temp_Students;
Output
NAME ROLL_NO LOCATION PHONE_NUMBER

Ram 101 Chennai 9988775566

Raj 102 Coimbatore 8877665544

Sasi 103 Madurai 7766553344

Ravi 104 Salem 8989898989


NAME ROLL_NO LOCATION PHONE_NUMBER

Sumathi 105 Kanchipuram 8989856868

Ajay 201 Mumbai 9090901234

Meena 202 Delhi 8080805678

Explanation:
 The subquery SELECT * FROM Temp_Students selects all rows from
the helper table.
 The INSERT INTO Student adds these rows into the main Student table.
 Thus, Ajay and Meena are successfully added.
Example 3: Using Subquery with DELETE
In this example, we use a subquery with DELETE to remove certain rows
from the Student table. Instead of hardcoding roll numbers, the subquery
finds them based on conditions.
Query:
DELETE FROM Student
WHERE ROLL_NO IN (
SELECT ROLL_NO FROM Student WHERE ROLL_NO <= 101 OR
ROLL_NO = 201
);
Output
NAME ROLL_NO LOCATION PHONE_NUMBER

Raj 102 Coimbatore 8877665544

Sasi 103 Madurai 7766553344

Ravi 104 Salem 8989898989

Sumathi 105 Kanchipuram 8989856868

Meena 202 Delhi 8080805678

Explanation:
 The subquery selects roll numbers 101 and 201.
 The outer query deletes students having those roll numbers.
 As a result, Ram (101) and Ajay (201) are removed.
Example 4: Using Subquery with UPDATE
Subqueries can also be used with UPDATE. In this example, we update
student names to "Geeks" if their location matches the result of a subquery.
Query:
UPDATE Student
SET NAME = 'Geeks'
WHERE LOCATION IN (
SELECT LOCATION FROM Student WHERE LOCATION IN ('Salem',
'Delhi')
);
Output
NAME ROLL_NO LOCATION PHONE_NUMBER

Raj 102 Coimbatore 8877665544

Sasi 103 Madurai 7766553344

Geeks 104 Salem 8989898989

Sumathi 105 Kanchipuram 8989856868

Geeks 202 Delhi 8080805678

Explanation:
 The subquery selects locations 'Salem' and 'Delhi'.
 The outer query updates the NAME field for students whose location
matches those values.
 Thus, Ravi and Meena are renamed to "Geeks".
Example 5: Simple Subquery in the FROM Clause
This example demonstrates using a subquery inside the FROM clause,
where the subquery acts as a temporary (derived) table.
Query:
SELECT NAME, PHONE_NUMBER
FROM (
SELECT NAME, PHONE_NUMBER, LOCATION
FROM Student
WHERE LOCATION LIKE 'C%'
) AS subquery_table;
Output
NAME PHONE_NUMBER

Ram 9988775566

Raj 8877665544
Explanation:
 The subquery (SELECT NAME, PHONE_NUMBER, LOCATION FROM
Student WHERE LOCATION LIKE 'C%') fetches students whose
location starts with "C" (Coimbatore, Chennai, etc.).
 The outer query then selects only NAME and PHONE_NUMBER from
this derived table.
 Only Raj qualifies because his location is Coimbatore.
Example 6: Subquery with JOIN
We can also use subqueries along with JOIN to connect data across
tables.
Query:
SELECT s.NAME, s.LOCATION, ns.SECTION
FROM Student s
INNER JOIN (
SELECT ROLL_NO, SECTION
FROM New_Student WHERE SECTION = 'A'
) ns
ON s.ROLL_NO = ns.ROLL_NO;
Output
NAME LOCATION SECTION

Ravi Salem A

Raj Coimbatore A

You might also like