Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
SQL Correlated Subqueries
Next article icon

SQL Server Correlated Subquery

Last Updated : 11 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Correlate subquery is a great tool in SQL servers that allows users to fetch the required data from the tables without performing complex join operations. In SQL, a subquery is a query nested inside another query. A correlated subquery is a specific type of subquery that references columns from the outer query, creating a relationship between the two.

In this article, we will learn about the correlated subqueries in SQL Server step by step with various examples. We will learn how correlated subquery can be used as a substitute for complex join operations. So deep dive into this article and master the correlate subqueries in SQL server.

What are Correlated Subqueries?

A correlated subquery is a nested inner query whose results depend on the outer query for its values. The inner query gets executed once for each row evaluated by the outer query. In simple words, the result of the subquery will be dependent on the outer query. Don't confuse correlated subqueries with the nested queries. In nested queries, the inner query is only executed one time whereas correlated subqueries get executed for every row returned by the outer query. The outer query can consist of UPDATE, DELETE, WHERE, and SELECT clauses in case of correlated subqueries.

Correlated_Subquery

Key points about correlated subqueries:

  • The inner query executes once for every row in the outer query.
  • The inner query has a reference to a column in the outer query in its WHERE clause.
  • The results of the inner query are used by the outer query.

Syntax:

SELECT columns
FROM outer_table

WHERE condition_operator

(SELECT columns
FROM inner_table
WHERE outer_table.column = inner_table.column);

The syntax of the Correlated subqueries mainly consist of 3 parts:

  • In the first part we will have to specify the columns we want to retirive in the final result set from the outer query. Use the SELECT clause to select the required columns and FROM clause to select the outer table from which the main query retrieves rows.
  • In the second part we will have to define the conditions for selecting rows from the outer table using the Where clause. The conditions can consist of comparisons logical operators or any valid conditions specified by the user.
  • In the third part we will have to define our correlated subquery. This inner query will retrieve the columns from the inner table. The correlation will be established by specifying a condition that links a column from the outer query's table to a column in the inner query's table.

Advantages of Using Correlated Subquery

Here are some of the key advantages of using the Correlated subqueries in SQL Server:

  • Avoid Complex Joins: Correlated subqueries can be used as a substitute for complex join operations. This can help to simplify the queries and improve the readability.
  • Query Optimization: In some cases the correlated subquery allows the database optimizer to efficiently process the data using the indexes which can optimize the overall performance of our query.
  • Allows row by row processing: For correlated subquery the inner query is executed for every row of the outer table which provides an easy way to filter data row by row.
  • Code reusability: The inner query of the correlated subqueries can be reused across various queries by simply changing the outer query which promotes the code reusabililty factor.

Examples of Correlated Subquery in SQL Server

Let us consider the following two demo tables Customers and Orders on which we will execute our queries for better understanding.

Customer Table:

Table-Customers
Table-Customers

Order Table:

Table-Orders
Table-Orders

Example 1 : Correlated Subquery Using the Exists Operator

In the following example we will see how we can use the Exists operator along with the correlated subqueries to fetch the required result:

SELECT CustomerName
FROM Customers C
WHERE EXISTS (
SELECT 1
FROM Orders O
WHERE O.CustomerID = C.CustomerID
);

Output:

Example1_Output
Output

Explanation: In the above example the outer query selects the name of the customers from the Customers table and the correlated subquery checks if there exists any orders in the Orders table for the current customer from the outer query. If a match is found the name of the customers is shown in the result set from the outer table Customer.

Example 2: Correlated Subquery Using the SELECT Clause

In the following example we will see how we can use the Select clause along with the correlated subqueries to fetch the required result:

SELECT CustomerName
FROM Customers C
WHERE (SELECT COUNT(*)
FROM Orders
WHERE CustomerID = C.CustomerID) > 1;

Output:

Example2_Output

Explanation: In the above example the outer query selects the name of the customers from the Customers table and the correlated subquery counts the number of orders for each customer and checks if it is greater than 1. If a match is found the record is displayed in the result set. In the orders table only 1 customer had placed multiple orders whose customerId was 1 which is returned in the result set.

Example 3: Correlated Subquery to Update the data

In the following example we will see how we can update our data in the tables with the help of correlated subqueries:

UPDATE Orders
SET Quantity = Quantity + 1
WHERE CustomerID IN (
SELECT CustomerID
FROM Customers
WHERE State = 'Maharashtra'
);

Output:

Example3_Output
Output

Explanation: In the above example the UPDATE statement increases the quantity of orders in the Order table and the correlated subquery identifies customers who belongs to the state Maharashtra and if a match is found then the quantity of orders is updated in the orders table. In our orders table we had 2 customers who belonged to Maharahtra and thus their order quantity was updated by 1 in the result set.

Example 4: Correlated Subquery to Delete the data

In the following example we will see how we can delete the data from the tables with the help of correlated subqueries:

DELETE FROM Customers
WHERE NOT EXISTS (
SELECT 1
FROM Orders
WHERE Customers.CustomerID = Orders.CustomerID
);

Output:

Example4_Output
Output

Explanation: In the above example the DELETE statement removes the record from the customers table and the correlated subquery identifies customers who have not placed any order if a match is found then the record of that customer is deleted from the outer customer table. In our table we had only one customer with customerID =5 who has not placed any order and we can see in the output his/her entry was deleted from the customers table.

Example 5: Find nth Value using Correlated Subquery

In the following example we will use the correlated subquery to find out the second oldest person from the table customers.

SELECT CustomerID, CustomerName, Age
FROM Customers C1
WHERE 1 = (
SELECT COUNT(DISTINCT Age)
FROM Customers C2
WHERE C2.Age > C1.Age
);

Output:

Example5_Output
Output

Explanation: The outer query C1 selects the customers from the Customer table and the correlated subquery counts the number of distinct ages that are greater than the age of the current customer. The outer query then filters customers where the count is equal to 1 which means the customer found is the second oldest person in the data set. Similary you can use 2 to find the third oldest employee from the table and so on. In our table the oldest person was of age 42 so as we wanted the second oldest person, the details of the person with age 35 were returned in the result set.

Conclusion

In this article, we have learned the working of correlated subqueries in SQL servers. We have learned how we can use these subqueries to fetch the result from the inner tables whose output depends on the outer tables. We understood how these subqueries can be used in place of complex join operations to fetch the required results from multiple tables. We hope this article has helped you to understand correlated subqueries in SQL servers.


Next Article
SQL Correlated Subqueries
author
gaurav472
Improve
Article Tags :
  • Geeks Premier League
  • SQL Server
  • Databases
  • Geeks Premier League 2023

Similar Reads

  • SQL Correlated Subqueries
    In SQL, correlated subqueries are powerful tools that allow us to perform row-by-row comparisons and retrieve complex data. Unlike regular subqueries, correlated subqueries depend on values from the outer query, making them dynamic and highly effective for solving complex database problems. In this
    5 min read
  • SQL Server UPDATE JOIN
    In the expansive realm of SQL Server, the UPDATE JOIN operation emerges as a potent tool for modifying data within tables by combining information from multiple sources. Unlike a traditional UPDATE statement that modifies a single table, UPDATE JOIN enables the modification of records based on condi
    6 min read
  • SQL | Subquery
    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, cal
    6 min read
  • SQL Server EXCEPT Operator
    Structured Query Language also known as SQL is a tool for storing, managing, and manipulating relational databases. SQL Server is a popular relational database management system (RDBMS) developed by Microsoft, providing a variety of operators to perform different operations on given datasets. One su
    4 min read
  • SQL Join vs Subquery
    The difference between SQL JOIN and subquery is that JOIN combines records of two or more tables whereas Subquery is a query nested in another query. SQL JOIN and Subquery are used to combine data from different tables simplifying complex queries into a single statement. Here we will discuss SQL JOI
    4 min read
  • PL/SQL Subqueries
    PL/SQL subqueries are powerful SQL features that allow for the nesting of one query inside another for dynamic data retrieval. They have extensive applications when complex problems are to be solved by reducing them into smaller, more manageable queries. The inner query, usually called the subquery,
    10 min read
  • MYSQL Subquery
    A subquery is embedded inside another query and acts as input or output for that query. Subqueries are also called inner queries and they can be used in various complex operations in SQL. Subqueries help in executing queries with dependency on the output of another query. Subqueries are enclosed in
    4 min read
  • SQL Server Common Table Expressions
    SQL Server is a relational database management system (RDBMS) that is used to handle complex data and maintain it in of tabular manner. With the help of SQL Server, one can easily protect their data as it provides various security features. In this article, we are going to explore SQL server's CTE a
    8 min read
  • SQL Server INTERSECT Operator
    In SQL Server, the INTERSECT operator is a kind of set operator that is used to combine the results of two SELECT statements and return rows which is common between them. In this article, We will explore the syntax, key concepts, and practical examples of using the INTERSECT operator. Whether you ar
    5 min read
  • How to Update Table Rows in SQL Server using Subquery ?
    Updating table rows in SQL Server using a subquery is a common operation that allows us to modify records based on values derived from another table or query. In this article, we will explain how to update table rows in SQL Server using subquery with the help of examples. Updating Table Rows Using a
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences