A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/sql/sql-subquery/ below:

SQL Subquery - GeeksforGeeks

SQL Subquery

Last Updated : 02 Aug, 2025

A subquery in SQL is a query nested within another SQL query. It allows you to perform complex filtering, aggregation, and data manipulation by using the result of one query inside another. Subqueries are often found in the WHERE, HAVING, or FROM clauses and are supported in SELECT, INSERT, UPDATE, and DELETE statements.

They are an essential tool when we need to perform operations like:

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:

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

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

NAME LOCATION PHONE_NUMBER Ravi Salem 8989898989 Raj Coimbatore 8877665544

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

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 can be used in DELETE statements to remove rows based on data from another table. In this example, the subquery gets roll numbers from Student1 where the location is 'Chennai'. The outer query then deletes matching rows from Student2.

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

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

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

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


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4