Friday, August 21, 2026

SQL JOINS (INNER, LEFT, RIGHT, and FULL Join)

 

Overview

A SQL Join statement combines data or rows from two or more tables based on a common field between them. This article gives a brief idea about different types of Joins such as INNER/EQUI JOIN, NATURAL JOIN, CROSS JOIN, SELF JOIN, etc.

What are JOINS in SQL?

SQL Joins are mostly used when a user is trying to extricate data from multiple tables (which have one-to-many or many-to-many relationships with each other) at one time. The join keyword merges two or more tables and creates a temporary image of the merged table. Then according to the conditions provided, it extracts the required data from the image table, and once data is fetched, the temporary image of the merged tables is dumped.

Large databases are often prone to data redundancy, i.e., the creation of repetitive data anomalies by insertion, deletion, and updation. But by using SQL Joins, we promote database normalization, which reduces data redundancy and eliminates redundant data.

In relational databases like SQL, there are two key fields generally used: Primary Key and Foreign Key. While the primary key is necessary for a table to qualify as a part of the relational database and identify each row uniquely of the table to which it belongs, the foreign key is responsible for linking two tables in the database. Here, the foreign key needs to be the primary key of another table. In some cases, the foreign and primary keys it references are present in the same table. In such cases, we use SQL Self Join. When we use SQL Joins, we often use these two key fields to identify what the user needs and accordingly form our queries.

Build an AI-First Career, Master the Complete Skillset

Choose from our industry-leading programs designed for career success


NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program
NSDC Certified

AI Forward Deployed Engineer Program

Full-stack engineering, production AI and client-facing consulting

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program

Example of SQL JOINS

We have a company’s employee database, where Table 1 (emp_dets) contains information about the employee like: employee id, employee name, and supervisor id. Table 2 (supervisor_dets) includes information on supervisors, i.e., their id and name.

Table 1 has emp_id as the primary key, and Table 2 has supervisor_id as the primary key. In Table 1, supervisor_id references Table 2. Hence, it is a foreign key for Table 1.

Joins in SQL

Depending on the users' needs, there are several types of joins. These joins are broadly classified into four types, i.e., Cross Self, Inner, and Outer.

Types of JOINS in SQL

CROSS JOINS in SQL

The Cartesian Join, a.k.a. Cross Join, is the cartesian product of all the rows of the first table with all the rows of the second table. Let’s say we have m rows in the first table and n rows in the second table. Then the resulting cartesian join table will have m*n rows. This usually happens when the matching column or WHERE condition is not specified.

General Syntax

SELECT column-name(s)
FROM table1 CROSS JOIN table2;

SELECT is used to specify all columns we need to display in the resulting table. FROM specifies the tables where we need to look for these columns. The type of join, i.e., CROSS JOIN, in this case, is placed between the two tables we wish to join.

Example

Let’s consider the scenario where the first table contains customer details, i.e., customer id and customer name, and the second table contains shopping details, i.e., product id and product name.

Cartesian / Cross Joins in SQL

Problem Statement

Write a query to give the cartesian product of the Customers and Shopping_Details tables.

Query

SELECT *
FROM Customers CROSS JOIN Shopping_Details;

SELF JOIN in SQL

In SQL Self Join, a table is joined to itself. This means each row of the table is joined with itself and all other rows concerning stated conditions if any. In other words, we can say that it is a merge between two copies of the same table. This is extremely helpful when the foreign key references the primary key of the same table.

General Syntax

SELECT a.column1 , b.column2
FROM table_name a, table_name b
WHERE some_condition;

Here we reference the same table with different names, i.e., a and b. This signifies a SELF JOIN.

Example

Let’s consider an employee table with the following details, i.e., employee id, name, phone number, and supervisor id. The supervisors are present at the employee table itself. Hence, the supervisor id acts like a foreign key which is also the primary key as it references the employee id.

Table_Name: Employees

Self Join in SQL

Problem Statement

Write a query to get all the employees who are also supervisors of some other employees from the given employee's table.

Query

SELECT a.Name AS Supervisors
FROM Employees a, Employees b
WHERE a.ID = b.supervisor_ID;

Here we use AS to rename the column name of the resultant table.

INNER JOIN in SQL

SQL Inner Join or Equi Join is the simplest join where all rows from the intended tables are cached together if they meet the stated condition. Two or more tables are required for this join. Inner Join can be used with various SQL conditional statements like WHERE, GROUP BY, ORDER BY, etc.

SQL inner join

General Syntax

SELECT column-name 
FROM table-1 INNER JOIN table-2 
WHERE table-1.column-name = table-2.column-name;

We can alternately use just the “JOIN” keyword instead of “INNER JOIN”.

Example

Let’s consider two tables of a supermarket set-up. The first table named Customers gives us information about different customers, i.e., their customer id, name, and phone number. Here, CustID is the primary key that uniquely identifies each row. The second table, named Shopping_Details, gives us information about items bought by customers, i.e., item id, customer id (referencing the customer that bought the item), item name, and quantity.

Equi Join in SQL

Problem Statement

Write a query to get all the customers who have bought items from the store. Display their name, item bought, and quantity.

Query

SELECT Customers.Name, Shopping_Details.Item_Name, Shopping_Details.Quantity
FROM Customers INNER JOIN Shopping_Details
WHERE Customers.ID==Shopping_Details.ID;
Sharpen Your Fundamentals with Free Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
A Course by Rahul Janghu

Learn Python for free and earn a certificate. This beginner-friendly course covers Python fundamentals, data structures, object-oriented programming, and hands-on projects, all in under 10 hours. Python powers web development, data science, and automation, making it one of the most in-demand skills in tech. No cost, no prerequisites. Just start building.

Free Agentic AI Course with Certification 2026: Learn Agent Memory and AI Skills
Free Agentic AI Course with Certification 2026: Learn Agent Memory and AI Skills
A Course by Gaurav Dadhich

Learn to build agentic AI agents that remember. Free, hands-on course on agent memory, retrieval, RAG vs memory & evaluation with certification. Start now.

Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
A Course by Tarun Luthra

Embark on your programming journey with our Free Java Course with Certificate. Master the fundamentals of Java and gain the skills needed for advanced Java development. This easy-to-follow course is designed with beginners in mind, offering a structured learning path to specialize in Java programming. With no prerequisites, this online Java course empowers you to learn Java at your own pace and take the first step toward a promising career in tech.

DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
A Course by Srikanth Varma

Scaler Topics free DBMS course is designed to help beginners learn about the fundamental concepts of database management systems. The course is completely online, and it comes with a free certificate of completion that you can add to your resume or LinkedIn profile. You'll learn about the most popular DBMS like MySQL, Oracle, and SQL Server, as well as the theoretical foundations of databases.

JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
A Course by Mrinal Bhattacharya

Kickstart your journey into web development with this free JavaScript course online with a certificate. Designed for beginners, this comprehensive JavaScript online course covers the essential concepts and skills needed to master Javascript, one of the most popular and widely used programming languages in the world. With a course duration of 10 hours and 9 minutes, you'll learn everything from the basics to advanced techniques, all at your own pace.

C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
A Course by Prateek Narang

Gain programming expertise with our C++ Course! Covering basics to advanced concepts, this online program provides a comprehensive curriculum encompassing environment setup, variables, conditional statements, loops, functions, pointers, arrays, sorting, character arrays, strings, and more. This C++ online course is perfect for beginners or seasoned programmers looking to enhance their skills and earn a certificate.

Special Case of INNER JOIN: NATURAL JOIN

SQL Natural Join is a type of Inner join based on the condition that columns having the same name and datatype are present in both the tables to be joined.

General Syntax

SELECT * FROM 
table-1 NATURAL JOIN table-2;

Example

Let’s consider two tables of a supermarket set-up. The first table named Customers gives us information about different customers, i.e., their customer id, name, and phone number. Here, CustID is the primary key that uniquely identifies each row. The second table, named Shopping_Details gives us information about items bought by customers, i.e., item id, customer id (referencing the customer that bought the item), item name, and quantity.

Natural Join in SQL

Problem Statement

Write a query to find all details of customers who bought something from the store.

Query

SELECT *
FROM Customers NATURAL JOIN Shopping_Details;
Quiz Pop
new tag
Quiz Type
SCQ
100
Success Rate:35%

Which SQL join type is based on the condition that columns with the same name and datatype exist in both tables to be joined?

When to Use What?

SQL is an essential skill for people looking for Data Engineering, Data Science, and Software Engineering Roles. Joins in SQL is one of the advanced SQL concepts and is often asked in interviews. These questions do not directly state what SQL join to use. Hence, we need to use a four-step analysis before we start forming our SQL query.

  1. Identification: Identify tables relating to the problem statement. We also need to identify relations between these tables, the order in which they are connected, and primary and foreign keys.

Example: Let’s say we have Tables A and B. Table A and Table B share a relation of Employee Details – Department Details. Table A has three fields – ID, Name, and DeptID. Table B has two fields – DeptID and DeptName. Table A has a primary key ID, and Table B’s primary key is DeptID. Table A and Table B are connected with the foreign key in Table A, i.e., Table B’s primary key, DeptID.

  1. Observe: Observe which join will be most suitable for the scenario. This means it should be able to retrieve all the required columns and have the least number of columns that need to be eliminated by the condition.

Example: If all values of Table A are required irrespective of the condition depending on Table C, we can use a left outer join on A and C.

  1. Deconstruction: Now that we have all requirements to form our query, firstly, we need to break it into sub-parts. This helps us form the query quicker and make our understanding of the database structure quicker. Here, we also form the conditions on the correctly identified relationships.

Example: You need to present data from Table A and Table B. But Table A’s foreign key is Table C’s primary key which is Table B’s foreign key. Hence breaking down the query into results from Table B and C (let’s say Temp) and then common results between its Temp and Table A will give us the correct solution.

  1. Compilation: Finally, we combine all the parts and form our final query. We can use query optimization techniques like heuristic optimization, resulting in quicker responses.

Let’s take a look at some interview questions based on SQL Joins:

  1. Write a query in SQL to find the names of departments where more than two employees are working. Sample Table: emp_dept
dpt_codedpt_name
57Sales
63Finance
47HR

Sample Table: emp_details

emp_idemp_fnameemp_lnameemp_dpt
1001JimHalpert 5757
1002KevinMalone63
1003DwightShrute57

How Scaler Transformed Careers in Different Fields

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data
Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more

Solution

Query

SELECT emp_dept.dpt_name
FROM emp_details 
INNER JOIN emp_dept
ON emp_dept = dpt_code
GROUP BY emp_department.dpt_name
HAVING COUNT(*) > 2;

Output:

dpt_name 
Sales   
Our Alumni Share Their Growth Stories
110% HIKE
Rohit Kamra
Rohit Kamra
Bangalore
BEFORE:
Specialist Data Scientist
Accenture
NOW:
Data Scientist
Brillio
“Learning DSML- easy or difficult? Well, I would say- it all comes down to how dedicated are your efforts. …”
View Profile
300% HIKE
Abirami S
Abirami S
Chennai
BEFORE:
Senior System Engineer
Infosys
NOW:
SDE 2
Zetwerk
“It took hard work, determination and support from some amazing folks at Scaler. Honestly, I thought they were …”
View Profile
200% HIKE
Rajmani Patel
Rajmani Patel
Bangalore
BEFORE:
Senior Member of Technical Staff
VMWare
NOW:
Senior Software Engineer
Microsoft
“Unwavering commitment lays the foundation for success, as each step remains anchored in resolute constancy. O…”
View Profile
250% HIKE
Krishna Chaitanya
Krishna Chaitanya
Hyderabad
BEFORE:
Data analyst
Innodatatics
NOW:
Software Engineer III
Walmart
“But I’m someone who has always been curious about learning more and keeping myself up to date and this made me…”
View Profile
500% HIKE
Subham Soni
Subham Soni
Burhanpur
BEFORE:
Software Engineer
Credit Suisse
NOW:
Backend Developer
Google
“Working at top product based company had been on my to-do list for quite some time. My time at Scaler has led …”
View Profile
200% HIKE
Rishi Prakash
Rishi Prakash
Gurgaon
BEFORE:
Senior Software Engineer
Accenture
NOW:
Software Engineer 2
Microsoft
“When I was in college, I thought that the only way one could only bag big companies was if they came from a pr…”
View Profile

Explanation

Since the question directly gives a single condition that we can directly execute without any loopholes, we directly link both tables using an INNER JOIN.

  1. Write a SQL statement to make a list in ascending order of the salesmen who work either for one or more customers or not yet join under any of the customers.

Sample Table: customers

cust_idcust_namecitysalesman_id
101Nick RimandoNew York648
102Brad DavisScranton271
103Graham ZusiAtlanta271
104Julian GreenNew York648

Sample Table: salesman

salesman_idsalesman_namecity
648Jim HalpertNew York
271Dwight ShruteScranton
017Pam BeeslyScranton

Solution:

Query:

SELECT a.cust_name,a.city,b.name AS "Salesman", b.city 
FROM customer a 
RIGHT OUTER JOIN salesman b 
ON b.salesman_id=a.salesman_id 
ORDER BY b.salesman_id;

Output:

cust_namecitySalesmancity
NULLNULLPam BeeslyScranton
Brad DavisScrantonDwight ShruteScranton
Graham ZusiAtlantaDwight ShruteScranton
Nick RimandoNew YorkJim HalpertNew York
Julian GreenNew YorkJim HalpertNew York

Turn Learning into Career Growth

1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary
1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary

Explanation:

This question states, “one or more customers or not yet join under any of the customers”. If it was “one or more customers” only, we could have directly executed the condition using an INNER JOIN. But, the “or not yet” creates the demand of a complex condition formation. To avoid this complexity, we can think of the resultant table by using a RIGHT OUTER JOIN where we will only have to form the condition of the “one or more” statement, and the “or not yet” results will be added as part of the RIGHT OUTER JOIN.

No comments:

Post a Comment

SQL JOINS (INNER, LEFT, RIGHT, and FULL Join)

  Overview A SQL Join statement combines data or rows from two or more tables based on a common field between them. This article gives a bri...