Open In App

SQL | Subquery

Last Updated : 14 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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. They are an essential tool when we need to perform operations like:

  • Filtering: Getting specific records based on conditions derived from another query.
  • Aggregating: Performing aggregate functions like SUM, COUNT, or AVG based on subquery results.
  • Updating: Dynamically updating records based on values from other tables.
  • Deleting: Deleting records from one table using criteria based on another.

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. Depending on the result, different SQL constructs may be required.

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 or temporary table that can be joined with other tables.

3. HAVING Clause: Subqueries in the HAVING clause allow you to filter aggregated data after performing group operations.

Types of Subqueries

  1. Single-Row Subquery: Returns a single value (row). Useful with comparison operators like =, >, <.
  2. Multi-Row Subquery: Returns multiple values (rows). Useful with operators like IN, ANY, ALL.
  3. Correlated Subquery: Refers to columns from the outer query in the subquery. Unlike regular subqueries, the subquery depends on the outer query for its values.
  4. Non-Correlated Subquery: Does not refer to the outer query and can be executed independently.

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 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 in WHERE Clause

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

NAMELOCATIONPHONE_NUMBER
RaviSalem8989898989
RajCoimbatore8877665544

Explanation: The inner query fetches the roll numbers of students in section 'A'. The outer query uses those roll numbers to filter records from the DATABASE table.

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

NAMEROLL_NOLOCATIONPHONE_NUMBER
Ram101chennai9988773344
Raju102coimbatore9090909090
Ravi103salem8989898989

Student2 Table

NAMEROLL_NOLOCATIONPHONE_NUMBER
Raj111chennai8787878787
Sai112mumbai6565656565
Sri113coimbatore7878787878

Query:

INSERT INTO Student1 
SELECT * FROM Student2;

Output

NAMEROLL_NOLOCATIONPHONE_NUMBER
Ram101chennai9988773344
Raju102coimbatore9090909090
Ravi103salem8989898989
Raj111chennai8787878787
Sai112mumbai6565656565
Sri113coimbatore7878787878

Explanation: The SELECT statement inside the INSERT INTO query fetches all records from Student2 and inserts them into Student1.

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

NAMEROLL_NOLOCATIONPHONE_NUMBER
Sai112mumbai6565656565
Sri113coimbatore7878787878

Explanation: The subquery retrieves roll numbers of students from Student1 who are located in 'Chennai'. The outer query deletes those records from Student2.

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

NAMEROLL_NOLOCATIONPHONE_NUMBER 
Sai112mumbai6565656565 
geeks113coimbatore7878787878 

Explanation: The inner query fetches the locations of 'Raju' and 'Ravi' from Student1. The outer query updates the name to 'Geeks' in Student2 where the location matches those of 'Raju' or 'Ravi'

Tips for Writing Efficient Subqueries

While subqueries are powerful, here are some best practices to ensure your queries are efficient and maintainable:

  1. Avoid Nested Subqueries When Possible: Too many nested subqueries can slow down performance. Consider using JOIN operations if applicable.
  2. Use EXISTS Instead of IN for Better Performance: When dealing with large datasets, EXISTS can sometimes be more efficient than IN, especially when the subquery returns a large result set.
  3. Use Aliases for Clarity: When using subqueries in the FROM clause, always use aliases to make your query more readable and maintainable.
  4. Test with Different Scenarios: Always test your subqueries in different environments (e.g., development vs. production) to ensure they perform well

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.


Next Article
Article Tags :

Similar Reads