0% found this document useful (0 votes)
15 views

SQL Joins

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

SQL Joins

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

SQL Joins

Understanding SQL Joins is fundamental when it comes to database management and data
analysis.Here explores the four primary types of SQL Joins: Left, Right, Inner, and Full. Each
type uniquely combines rows from two or more tables based on a related column. By the end
ofHere, you'll have a solid understanding of how these joins work, when to use them, and how
they impact data manipulation and querying. Whether you're a beginner or an experienced SQL
user looking to refine your skills, this guide is valuable for exploring SQL Joins.
Table of Content
 What are Joins?
 Types of Joins
 INNER JOIN
 LEFT JOIN
 RIGHT JOIN
 FULL JOIN
What are SQL Joins?
SQL Joins are a fundamental concept in SQL (Structured Query Language), used to combine
rows from two or more tables based on a related column between them. The primary purpose of
joins is to query data from multiple tables to create a set of results that can be used for analysis or
reporting.
In simple terms, joins are the backbone of combining data from multiple tables in SQL. They act
like bridges, connecting related information scattered across different tables based on shared
fields. Essentially, joins let you retrieve data from more than one table in a single query,
presenting a unified view of your information.
There are 4 different types of joins that you can use. Refer below.
Types of Joins in SQL
Following are the four types of joins that you can use:
 INNER JOIN
 LEFT JOIN
 RIGHT JOIN
 FULL JOIN
Now, in the next section, we will understand how these joins work with the help of examples.
For that, we will take three tables: Patients Table (patient_id, patient_name, sex, age,
phone_number, state, country, haemoglobin), Medicines Table (medicine_id,
medicine_name, patient_id, doctor_id, price), Doctors Table (doctor_id, doctor_name,
phone_number, email_id patient_id).

Patients Table
Patient ID Patient Name Sex Age Phone Number State Country Haemoglobin
1 Sheela F 23 9876543210 Telangana India 82.321
2 Rehan M 21 7429061312 Karnataka India 83.231
3 Anay M 56 7382221121 Haryana India 94.567
4 Mahira F 42 9318281092 Gujarat India 78.567
5 Nishant M 12 8209109311 Maharashtra India 65.234

Medicines Table
MedicineID Medicine Name PatientID DoctorID Price
M01 MeftalForte 1 4 500
M02 Dolo 2 2 670
M03 Wikoryl 3 1 980
M04 PanD 1 4 420
M05 Uprise 4 3 930
M06 Boroline 6 3 470
M07 Volini 6 1 820
M08 Vicks 4 2 640
M09 Cetaphil Day Cream 3 3 230
M10 MeftalSpas 5 5 850

Doctors Table
Do Doct
Phone
cto or Patie
Numb EmailID
r Nam ntID
er
ID e
Dr.M 76263 manoj@g
01 2
anoj 13013 mail.com
Dr.D 86543 dipika@g
02 1
ipika 45678 mail.com
Dr.S 94567 sana@gma
03 4
ana 86543 il.com
Dr.P 84232 paras@gm
04 3
aras 31133 ail.com
Dr.
67890 suhail@gm
05 Suhai 4
56798 ail.com
l

Let's start with the Inner Join


Inner Join
This is the most common type of join. INNER JOIN returns rows when at least one match exists
in both tables. If there is no match, the rows are not returned.
Think of it like merging two tables perfectly based on identical keys.
Syntax of Inner Join
SELECT TableName1.ColumnName1,TableName2.ColumnName1,....
FROM TableName1
INNER JOIN TableName2
ON TableName1.MatchingColumnName = TableName2.MatchingColumnName;

Fetch the record of patient_id, patient_name, patient_age, medicine_id and medicine name
using medicine and patient table.

SELECT Patients.PatientID, Patients.PatientName, Patients.Age, Medicines.MedicineID,


Medicines.MedicineName
FROM Patients
INNER JOIN Medicines ON Patients.PatientID=Medicines.PatientID;
Output:
Patient ID Patient Name Age MedicineID MedicineName
1 Sheela 23 M01 MeftalForte
2 Rehan 21 M02 Dolo
3 Anay 56 M03 Wikoryl
1 Sheela 23 M04 PanD
4 Mahira 42 M05 Uprise
4 Mahira 42 M08 Vicks
3 Anay 56 M09 Cetaphil Day Cream
5 Nishant 12 M10 MeftalSpas
SQL LEFT JOIN
Left join returns all the records from the left table and only the records that match the condition
from the right table. Here, please note that for all the records which do not have matching values
in the right table, NULL values will be returned.

Syntax of SQL LEFT JOIN:


SELECT TableName1.ColumnName1,TableName2.ColumnName1,....
FROM TableName1
LEFT JOIN TableName2
ON TableName1.MatchingColumnName = TableName2.MatchingColumnName;

SELECT Patients.PatientName, Patients.Age, Medicines.MedicineID, Medicines.MedicineName


FROM Patients
LEFT JOIN Medicines ON Patients.PatientID=Medicines.PatientID;
Output:
Patient Name Age MedicineID MedicineName
Sheela 23 M01 MeftalForte
Rehan 21 M02 Dolo
Anay 56 M03 Wikoryl
Sheela 23 M04 PanD
Mahira 42 M05 Uprise
Mahira 42 M08 Vicks
Anay 56 M09 Cetaphil Day Cream
Nishant 12 M10 MeftalSpas
Right Join
Right, join returns all the records from the right table and only those that match the condition
from the left table. Here, please note that for all the records which do not have matching values
in the left table, NULL values will be returned.

Syntax of RIGHT JOIN:


SELECT TableName1.ColumnName1,TableName2.ColumnName1,....
FROM TableName1
RIGHT JOIN TableName2
ON TableName1.MatchingColumnName = TableName2.MatchingColumnName;

SELECT Patients.PatientName, Patients.Age, Medicines.MedicineID, Medicines.MedicineName


FROM Patients
RIGHT JOIN Medicines ON Patients.PatientID=Medicines.PatientID;
Output:

Patient Name Age MedicineID MedicineName


Sheela 23 M01 MeftalForte
Rehan 21 M02 Dolo
Anay 56 M03 Wikoryl
Sheela 23 M04 PanD
Mahira 42 M05 Uprise
NULL NULL M06 Boroline
NULL NULL M07 Volini
Mahira 42 M08 Vicks
Anay 56 M09 Cetaphil Day Cream
Nishant 12 M10 MeftalSpas
SQL Full Join
Full join returns the records that either have matches from one of the tables.

Syntax of FULL JOIN:

SELECT TableName1.ColumnName1,TableName2.ColumnName1,....
FROM TableName1
FULL JOIN TableName2
ON TableName1.MatchingColumnName = TableName2.MatchingColumnName;

SELECT Patients.PatientID, Patients.PatientName, Medicines.MedicineID,


Medicines.MedicineName
FROM Patients
FULL JOIN Medicines ON Patients.PatientID=Medicines.PatientID;
Output:

Patient ID Patient Name MedicineID MedicineName


1 Sheela M01 MeftalForte
2 Rehan M02 Dolo
3 Anay M03 Wikoryl
1 Sheela M04 PanD
4 Mahira M05 Uprise
6 NULL M06 Boroline
6 NULL M07 Volini
4 Mahira M08 Vicks
3 Anay M09 Cetaphil Day Cream
5 Nishant M10 MeftalSpas
FAQs on What is SQL Joins: Left, Right, Inner, and Full Join
What is a Full/Outer Join and when is it used?
A Full Join, also known as a Full Outer Join, retrieves all records from both tables, including
both matching and non-matching records. It's used when you need a comprehensive combination
of data from both tables without losing any information.
How does a Right Join work in SQL?
A Right Join, or Right Outer Join, returns every record from the right table and the matching
records from the left table. Non-matching records in the left table are represented as NULL in the
result set.
What is a Left Join and how is it different from an Inner Join?
A Left Join returns every row from the left table and the matched records from the right table.
Unlike an Inner Join, which only returns matching rows from both tables, a Left Join includes all
records from the left table, even if there are no matching rows in the right table.
Can you provide an example of a Full Outer Join?
Sure, consider two tables, 'movies' and 'directors'. A Full Outer Join between these tables can be
performed using FULL OUTER JOIN directors ON directors.id = movies.director_id. This will
return all movies with their directors, including movies without directors and directors without
movies.
What are some tips for optimizing JOIN performance in SQL?
To optimize JOIN performance, consider using appropriate join types for your needs, ensure
indexing on key columns, and consider the size of the tables being joined. For large data sets,
using hash joins can be efficient.
How do I use a Right Outer Join in SQL?
A Right Outer Join adds all rows from the right-hand table to the output and only matching rows
from the left-hand table. It is useful when you want all records from the right-hand table and only
the matching ones from the left-hand table.
What is the difference between Left and Right Joins?
The main difference lies in which table's records are included completely. A Left Join includes
all records from the left table, while a Right Join includes all records from the right table. The
non-matching rows from the opposite table are represented as NULL.
When should I use an INNER JOIN?
Use an INNER JOIN when you need to retrieve rows that have matching values in both tables
involved in the join.
Can you explain the basic concept of SQL Joins?
SQL Joins are used to combine rows from two or more tables based on a related column between
them. They are essential for querying data from multiple tables and understanding the
relationships between different sets of data.

UNION and UNION ALL


UNION and UNION ALL are set operators in SQL used to concatenate the results of two or
more SELECT statements. Still, they differ from each other in how they handle duplicate
records. The UNION command combines two or more SELECT statements but removes
duplicates from the final result set, whereas the UNION ALL statement does not remove the
duplicate from the result. UNION ALL simply concatenates all records, including duplicates
from the SELECT statement.Here will explore the difference between UNION and UNION
ALL.
UNION and UNION ALL in SQL are set operators that combine the results of
two SELECT queries. Both share standard features, with one significant difference: UNION only
returns a unique record, while UNION ALL returns all the records (including duplicates).Here
will explore the difference between UNION and UNION ALL.

UNION vs. UNION ALL


Parameter UNION UNION ALL
Combines the result from the multiple tables Combines the result from the multiple
Definition and returns the distinct records into a single tables and returns all the records into a
result set. single result set.
Removal of It has a default feature to eliminate duplicate It can’t eliminate the duplicate rows from
duplicates rows from the table. the table.
Slow performance as it removes duplicate
Performance Fast performance as compared to UNION.
rows from the output.
SELECT column_names SELECT column_names
FROM table_1 FROM table_1
WHERE conditions WHERE conditions
Syntax UNION UNION ALL
SELECT column_names SELECT column_names
FROM table_2 FROM table_2
WHERE conditions WHERE conditions
What is a UNION?
UNION in SQL combines data from two SELECT queries' results into a single distinct result set.
The result set to produce from UNION doesn’t contain any duplicate value.

Syntax

SELECT column_names

FROM table_1

WHERE conditions

UNION

SELECT column_names

FROM table_2
WHERE conditions;

What is UNION ALL?


UNION ALL is an extension of UNION in SQL. As the result set of UNION of two tables
doesn’t contain all the records from both tables, UNION ALL comes into the picture and returns
all the records from both tables (including duplicate rows also).
Syntax

SELECT column_names
FROM table_1
WHERE conditions

UNION ALL

SELECT column_names
FROM table_2
WHERE conditions;
Rules
 The SELECT statements must have the same number of columns and data types.
 Columns in both the SELECT statements must be in the same order.
 The names of the columns can be different, but the final result set will show the column name
of the first selected query.
Let’s understand the difference between UNION and UNION ALL by an example.
Example
Let us have two tables of employee names and manager names. Combine both the tables using
UNION and UNION ALL.
Employee
Employee_id Name
1 Ram
2 Shyam
3 Joya
4 Vidit
Manager
Employee_id Name
1 Ram
4 Vidit

UNION
SELECT Employee_id, name
FROM Employee
UNION
SELECT *
FROM Manager;
output

Employee_id Name
1 Ram
2 Shyam
3 Joya
4 Vidit

UNION ALL
SELECT Employee_id, name
FROM Employee
UNION
SELECT *
FROM Manager;
output
Employee_id Name
1 Ram
2 Shyam
3 Joya
4 Vidit
1 Ram
4 Vidit

Key differences
 Both UNION and UNION ALL combine the result of two or more tables.
 The result set of UNION does not contain duplicate rows, while the result set of UNION ALL
returns all the rows from both tables.
 The execution time of UNION ALL is less than the execution time of UNION as it does not
remove the duplicate rows.
GROUP BY
 The GROUP BY clause in sql is used to group the rows that have identical values by one
or more columns. InHere, we will briefly discuss how GROUP BY clause is used in SQL
with aggregation function, having clause, order by clause and with the case statement.

What is GROUP BY in SQL?


GROUP BY in SQL is used to group all the rows that have the same (or identical) value by one
or more columns.
 It is used in conjunction with the aggregate function
 It follows WHERE clause in SELECT statement and precedes the ORDER BY clause.
The below image shows how the GROUP BY clause works in SQL.
The above table (left table) contains the record of Employees (Employee ID, Name, and
Department), and when we apply the GROUP BY clause on the Department column, it returns
the result set that includes the unique value in the department column (Sales, Marketing, and
Education).
Syntax

SELECT column_names

FROM table_name

WHERE conditions

GROUP BY column_names
ORDER BY column_names;

Let’s have a Student table that contains the StudentID, Name, Percentage, and corresponding
Grade.
Student ID Name Percentage Grade Remark
1001 Ajay 87 A Excellent
1002 Babloo 81 A Excellent
1003 Chhavi 79 B Good
1004 Dheeraj 93 O Excellent
1005 Evina 95 O Excellent
1006 Fredy 80.7 A Excellent
1007 Garima 63 C Poor
1008 Hans 49 F Fail
1009 Ivanka 88 A Excellent
1010 Jai 74 B Good
1011 Kundan 88 A Excellent
1012 Himanshi 37 F Fail
1013 Atul 67 B Good
1014 Jaya 48 F Fail
1015 Aquib 75 B Good
COUNT with GROUP BY
Example: Use the GROUP BY clause to count the number of students by the grade.
Query

SELECT Grade, COUNT (StudentID) AS Number of Students

FROM Student
GROUP BY Grade;
Output
Grade Number of Students
A 5
B 4
C 1
F 3
O 2

GROUP BY with HAVING


Example: Find the grade in which the number of students is greater than or equal to 3.
Query

SELECT Grade, COUNT (StudentID) AS Number of Students

FROM Student

GROUP BY Grade
HAVING Number of Students >= 3;
Output
Grade Number of Students
A 5
B 4
F 3

GROUP BY with ORDER BY


Example: Use the ORDER BY clause in the above example to arrange the number of
students in each grade in descending order.
Query
SELECT Grade, COUNT (StudentID) AS Number of Students

FROM Student

GROUP BY Grade
ORDER BY Number of Students DESC;
Output
Grade Number of Students
A 5
B 4
F 3
O 2
C 1

You might also like