The Wayback Machine - https://web.archive.org/web/20241009203032/https://www.geeksforgeeks.org/join-operation-vs-nested-query-in-dbms/
Open In App

Join operation Vs Nested query in DBMS

Last Updated : 09 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The growth of technology and automation coupled with exponential amounts of data has led to the importance and omnipresence of databases which, simply put, are organized collections of data. Considering a naive approach, one can theoretically keep all the data in one large table, however that increases the access time in searching for a record, security issues if the master table is destroyed, redundant storage of information and other issues. So tables are decomposed into multiple smaller tables. 

For retrieving information from multiple tables, we need to extract selected data from different records, using operations called join(inner join, outer join and most importantly natural join). Consider 2 table schemas employee(employee_name, street, city)with n rows and works(employee_name, branch_name, salary) with m rows. A cartesian product of these 2 tables creates a table with n*m rows. A natural join selects from this n*m rows all rows with same values for employee_name. To avoid loss of information(some tuples in employee have no corresponding tuples in works) we use left outer join or right outer join. 

A join operation or a nested query is better subject to conditions: 
 

  • Suppose our 2 tables are stored on a local system. Performing a join or a nested query will make little difference. Now let tables be stored across a distributed databases. For a nested query, we only extract the relevant information from each table, located on different computers, then merge the tuples obtained to obtain the result. For a join, we would be required to fetch the whole table from each site and create a large table from which the filtering will occur, hence more time will be required. So for distributed databases, nested queries are better.
  • RDBMS optimizer is concerned with performance related to the subquery or join written by the programmer. Joins are universally understood hence no optimization issues can arise. If portability across multiple platforms is called for, avoid subqueries as it may run into bugs(SQL server more adept with joins as its usually used with Microsoft’s graphical query editors that use joins).
  • Implementation specific: Suppose we have queries where a few of the nested queries are constant. In MySQL, every constant subquery would be evaluated as many times as encountered, there being no cache facility. This is an obvious problem if the constant subquery involves large tuples. Subqueries return a set of data. Joins return a dataset which is necessarily indexed. Working on indexed data is faster so if the dataset returned by subqueries is large, joins are a better idea.
  • Subqueries may take longer to execute than joins depending on how the database optimizer treats them(may be converted to joins). Subqueries are easier to read, understand and evaluate than cryptic joins. They allow a bottom-up approach, isolating and completing each task sequentially.
     

Join operation and nested queries are both used in relational database management systems (RDBMS) to combine data from multiple tables, but they differ in their approach.

Join operation:
A join operation combines data from two or more tables based on a common column or columns. The join operation is performed using the JOIN keyword in SQL, and it returns a single result set that contains columns from all the tables involved in the join.

For example, let’s say we have two tables, Table1 and Table2, with the following data:

Table1
ID | Name
1 | John
2 | Sarah
3 | David

Table2
ID | Address
1 | 123 Main St.
2 | 456 Elm St.
4 | 789 Oak St.

If we want to combine the data from these two tables based on the ID column, we can perform an inner join using the following SQL query:

SELECT Table1.ID, Table1.Name, Table2.Address
FROM Table1
INNER JOIN Table2
ON Table1.ID = Table2.ID

Result:
ID | Name | Address
1 | John | 123 Main St.
2 | Sarah | 456 Elm St.

Nested query:
A nested query is a SQL query that is embedded within another SQL query. It is used to retrieve data from one or more tables based on a condition that is evaluated using the results of another query. The nested query is executed first, and its results are used to evaluate the outer query.

For example, let’s say we have the same two tables as before:

Table1
ID | Name
1 | John
2 | Sarah
3 | David

Table2
ID | Address
1 | 123 Main St.
2 | 456 Elm St.
4 | 789 Oak St.

If we want to retrieve the names of the people who have an address in Table2, we can use a nested query as follows:

SELECT Name
FROM Table1
WHERE ID IN (SELECT ID FROM Table2)

Result:
Name
John
Sarah

In this case, the nested query is executed first, and it returns the ID values of the rows in Table2. These ID values are then used to evaluate the outer query, which retrieves the names of the people who have those ID values in Table1.

The choice between using a join operation or a nested query depends on the specific requirements of the task at hand. Joins are often faster and more efficient for large datasets, but nested queries can be more flexible and allow for more complex conditions to be evaluated.


Previous Article
Next Article

Similar Reads

Should I join a mass recruiter or a startup?
A Startup as the name suggests, is a young company that is just beginning to develop and usually small in size and have bare minimum finances. These companies generally offer a product or service that is not currently being offered elsewhere in the market, means based on new ideas or that the founders believe is being offered in an inferior manner
5 min read
Infosys Interview Experience for Operation Executive
The first interview or first job is always a memorable moment in everyone’s life, same with me. My first interview was for an Operation Executive role in Infosys. I was so nervous before my interview but well-prepared with some questions from 'Geeksforgeeks'. There was a total of 3 rounds and each round was eliminated. Round 1: An online written ap
3 min read
Climber Interview Experience for Operation Executive | On-Campus 2021
My Captain by The Climber is an online platform that helps the students to take the first step in their field of passion with the help of young achievers, mentors, and guides. There were three rounds including the interview for this role and the eligibility criteria were 60% throughout Round 1: Round 1 was just to register for the drive Round 2: Ro
2 min read
Infosys Interview Experience for Operation Executive
I am going to share my Experience of 19 min Interview for Operation Executive Role in Infosys. Virtual Interview: In the online virtual Interview first Interviewer ask me to Introduce myself. After that, he asks questions about my introduction About my internships like how you manage internships with your college work what you learn from that inter
2 min read
Infosys Interview Experience for Operation Executive
I recently applied for the position of Operation Executive at Infosys and went through a comprehensive selection process consisting of three rounds: an Online Aptitude test, a Technical Interview, and an HR Interview. Each stage provided me with the opportunity to showcase my skills and expertise. Round 1 : The journey began with an Online Aptitude
2 min read
Infosys Interview Experience For Operation Executive
Hi, Here I'm going share my interview experience for the operation executive. After completing my diploma in CSE (computer science engineer) I have applied for jobs in so many companies as of one in this. Firstly there was an aptitude test where there was logical reasoning and some questions related to Math like calculating distance and time, ratio
2 min read
Find the sum of diagonals passing through given coordinates for Q query
Given a 2D matrix of size N x M and Q queries where each query represents a coordinate (x, y) of the matrix, the task is to find the sum of all elements lying in the diagonals that pass through the given point. Examples: Input: N = 4, M = 4, mat[][] = {{1, 2, 2, 1}, {2, 4, 2, 4}, {2, 2, 3, 1}, {2, 4, 2, 4}}, query = { {0, 0}, {3, 1}, {3, 3} } Outpu
12 min read
Bentley System Interview Experience for Associate Software Developer
1. Coding Assessment 1 (Online) from HomeTwo Questions were asked and the the time was I guess 70 Mins Min Adjacent Swaps to Group Red Balls One question related to 2D Array Cleaning Robot Problem2. Coding Assessment 2 (Online) from Bentley Office PuneThe shortlisted students from the 1st Round were invited to the Pune Office to give Round 2. There
1 min read
Top 30 Java 8 Interview Questions and Answers for 2024
Java 8 introduced a host of powerful features that have significantly enhanced the Java programming language. Introducing new features such as Lambda Expressions, Stream API, Functional Interfaces, the new Date and Time API, and more. As a result, Java 8 skills are highly sought after by employers in the tech industry. To help you prepare for your
15+ min read
Accenture Interview Experience
I have gone through Accenture hiring process 2023 for experienced people . As I am experienced person (with 5 years in total IT experience)so I am putting the things here so that it might help other people in this community. First, there would be an online Assessment Test:This would be very specific to your primary skill test. 30 questions. Scoring
3 min read
LTI Mindtree Interview Experience
Embarking on the interview process with LTI Mindtree marked a pivotal moment in my career journey, filled with anticipation, preparation, and determination. As I navigated through each round of interviews, I encountered a series of challenges and opportunities that tested my skills, knowledge, and suitability for the role. Round 1: Initial Screenin
3 min read
Capgemini Exceller Interview Experience (On- Campus) 2023-24
Capgemini is a global leader in partnering with companies to transform and manage their business by harnessing the power of technology. The Group is guided everyday by its purpose of unleashing human energy through technology for an inclusive and sustainable future. Founded in 1967 in France, it has grown to become one of the world's largest consul
5 min read
IBM Interview Experience for Software Engineer
IBM is one of the top well-known MNCs. Round 1: ( coding test - 1)Round 1 is an Online coding test on the Hackerrank platform which consists of 3 coding questions (difficulty level: Easy to medium)Questions were modified versions of:https://www.geeksforgeeks.org/stock-buy-sell/https://www.geeksforgeeks.org/problems/reverse-a-linked-list/1Tip: Since
2 min read
DeltaX Interview Experience for Associate Product Engineer (On-Campus)
Recently, DeltaX came for Hiring candidates for Associate Product Engineer The drive is of 1-day event.Eligibility criteria:50% or 5.0 in B.Tech average, till date.Drive Consists of 3 RoundsRound 1: Online MCQ TestThe duration of the test is about 45 minutes and no webcam is there while this round happened. This test covers all the topics related t
3 min read
Propel Interview Experience
Let me share my interview experience on Propel for the role of Developer. To know about the company, visit There were three rounds. Round 1 was an Aptitude test, round 2 was Programming followed by a technical HR round. Round 1:The aptitude test had a duration of 75 mins, it consisted of logical, verbal, and mathematical questions. No negative mark
1 min read
LinkedIn Interview Experience for Summer Intern 2023
LinkedIn visited our campus in Oct'22 for Software Development Engineer Internship role. Resumes were filtered out by LinkedIn itself and eligible candidates received the confirmation for selection in the recruitment process. 1. Coding Round (90 Mins.) Consists of 2 coding questions and 10 MCQs. Both coding questions have medium difficulty. I can't
3 min read
Tejas Networks Recruitment Process
This article will give you information about the company, its recruitment process, sample questions that have been asked previously, lots of experiences shared by other aspirants, and the portal where you can apply. Table of Content About Company:Recruitment Process:Tejas Networks Eligibility Criteria :Online Assessment: Technical Round 1: Technica
2 min read
HackerRank Interview Experience for SDE Internship
Following was my interview experience with HackerRank for Summer Intern 2023. I will try to make it short and to the point without giving too much information. Phase 1: I applied for the SDE intern role on https://www.hackerrank.com/careers somewhere around March 2022.Phase 2: One or two days after applying, I received an online assessment. The exa
1 min read
Accenture Interview Experience for ASE and Advanced ASE (On-Campus)
Hi geeks! So Accenture started their recruitment process on campus by virtually sending their Job Description and related information with a registration link. They sent details about 2 profiles they recruit for : ASE and Advanced ASE. After registering they sent us a profile link and password for their support website on Hirepro. Day 1 Qualifying
6 min read
Cognizant GenC Next Interview Experience (On-Campus)
Cognizant came to our campus and conducted the hiring process in 2-3 stages, Cognizant is known as one of the prominent and well known service based company. The eligibility criteria they had set was: 10th Grade cutoff: 6 CGPA12th Grade cutoff: 60%College current cut-off: 6 CGPABranch: CSE, IT, ECE, EEE JOB TITLE: There offered various job titles ,
8 min read
Accenture Interview Experience (On-Campus)
I recently appeared for the Accenture recruitment process. They were offering 2 profile roles: Associate Software Engineer.Software Engineer/Full Stack Engineer.This was a Pool Campus Recruitment process. Additional Requirements along with academic eligibility: PAN Card – all students must submit a PAN card that has their photo as the only identity
3 min read
TCS Codevita 9 Pre-qualifier round questions
TCS Codevita Pre-qualifier Round which was held on 15th August 2020 by TCS to filter out the candidates that suits there company as Software Engineers. The level of this Coding Round was medium and not that easy. Every candidate has to solve atleast one question to be qualified for the next round. The coding round comprised of good set of questions
11 min read
Window functions in SQL
Window functions apply to aggregate and ranking functions over a particular window (set of rows). OVER clause is used with window functions to define that window. OVER clause does two things : Partitions rows to form a set of rows. (PARTITION BY clause is used) Orders rows within those partitions into a particular order. (ORDER BY clause is used) N
4 min read
Nvidia Software Interview Experience | Internship
Company name - Nvidia Role - Software Intern Duration - 6 month Round 1 (Written Test) This is an on-campus drive for both B.Tech and M.Tech. The profile is a Software intern. Time duration – 1Hr Number of Questions – 50, No negative marking Mode - Pen Paper-based Sections: C/C++ (15 MCQs, Average but Confusing) – Pointers, Recursion, Unary Increme
4 min read
Viasat Interview Experience for Software Engineer
Round 1: Written Test There were 3 sections namely, Reading comprehensions, Quantitative Aptitude and Data Interpretation. There was section wise time limit. Questions were easy to moderate but the trick is to manage the time. Round 2: Technical Round 1 Technical Questions: Language you are most comfortable in? For me it was Java. What are the diff
1 min read
Linkedin Internship Interview Experience
Round 1: First round was online coding round. It was hosted on hackerrank platform. 4 questions were there. First one was to check weather a valid BST exists given its pre-order traversal.Find maximum number of consecutive days when all the employees were present. Matrix data was given. data[i][j] denotes the jth employee's attendance on ith day.Mi
2 min read
Debouncing in JavaScript
Debouncing is a technique in programming that helps improve the performance of web applications by controlling the frequency at which time-consuming tasks are triggered. If a task is triggered too often—like when a user types quickly or rapidly clicks a button—it can lead to performance issues. Debouncing provides a solution by limiting how frequen
3 min read
SQL | Arithmetic Operators
Prerequisite: Basic Select statement, Insert into clause, Sql Create Clause, SQL Aliases We can use various Arithmetic Operators on the data stored in the tables. Arithmetic Operators are: + [Addition] - [Subtraction] / [Division] * [Multiplication] % [Modulus] Addition (+) : It is used to perform addition operation on the data items, items include
5 min read
What is Array?
Array is a linear data structure where all elements are arranged sequentially. It is a collection of elements of same data type stored at contiguous memory locations. For simplicity, we can think of an array as a flight of stairs where on each step is placed a value (let's say one of your friends). Here, you can identify the location of any of your
2 min read
SQL | DESCRIBE Statement
Prerequisite: SQL Create Clause As the name suggests, DESCRIBE is used to describe something. Since in a database, we have tables, that's why do we use DESCRIBE or DESC(both are the same) commands to describe the structure of a table. Syntax: DESCRIBE one; OR DESC one; Note: We can use either DESCRIBE or DESC(both are Case Insensitive). Suppose our
2 min read