Open In App

SQL | Subquery

Last Updated : 10 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In SQL, subqueries are one of the most powerful and flexible tools for writing efficient queries. A subquery is essentially a query nested within another query, allowing users to perform operations that depend on the results of another query. This makes it invaluable for tasks such as filtering, calculating aggregates, or even modifying data dynamically.

In this article, we will explain the concept of SQL subqueries, exploring their syntax, use cases, and how they can be applied effectively. We’ll provide detailed examples and outputs to ensure we fully understand how to use subqueries to simplify complex operations.

What is SQL Subquery?

In SQL, a subquery can be defined as a query embedded within another query. It is often used in the WHERE, HAVING, or FROM clauses of a statement. Subqueries are commonly used with SELECT, UPDATE, INSERT, and DELETE statements to achieve complex filtering and data manipulation.

While there is no universal syntax for subqueries, they are commonly used in SELECT statements as follows. This general syntax allows the outer query to use the results of the inner subquery for filtering or other operations.

Syntax

SELECT column_name
FROM table_name
WHERE column_name expression operator
(SELECT column_name FROM table_name WHERE ...);

Key Characteristics of Subqueries

  1. Nested Structure: A subquery is executed within the context of an outer query.
  2. Parentheses: Subqueries must always be enclosed in parentheses.
  3. Comparison Operators: Subqueries can be used with operators like =, >, <, IN, NOT IN, LIKE, etc.
  4. Single-Row vs. Multi-Row Subqueries: Subqueries may return a single value (e.g., a single row) or multiple values.

Common SQL Clauses for Subqueries

Subqueries are frequently used in specific SQL clauses to achieve more complex results. Here are the common clauses where subqueries are used:

1. WHERE Clause

Subqueries in the WHERE clause help filter data based on the results of another query. For example, you can filter records based on values returned by a subquery.

2. FROM Clause

Subqueries can be used in the FROM clause to treat the result of the subquery as a derived table, which can then be joined with other tables.

3. HAVING Clause

Subqueries in the HAVING clause allow you to filter grouped data after aggregation has occurred.

Examples of 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 the flexibility and importance of subqueries in simplifying complex database tasks. Consider the following two tables:

1. DATABASE TABLE

Database-table

Database Table

2. STUDENT TABLE

student-table

Student Table

Example 1: Fetching Data Using Subquery

This example demonstrates how to use a subquery to retrieves roll numbers of students in section ‘A’, and the outer query uses those roll numbers to fetch corresponding details (name, location, and phone number) from the DATABASE table. This enables filtering based on results from another table.

Query:

SELECT NAME, LOCATION, PHONE_NUMBER 
FROM DATABASE
WHERE ROLL_NO IN (
SELECT ROLL_NO FROM STUDENT WHERE SECTION='A'
);

Output

NAME LOCATION PHONE_NUMBER
Ravi Salem 8989898989
Raj Coimbatore 8877665544

Example 2: Using Subquery with INSERT

In this example, a subquery is used to insert all records from the Student2 table into the Student1 table. The SELECT statement inside the INSERT INTO statement fetches all the data from Student2 and inserts it into Student1.

Student1 Table

NAME ROLL_NO LOCATION PHONE_NUMBER
Ram 101 chennai 9988773344
Raju 102 coimbatore 9090909090
Ravi 103 salem 8989898989

Student2 Table

NAME ROLL_NO LOCATION PHONE_NUMBER
Raj 111 chennai 8787878787
Sai 112 mumbai 6565656565
Sri 113 coimbatore 7878787878

Query:

INSERT INTO Student1 
SELECT * FROM Student2;

Output

NAME ROLL_NO LOCATION PHONE_NUMBER
Ram 101 chennai 9988773344
Raju 102 coimbatore 9090909090
Ravi 103 salem 8989898989
Raj 111 chennai 8787878787
Sai 112 mumbai 6565656565
Sri 113 coimbatore 7878787878

Example 3: Using Subquery with DELETE

Subqueries are often used in DELETE statements to remove rows from a table based on criteria derived from another table. The subquery retrieves roll numbers of students from Student1 where the location is ‘Chennai‘. The outer query then deletes records from Student2 whose roll numbers match those from the subquery. This allows for targeted deletion based on data from another table.

Query:

DELETE FROM Student2 
WHERE ROLL_NO IN (SELECT ROLL_NO
FROM Student1
WHERE LOCATION = 'chennai');

Output

NAME ROLL_NO LOCATION PHONE_NUMBER  
Sai 112 mumbai 6565656565  
Sri 113 coimbatore 7878787878  

Example 4: Using Subquery with UPDATE

The subquery retrieves the locations of ‘Raju’ and ‘Ravi’ from Student1. The outer query then updates the NAME in Student2 to ‘Geeks’ for all students whose LOCATION matches any of the retrieved locations. This allows for updating data in Student2 based on conditions from Student1.

Query:

UPDATE Student2 
SET NAME='geeks'
WHERE LOCATION IN (SELECT LOCATION
FROM Student1
WHERE NAME IN ('Raju', 'Ravi'));

Output

NAME ROLL_NO LOCATION PHONE_NUMBER  
Sai 112 mumbai 6565656565  
geeks 113 coimbatore 7878787878  

Conclusion

Subqueries in SQL are an essential tool for performing complex operations efficiently. They allow developers to break down queries into smaller, manageable parts and dynamically retrieve or manipulate data. By embedding one query inside another, subqueries allow for more dynamic filtering, updating, inserting, and deleting of data. Mastering subqueries and understanding their applications in different SQL clauses such as WHERE, FROM, and HAVING enhances our ability to perform advanced data manipulations and optimizations in relational databases.

FAQs

What is a Subquery in SQL?

A subquery is a query nested within another SQL query, often used for filtering or computing data dynamically based on results from another query.

Where Can Subqueries Be Used?

Subqueries can be used in clauses like WHERE, FROM, HAVING, and with commands like SELECT, UPDATE, DELETE, and INSERT.

What is the Difference Between Subquery and Nested Query?

A subquery and nested query are often used interchangeably, but a nested query refers specifically to queries embedded within another SQL query. By mastering these concepts, you can efficiently manage complex databases and perform advanced data manipulation.



Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg