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:
Difference between Where and Having Clause in SQL
Next article icon

Difference Between Nested Subquery, Correlated Subquery and Join Operation

Last Updated : 19 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Nested subqueries, correlated subqueries, and join operations are common methods for querying data, but they all have different behaviors and serve various purposes. Joins are used to combine two or more different tables based on a common field between them. We can easily retrieve data from multiple tables using joins.

Similarly, Nested and correlated subqueries are a combination of two queries (inner and outer queries) but serve different purposes. All these help in optimizing performance and ensuring accurate data retrieval. So, in this article, we are going to discuss the JOIN Operation and Subquery(nested and correlated) in detail.

JOIN Operation

A join operation is a binary operation used to combine data or rows from two or more tables based on a common field between them. It is often spread across multiple tables in a relational database. INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN are different types of Joins.

Example:

Orders (OrderID , OrderDate);
Customers (CustomerID, CustomerName, ContactName, Country);

Find details of customers who have ordered.

Query

SELECT * from Customers JOIN Orders 
ON Orders.OrderID=Customers.CustomerID;

Output

output

output

Advantages of Join Operations

  • Performance: Joins are faster than subqueries and efficient as well especially with large datasets.
  • Flexibility: it is easier to combine and work with data with multiple tables in one query, allowing us to handle complex data relationships.
  • Readability: understanding the complex multi-table queries will be easy.

Disadvantages of Join Operations

  • Complex large queries: it is difficult to read and understand easily if the query is very large with multiple joins in it.
  • Duplication of Data: duplication of rows may occur sometimes which need to manages carefully.

Subquery

The provided SQL script creates two tables, Customers and Orders, and populates them with sample data. However, the Orders table lacks a foreign key to associate orders with customers. This can lead to difficulties in linking orders to specific customers and querying related information. To resolve this, you should add a CustomerID column to the Orders table and establish a foreign key relationship with the Customers table to ensure data integrity and enable meaningful queries across these tables.

CREATE TABLE Customers(
CustomerID INT PRIMARY KEY NOT NULL,
CustomerName VARCHAR(50),
ContactName VARCHAR(50),
Country VARCHAR(50);

CREATE TABLE Orders(
OrderID INT ,
OrderDate DATE);

INSERT INTO Orders(OrderID,OrderDate)
VALUES(1,'11/12/2020'),
(2,'14/12/2014'),
(3,'17/1/2019'),
(4,'18/2/2020');

INSERT INTO Customers(CustomerID,CustomerName, ContactName,Country)
VALUES (1,'John','David','USA'),
(2,'Leo','David','UK'),
(3,'David','John','USA'),
(4,'Betty','Leo','UK'),
(5,'Peter','Peter','UAE');

Customers table:

Customer Table

Customer Table

Orders table:

Order Table

Order Table

Nested Subquery

A Nested subquery also known as inner query is placed inside another SQL query called as outer query and the Inner query will runs first, and executed only once. Outer query is executed with the result from Inner query. Hence, the Inner query is used in execution of the Outer query. Often used with WHERE , FROM or SELECT clause.

Example:

Orders (OrderID, CustomerID, OrderDate);
Customers (CustomerID, CustomerName, ContactName, Country);

Find details of customers who have ordered.

Query

SELECT * FROM Customers WHERE 
CustomerID IN (SELECT CustomerID FROM Orders);

Output

output

output

Advantages of Nested Subqueries

  • Modularity: Nested subqueries allows queries to manage in parts means the queries are broken down into smaller parts and which is easier to manage.
  • Readability: Breaking a query into smaller parts makes it easier to read and understand, better for simple use cases.
  • Simplifies Logic: Nested queries sometimes allows to avoid complex joins and filtering conditions.
  • Independent execution: subquery is executed independently from the outer query, which makes it reusable in different scenarios.

Disadvantages of Nested Queries

  • Performance: They can be slower, especially in those cases when an inner query runs multiple times for each row in the outer query. This creates the issue in performance.
  • Limited Optimization: because of complex nested queries many databases struggle to optimize them and which leads to inefficient execution plans.
  • Complexity in Multi-Level Nesting: As if there are multilevel or deeply nested queries is present then it is harder to manage and debug them.
  • Larger Data can be less efficient: If there is larger datasets than nested queries can become inefficient, as they may require more resources and time to process than join operations.

Correlated Subquery

In Correlated Query, Outer query executes first and for every Outer query row Inner query is executed. Hence, the Inner query uses values from the Outer query.

Example:

Orders (OrderID , OrderDate);
Customers (CustomerID, CustomerName, ContactName, Country);

Find details of customers who have ordered.

Query

SELECT * FROM Customers where 
EXISTS (SELECT CustomerID FROM Orders
WHERE Orders.OrderID=Customers.CustomerID);

Output

output

output

Advantages of Correlated Queries

  • Row-by-Row Evolution: for making them useful for filtering or matching data between related tables it allows to perform comparisons and checks on a row-by-row basis.
  • Dynamic Querying: correlated queries allows for dynamic and flexible data retrieval as the subquery is dependent on each row from the outer queries.
  • Complex Conditions can be Simplified: across related data these subquery can simplified the logic in cases where you need to apply complex conditions.

Disadvantages of Correlated Queries

  • Performance Issues: If the dataset is large and the subquery is executed for every row processed by the outer query, then the performance gets slow.
  • Complexity: for beginners to write and maintain them can be complex and difficult task , also to read and understand them easily.
  • Resource-intensive: These subqueries consumes more processing power and memory as they are complex sometimes and require multiple executions.

Application of Join Operation and Subquery

To understand the difference between Nested Subquery, Correlated Subquery, and Join Operation firstly we have to understand where we use subqueries and where to use joins.

When we want to get data from multiple tables we use join operation. Example: Let’s consider two relations as:

Employee (eId, eName, eSalary, dId);
Department (dId, dName, dLocation);

Now, we have to find employee names and Department name working at London Location. Here, we have to display eName from employee table and dName from Department table. Hence we have to use Join Operation.

SELECT e.eName, d.dName from Employee e, 
Department d
where e.dId=d.dId and d.dLocation="London";

When we want to get data from one table and the condition is based on another table we can either use Join or Subquery. Now, we have to find employee names working at London Location. Here, we have to display only eName from the employee table hence we can use either Join Operation or Subquery Using Join Operation:

SELECT e.eName from Employee e, Department d 
where e.dId=d.dId and d.dLocation="London";

Using Subquery:

SELECT eName from Employee 
where dId=(SELECT dId from Department where dLocation="London");

After understanding the basic difference between Join and Subqueries, Now we will understand the difference between Nested Subquery, Correlated Subquery, and Join Operation.

Difference between Nested Query, Correlated Query and Join Operation

Parameters Nested Query Correlated Query Join Operation
Definition In Nested query, a query is written inside another query and the result of the inner query is used in the execution of the outer query.  In Correlated query, a query is nested inside another query and an inner query uses values from the outer query.                     The join operation is used to combine data or rows from two or more tables based on a common field between them. INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN are different types of Joins.
Approach Bottom-up approach i.e. Inner query runs first, and only once. The outer query is executed with result from the Inner query. Top to Down Approach i.e. Outer query executes first and for every Outer query row Inner query is executed. It is basically cross product satisfying a condition.
Dependency Inner query execution is not dependent on Outer query. Inner query is dependent on the Outer query. There is no Inner Query or Outer Query. Hence, no dependency is there.
Performance  Performs better than Correlated Query but is slower than Join Operation. Performs slower than both Nested Query and Join operations as for every outer query inner query is executed. By using joins we maximize the calculation burden on the database but joins are better optimized by the server so the retrieval time of the query using joins will almost always be faster than that of a subquery.

Conclusion

In conclusion, nested queries are best for simpler tasks where results from one query are used in another, but they can be slower for complex operations. Correlated queries offer dynamic referencing of outer query values, but they are often less efficient due to repeated executions. Join operations are generally the most efficient for combining data from multiple tables, making them ideal for complex and large-scale data retrieval.



Next Article
Difference between Where and Having Clause in SQL

D

deekshajaindodya
Improve
Article Tags :
  • Databases
  • DBMS
  • Difference Between
  • SQL

Similar Reads

  • Difference between Inner Join and Outer Join in SQL
    JOINS in SQL are fundamental operations used to combine data from multiple tables based on related columns. They are essential for querying data that is distributed across different tables, allowing you to retrieve and present it as a single or similar result set. In this article, We will learn abou
    5 min read
  • Difference Between Equal and IN operator in SQL
    The equal and IN operators are commonly used comparison operators in SQL. While they serve similar purposes in filtering data, there are key differences in their functionality and use cases. Understanding when to use each operator can help optimize our queries and make them more readable. In this ar
    3 min read
  • Difference between Where and Having Clause in SQL
    In SQL, the WHERE and HAVING clauses are essential for filtering data and refining query results. While both serve the purpose of applying conditions, they are used at different stages of query execution and for distinct purposes. Understanding the differences between the WHERE and HAVING clauses is
    4 min read
  • Difference between Simple and Complex View in SQL
    A View in SQL as a logical subset of data from one or more tables. Views are used to restrict data access. A View contains no data of its own but it is like a window through which data from tables can be viewed or changed. The table on which a View is based is called BASE Tables. There are 2 types o
    2 min read
  • Difference Between Left Join and Left Outer Join
    In SQL language, different joins are used to assemble rows from two or more tables from the related column. The terms "Left Join" and "Left Outer Join" are used interchangeably in SQL but they refer to the same concept. A Left Join retrieves all records from the left table (the first table in the qu
    5 min read
  • Difference Between JOIN, IN and EXISTS Clause in SQL
    SEQUEL widely known as SQL, Structured Query Language is the most popular standard language to work on databases. We can perform tons of operations using SQL which includes creating a database, storing data in the form of tables, modify, extract and lot more. There are different versions of SQL like
    4 min read
  • Difference between Natural join and Cross join in SQL
    A JOIN clause is used to combine rows from two or more tables, based on a related data column in between them. Natural Join and Cross Join both serve different purposes in database management. While the former matches column with same name, the latter outputs all possible row combinations between tw
    2 min read
  • Difference between From and Where Clause in SQL
    1. FROM Clause: It is used to select the dataset which will be manipulated using Select, Update or Delete command.It is used in conjunction with SQL statements to manipulate dataset from source table.We can use subqueries in FROM clause to retrieve dataset from table. Syntax of FROM clause: SELECT *
    2 min read
  • Difference Between Cube and Rollup in SQL Server
    In SQL Server, both ROLLUP and CUBE are sub-clause of the GROUP BY clause and are used in conjunction with aggregate functions to produce summary reports. It helps to generate multiple group sets using the hierarchy. To enhance the capabilities of grouping and aggregation, SQL Server provides two po
    3 min read
  • Compare and Find Differences Between Two Tables in SQL
    Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, etc. Here we are going to see how to Compare and Find Differences Between Two Tables in SQL Here, we will first create a database name
    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