SlideShare ist ein Scribd-Unternehmen logo
1 von 53
Downloaden Sie, um offline zu lesen
https://www.facebook.com/Oxus20
oxus20@gmail.com
Everything
about
Database JOINS
and
Relationships
» Definitions
» JOINS
» INNER JOIN
» LEFT JOIN
» RIGHT JOIN
» FULL JOIN
» CROSS JOIN
» SELF JOIN
Abdul Rahman Sherzad
Database Definition
» A database is a set of related data that has a regular
structure and that is organized in such a way that a
computer can easily find the desired information.
» A database is a collection of information that is
organized so that it can easily be accessed,
managed, and updated.
» A database is a collection logically related data.
2
https://www.facebook.com/Oxus20
DBMS Definition
» A DBMS (Database Management System) is a set of
software programs or a tools which helps the user to
perform all related operations i.e. to store, access,
and process data or facts into useful information.
» A DBMS guarantees security, integrity, and privacy
by providing a centralized control of database.
3
https://www.facebook.com/Oxus20
DBMS Examples
» Free and Open Source
˃ MySQL
˃ PostgreSQL
˃ SQLite
˃ Firebird
» Proprietary and Closed Source
˃ Microsoft SQL Server (MS SQL)
˃ Oracle
˃ Microsoft Access
˃ DB2
4
https://www.facebook.com/Oxus20
Application Program Definition
» An application program (sometimes shortened to
application) accesses the database by sending
queries or requests to the DBMS via a GUI
(Graphical User Interface).
5
https://www.facebook.com/Oxus20
Database System Definition
» The database, the DBMS software, and the
application program together are called a database
system.
˃ Computerized Library Systems
˃ ATM (Automated Teller Machines)
˃ Flight Reservation Systems
˃ Computerized Human Resource Systems
6
https://www.facebook.com/Oxus20
Summary at a Glance
7
https://www.facebook.com/Oxus20
GUI / Web Interface
MySQL, Oracle, MS SQL
Facebook, YouTube, Library System
• Data related to the videos
• Data related to the users
• Data related to the library
Relationship Definition
» When creating a database, common sense dictates that
we use separate tables for different types of entities to
reduce and overcome redundancy.
» We need to establish relationships between these
separated tables to provide useful information.
» A relationship exists between two database tables when
one table has a foreign key that references the primary
key of another table.
8
https://www.facebook.com/Oxus20
Types of Relationships
» One to One Relationships
˃ Both tables can have only one record on either side of the relationship.
» One to Many / Many to One Relationships
˃ The primary key table contains only one record that relates to none, one, or
many records in the related table.
» Many to Many Relationships
˃ Each record in both tables can relate to any number of records (or no records) in
the other table.
» Self Referencing Relationships
˃ This is used when a table needs to have a relationship with itself.
9
https://www.facebook.com/Oxus20
JOINS
» When selecting data from multiple tables with
relationships, we will be using the JOIN query.
» INNER JOIN
» Natural JOIN
» Left (Outer) JOIN
» Right (Outer) JOIN
» Cross JOIN
10
https://www.facebook.com/Oxus20
JOIN in Live Examples
Students Subjects
code first_name last_name
20120 Abdul Rahman Sherzad
20121 Cristina Silva
20122 Bob Logan
20123 Ana Nava
20124 Sekila Manzikalla
id subject_name
1 Web Development
2 Web Design
3 Concept of Programming
4 Fundamentals of Database Systems
5 Graphic Design
11
https://www.facebook.com/Oxus20
Visualizing the Relationships
12
https://www.facebook.com/Oxus20
The database includes a "many-to-many" relationship; each student can take
many subjects, while each subject can of course chosen by many students.
To represent this, there is students table, subjects table, and enrollments table
to show the combinations of the students enrolled in subjects and the subjects
which taken by the students.
Database Schema
DROP SCHEMA IF EXISTS joins;
CREATE SCHEMA IF NOT EXISTS joins
DEFAULT CHARACTER SET utf8 COLLATE
utf8_general_ci;
USE joins;
13
https://www.facebook.com/Oxus20
Table Students Schema
DROP TABLE IF EXISTS students;
CREATE TABLE IF NOT EXISTS students (
code INT NOT NULL,
first_name VARCHAR(45) NOT NULL,
last_name VARCHAR(45) NOT NULL,
PRIMARY KEY (code)
) ENGINE = InnoDB;
14
https://www.facebook.com/Oxus20
Table Students Data
INSERT INTO students
(code, first_name, last_name)
VALUES (20120, 'Abdul Rahman', 'Sherzad'),
(20121, 'Cristina', 'Silva'),
(20122, 'Bob', 'Logan'),
(20123, 'Ana', 'Nava'),
(20124, 'Sekila', 'Manzikalla');
15
https://www.facebook.com/Oxus20
Table Subjects Schema
DROP TABLE IF EXISTS subjects;
CREATE TABLE IF NOT EXISTS subjects (
id INT NOT NULL AUTO_INCREMENT,
subject_name VARCHAR(45) NULL,
PRIMARY KEY (id),
UNIQUE INDEX (subject_name)
) ENGINE = InnoDB;
16
https://www.facebook.com/Oxus20
Table Subjects Data
INSERT INTO subjects (id, subject_name)
VALUES (1, 'Web Development'),
(2, 'Web Design'),
(3, 'Concept of Programming'),
(4, 'Fundamentals of Database Systems'),
(5, 'Graphic Design');
17
https://www.facebook.com/Oxus20
Table Enrollments Schema
DROP TABLE IF EXISTS enrollments;
CREATE TABLE IF NOT EXISTS enrollments (
student_code INT NOT NULL,
subject_id INT NOT NULL,
PRIMARY KEY (student_code, subject_id),
FOREIGN KEY (student_code) REFERENCES students (code)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (subject_id) REFERENCES subjects (id)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE = InnoDB;
18
https://www.facebook.com/Oxus20
Table Enrollments Data
INSERT INTO enrollments (student_code, subject_id)
VALUES (20120, 1),
(20120, 2),
(20121, 2),
(20121, 3),
(20122, 3),
(20123, 3),
(20122, 4),
(20123, 4);
19
https://www.facebook.com/Oxus20
INNER JOIN (JOIN)
» The most frequently used clause is INNER JOIN
or just JOIN.
» Fetching Matching Records From All the Tables
» Let's say we want to see which students taken
which subjects.
20
https://www.facebook.com/Oxus20
INNER JOIN (JOIN)
SELECT code, first_name, last_name,
subject_name
FROM students INNER JOIN enrollments
ON students.code = enrollments.student_code
INNER JOIN subjects
ON enrollments.subject_id = subjects.id;
21
https://www.facebook.com/Oxus20
Alternative I - INNER JOIN (JOIN)
SELECT code, first_name, last_name,
subject_name
FROM students INNER JOIN enrollments
INNER JOIN subjects
ON students.code = enrollments.student_code
AND enrollments.subject_id = subjects.id;
22
https://www.facebook.com/Oxus20
Alternative II – Just JOIN
SELECT code, first_name, last_name,
subject_name
FROM students JOIN enrollments
ON students.code = enrollments.student_code
JOIN subjects
ON enrollments.subject_id = subjects.id;
23
https://www.facebook.com/Oxus20
Alternative III – Where Clause
SELECT code, first_name, last_name,
subject_name
FROM students, subjects, enrollments
WHERE students.code =
enrollments.student_code
AND enrollments.subject_id = subjects.id;
24
https://www.facebook.com/Oxus20
OUTPUT
25
https://www.facebook.com/Oxus20
Alternative IV - Alias
SELECT code AS 'Student Code',
first_name AS 'First Name',
last_name AS 'Last Name',
subject_name AS 'Subject'
FROM students AS stu INNER JOIN enrollments AS en
ON stu.code = en.student_code
INNER JOIN subjects AS sub
ON en.subject_id = sub.id;
26
https://www.facebook.com/Oxus20
Alternative V – Alias Refined
SELECT code 'Student Code',
first_name 'First Name',
last_name 'Last Name',
subject_name 'Subject'
FROM students stu INNER JOIN enrollments en
ON stu.code = en.student_code
INNER JOIN subjects sub
ON en.subject_id = sub.id;
27
https://www.facebook.com/Oxus20
OUTPUT
28
https://www.facebook.com/Oxus20
RIGHT JOIN (RIGHT OUTER JOIN)
» What if we require a list of all students and their
subjects even if they are not enrolled on one?
» A RIGHT JOIN produces a set of records which
matches every entry in the right table (students)
regardless of any matching entry in the left table
(subjects) and / or (enrollments).
29
https://www.facebook.com/Oxus20
RIGHT JOIN (RIGHT OTHER JOIN)
SELECT code, first_name, last_name,
subject_name
FROM subjects INNER JOIN enrollments
ON subjects.id = enrollments.subject_id
RIGHT JOIN students
ON students.code = enrollments.student_code;
30
https://www.facebook.com/Oxus20
OUTPUT
31
https://www.facebook.com/Oxus20
LEFT JOIN (LEFT OUTER JOIN)
» Let's change the scenario, perhaps we require a list of
all subjects and students even if the subjects are not
chosen by any students?
» A LEFT JOIN produces a set of records which matches
every entry in the left table (subjects) regardless of any
matching entry in the right table (students) and / or
enrollments.
32
https://www.facebook.com/Oxus20
LEFT JOIN (LEFT OUTER JOIN)
SELECT subject_name, code, first_name,
last_name
FROM subjects LEFT JOIN
( students INNER JOIN enrollments
ON students.code = enrollments.student_code )
ON subjects.id = enrollments.subject_id;
33
https://www.facebook.com/Oxus20
Alternative – RIGHT JOIN
SELECT subject_name, code, first_name,
last_name
FROM students INNER JOIN enrollments
ON students.code = enrollments.student_code
RIGHT JOIN subjects
ON subjects.id = enrollments.subject_id
34
https://www.facebook.com/Oxus20
OUTPUT
35
https://www.facebook.com/Oxus20
LEFT JOIN vs. RIGHT JOIN
» LEFT (OUTER) JOIN and RIGHT (OUTER) JOIN
works exactly the same.
» ONLY the order of the tables are reversed!
36
https://www.facebook.com/Oxus20
FULL JOIN (or FULL OUTER JOIN)
» The OUTER JOIN which returns all records in both
tables regardless of any match. Where no match exists,
the missing side will contain NULL.
» OUTER JOIN is less useful than INNER, LEFT or RIGHT
joins and it's not implemented in MySQL.
» However, you can work around this restriction using the
UNION of a LEFT and RIGHT JOIN.
37
https://www.facebook.com/Oxus20
FULL JOIN (or FULL OUTER JOIN)
SELECT code, first_name, last_name, subject_name
FROM subjects LEFT JOIN
( students INNER JOIN enrollments
ON students.code = enrollments.student_code )
ON subjects.id = enrollments.subject_id
UNION
SELECT code, first_name, last_name, subject_name
FROM subjects INNER JOIN enrollments
ON subjects.id = enrollments.subject_id
RIGHT JOIN students ON students.code = enrollments.student_code;
38
https://www.facebook.com/Oxus20
OUTPUT
39
https://www.facebook.com/Oxus20
Cross Join
» This is the default type of JOIN query when no
condition is specified.
» The result is a so called "Cartesian Product" of the
tables.
» It means that each row from the first table is
matched with each row of the second table.
» Since each table had 5 rows, we ended up getting a
result of 25 rows.
40
https://www.facebook.com/Oxus20
Cross Join
SELECT code, first_name, last_name,
subject_name
FROM
students
CROSS JOIN
subjects;
41
https://www.facebook.com/Oxus20
Cross Join - Alternative
SELECT code, first_name, last_name,
subject_name
FROM Students, subjects;
42
https://www.facebook.com/Oxus20
OUTPUT
43
https://www.facebook.com/Oxus20
SELF JOIN
» The SELF JOIN is used to join a table to itself as if
the table were two tables; temporarily renaming at
least one table in the SQL statement.
» You can view SELF JOIN as two identical tables. But
in normalization you cannot create two copies of the
table so you just simulate having two tables with
SELF JOIN.
44
https://www.facebook.com/Oxus20
SELF JOIN
» Let's say you have a
table named "users"
with following
structure:
˃ User ID
˃ User Name
˃ User's Manager's ID
UserID UserName ManagerID
1 Abdul Rahman Sherzad 0
2 Ana Nava 1
3 Bob Logan 2
4 Cristina Silva 3
https://www.facebook.com/Oxus20
45
Table Users Schema
CREATE TABLE IF NOT EXISTS users (
UserID int(11) NOT NULL AUTO_INCREMENT,
UserName varchar(50) NOT NULL,
ManagerID int(11) NOT NULL,
PRIMARY KEY (UserID)
) ENGINE=InnoDB;
46
https://www.facebook.com/Oxus20
Table Users Data
INSERT INTO users
(UserID, UserName, ManagerID)
VALUES (1, 'Abdul Rahman Sherzad', 0),
(2, 'Ana Nava', 1),
(3, 'Bob Logan', 2),
(4, 'Cristina Silva', 3);
47
https://www.facebook.com/Oxus20
SLEF JOIN - Example
SELECT u.UserID, u.UserName AS 'User
Name', m.UserName AS 'Manager Name'
FROM users u INNER JOIN users m
ON u.ManagerID = m.UserID;
48
https://www.facebook.com/Oxus20
OUTPUT
49
https://www.facebook.com/Oxus20
SELF JOIN with LEFT JOIN
SELECT u.UserID, u.UserName AS 'User
Name', m.UserName AS 'Manager Name'
FROM users u LEFT JOIN users m
ON u.ManagerID = m.UserID
ORDER BY u.UserID ASC;
50
https://www.facebook.com/Oxus20
OUTPUT
51
https://www.facebook.com/Oxus20
Conclusion
» Thank you for reading this presentation. I hope
you that it gives you a better understanding of
JOINS and helps you write more efficient SQL
queries as well as enjoyed it!
» Please leave your comments and questions, and
have a great day 
52
https://www.facebook.com/Oxus20
END
https://www.facebook.com/Oxus20
53

Weitere ähnliche Inhalte

Was ist angesagt?

Database Management Systems 4 - Normalization
Database Management Systems 4 - NormalizationDatabase Management Systems 4 - Normalization
Database Management Systems 4 - Normalization
Nickkisha Farrell
 

Was ist angesagt? (20)

Join
JoinJoin
Join
 
basic structure of SQL FINAL.pptx
basic structure of SQL FINAL.pptxbasic structure of SQL FINAL.pptx
basic structure of SQL FINAL.pptx
 
Sql commands
Sql commandsSql commands
Sql commands
 
The Relational Model
The Relational ModelThe Relational Model
The Relational Model
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
Aggregate functions
Aggregate functionsAggregate functions
Aggregate functions
 
Subqueries
SubqueriesSubqueries
Subqueries
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
 
Trigger
TriggerTrigger
Trigger
 
Data Dictionary
Data DictionaryData Dictionary
Data Dictionary
 
Sql joins inner join self join outer joins
Sql joins inner join self join outer joinsSql joins inner join self join outer joins
Sql joins inner join self join outer joins
 
Sql joins
Sql joinsSql joins
Sql joins
 
Database Management Systems 4 - Normalization
Database Management Systems 4 - NormalizationDatabase Management Systems 4 - Normalization
Database Management Systems 4 - Normalization
 
Sub query_SQL
Sub query_SQLSub query_SQL
Sub query_SQL
 
Joins And Its Types
Joins And Its TypesJoins And Its Types
Joins And Its Types
 
SQL Constraints
SQL ConstraintsSQL Constraints
SQL Constraints
 
Types Of Keys in DBMS
Types Of Keys in DBMSTypes Of Keys in DBMS
Types Of Keys in DBMS
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
set operators.pptx
set operators.pptxset operators.pptx
set operators.pptx
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 

Andere mochten auch

Database Introduction - Join Query
Database Introduction - Join QueryDatabase Introduction - Join Query
Database Introduction - Join Query
Dudy Ali
 
Total Relationship Marketing
Total Relationship MarketingTotal Relationship Marketing
Total Relationship Marketing
Steve Raybould
 

Andere mochten auch (20)

Joins in databases
Joins in databases Joins in databases
Joins in databases
 
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Server
 
Dbms slides
Dbms slidesDbms slides
Dbms slides
 
sql statements & joins
sql statements & joinssql statements & joins
sql statements & joins
 
Database Join
Database JoinDatabase Join
Database Join
 
Sub join a query optimization algorithm for flash-based database
Sub join a query optimization algorithm for flash-based databaseSub join a query optimization algorithm for flash-based database
Sub join a query optimization algorithm for flash-based database
 
BCA GGSIPU NEW SYALLBUS
BCA GGSIPU NEW SYALLBUSBCA GGSIPU NEW SYALLBUS
BCA GGSIPU NEW SYALLBUS
 
Database - SQL Joins
Database - SQL JoinsDatabase - SQL Joins
Database - SQL Joins
 
Database Introduction - Join Query
Database Introduction - Join QueryDatabase Introduction - Join Query
Database Introduction - Join Query
 
Scrum Model
Scrum ModelScrum Model
Scrum Model
 
SQL Join Basic
SQL Join BasicSQL Join Basic
SQL Join Basic
 
Database - Normalization
Database - NormalizationDatabase - Normalization
Database - Normalization
 
Total Relationship Marketing
Total Relationship MarketingTotal Relationship Marketing
Total Relationship Marketing
 
SQL
SQLSQL
SQL
 
Payilagam oracle sql & plsql training syllabus
Payilagam oracle sql & plsql training syllabusPayilagam oracle sql & plsql training syllabus
Payilagam oracle sql & plsql training syllabus
 
Colorectal Cancer-A Rising Concern
Colorectal Cancer-A Rising ConcernColorectal Cancer-A Rising Concern
Colorectal Cancer-A Rising Concern
 
Oracle Baisc Tutorial
Oracle Baisc TutorialOracle Baisc Tutorial
Oracle Baisc Tutorial
 
Database Normalization
Database NormalizationDatabase Normalization
Database Normalization
 
En ch23
En ch23En ch23
En ch23
 
Normalization in Database
Normalization in DatabaseNormalization in Database
Normalization in Database
 

Ähnlich wie Everything about Database JOINS and Relationships

ACCT202 SUMMER 2018 ONLINE SPECIAL ASSIGNMENTFINANCIAL RATIOS FO.docx
ACCT202 SUMMER 2018 ONLINE SPECIAL ASSIGNMENTFINANCIAL RATIOS FO.docxACCT202 SUMMER 2018 ONLINE SPECIAL ASSIGNMENTFINANCIAL RATIOS FO.docx
ACCT202 SUMMER 2018 ONLINE SPECIAL ASSIGNMENTFINANCIAL RATIOS FO.docx
nettletondevon
 
Running Head STUDENT RECORD KEEPING SYSTEM DATABASE PROJECT 1.docx
Running Head STUDENT RECORD KEEPING SYSTEM DATABASE PROJECT  1.docxRunning Head STUDENT RECORD KEEPING SYSTEM DATABASE PROJECT  1.docx
Running Head STUDENT RECORD KEEPING SYSTEM DATABASE PROJECT 1.docx
jeanettehully
 
Using Multiple Tools to Create Dashboards
Using Multiple Tools to Create DashboardsUsing Multiple Tools to Create Dashboards
Using Multiple Tools to Create Dashboards
Colby Stoever
 
20080930
2008093020080930
20080930
xoanon
 

Ähnlich wie Everything about Database JOINS and Relationships (20)

Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and Relationships
 
Keys.ppt
Keys.pptKeys.ppt
Keys.ppt
 
ACCT202 SUMMER 2018 ONLINE SPECIAL ASSIGNMENTFINANCIAL RATIOS FO.docx
ACCT202 SUMMER 2018 ONLINE SPECIAL ASSIGNMENTFINANCIAL RATIOS FO.docxACCT202 SUMMER 2018 ONLINE SPECIAL ASSIGNMENTFINANCIAL RATIOS FO.docx
ACCT202 SUMMER 2018 ONLINE SPECIAL ASSIGNMENTFINANCIAL RATIOS FO.docx
 
Everything about Object Oriented Programming
Everything about Object Oriented ProgrammingEverything about Object Oriented Programming
Everything about Object Oriented Programming
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World Examples
 
Unit03 dbms
Unit03 dbmsUnit03 dbms
Unit03 dbms
 
Bill howe 2_databases
Bill howe 2_databasesBill howe 2_databases
Bill howe 2_databases
 
Scholarly Identity Tools
Scholarly Identity Tools Scholarly Identity Tools
Scholarly Identity Tools
 
Running Head STUDENT RECORD KEEPING SYSTEM DATABASE PROJECT 1.docx
Running Head STUDENT RECORD KEEPING SYSTEM DATABASE PROJECT  1.docxRunning Head STUDENT RECORD KEEPING SYSTEM DATABASE PROJECT  1.docx
Running Head STUDENT RECORD KEEPING SYSTEM DATABASE PROJECT 1.docx
 
Database Concepts and Components
Database Concepts and ComponentsDatabase Concepts and Components
Database Concepts and Components
 
Using Multiple Tools to Create Dashboards
Using Multiple Tools to Create DashboardsUsing Multiple Tools to Create Dashboards
Using Multiple Tools to Create Dashboards
 
MICRO PROJECT 22319 DMS
MICRO PROJECT 22319 DMSMICRO PROJECT 22319 DMS
MICRO PROJECT 22319 DMS
 
CIS 111 STUDY Education Your Life--cis111study
CIS 111 STUDY Education Your Life--cis111studyCIS 111 STUDY Education Your Life--cis111study
CIS 111 STUDY Education Your Life--cis111study
 
CIS 111 STUDY Inspiring Innovation--cis111study.com
CIS 111 STUDY Inspiring Innovation--cis111study.comCIS 111 STUDY Inspiring Innovation--cis111study.com
CIS 111 STUDY Inspiring Innovation--cis111study.com
 
CIS 111 STUDY Education Planning--cis111study.com
CIS 111 STUDY Education Planning--cis111study.comCIS 111 STUDY Education Planning--cis111study.com
CIS 111 STUDY Education Planning--cis111study.com
 
MS Access and Database Fundamentals
MS Access and Database FundamentalsMS Access and Database Fundamentals
MS Access and Database Fundamentals
 
Student Administration System
Student Administration SystemStudent Administration System
Student Administration System
 
20080930
2008093020080930
20080930
 
CIS 111 STUDY Knowledge Specialist--cis111study.com
CIS 111 STUDY Knowledge Specialist--cis111study.comCIS 111 STUDY Knowledge Specialist--cis111study.com
CIS 111 STUDY Knowledge Specialist--cis111study.com
 
Hartman Summit 09
Hartman Summit 09Hartman Summit 09
Hartman Summit 09
 

Mehr von Abdul Rahman Sherzad

Web Application Security and Awareness
Web Application Security and AwarenessWeb Application Security and Awareness
Web Application Security and Awareness
Abdul Rahman Sherzad
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event Schedulers
Abdul Rahman Sherzad
 

Mehr von Abdul Rahman Sherzad (20)

Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in AfghanistanData is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
 
PHP Unicode Input Validation Snippets
PHP Unicode Input Validation SnippetsPHP Unicode Input Validation Snippets
PHP Unicode Input Validation Snippets
 
Iterations and Recursions
Iterations and RecursionsIterations and Recursions
Iterations and Recursions
 
Sorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQLSorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQL
 
PHP Variable variables Examples
PHP Variable variables ExamplesPHP Variable variables Examples
PHP Variable variables Examples
 
Cross Join Example and Applications
Cross Join Example and ApplicationsCross Join Example and Applications
Cross Join Example and Applications
 
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
 
Web Application Security and Awareness
Web Application Security and AwarenessWeb Application Security and Awareness
Web Application Security and Awareness
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event Schedulers
 
Mobile Score Notification System
Mobile Score Notification SystemMobile Score Notification System
Mobile Score Notification System
 
Herat Innovation Lab 2015
Herat Innovation Lab 2015Herat Innovation Lab 2015
Herat Innovation Lab 2015
 
Evaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan UniversitiesEvaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan Universities
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail Explanation
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and Answers
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by Step
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and Technologies
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 
Java Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesJava Unicode with Live GUI Examples
Java Unicode with Live GUI Examples
 

Kürzlich hochgeladen

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 

Kürzlich hochgeladen (20)

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 

Everything about Database JOINS and Relationships

  • 1. https://www.facebook.com/Oxus20 oxus20@gmail.com Everything about Database JOINS and Relationships » Definitions » JOINS » INNER JOIN » LEFT JOIN » RIGHT JOIN » FULL JOIN » CROSS JOIN » SELF JOIN Abdul Rahman Sherzad
  • 2. Database Definition » A database is a set of related data that has a regular structure and that is organized in such a way that a computer can easily find the desired information. » A database is a collection of information that is organized so that it can easily be accessed, managed, and updated. » A database is a collection logically related data. 2 https://www.facebook.com/Oxus20
  • 3. DBMS Definition » A DBMS (Database Management System) is a set of software programs or a tools which helps the user to perform all related operations i.e. to store, access, and process data or facts into useful information. » A DBMS guarantees security, integrity, and privacy by providing a centralized control of database. 3 https://www.facebook.com/Oxus20
  • 4. DBMS Examples » Free and Open Source ˃ MySQL ˃ PostgreSQL ˃ SQLite ˃ Firebird » Proprietary and Closed Source ˃ Microsoft SQL Server (MS SQL) ˃ Oracle ˃ Microsoft Access ˃ DB2 4 https://www.facebook.com/Oxus20
  • 5. Application Program Definition » An application program (sometimes shortened to application) accesses the database by sending queries or requests to the DBMS via a GUI (Graphical User Interface). 5 https://www.facebook.com/Oxus20
  • 6. Database System Definition » The database, the DBMS software, and the application program together are called a database system. ˃ Computerized Library Systems ˃ ATM (Automated Teller Machines) ˃ Flight Reservation Systems ˃ Computerized Human Resource Systems 6 https://www.facebook.com/Oxus20
  • 7. Summary at a Glance 7 https://www.facebook.com/Oxus20 GUI / Web Interface MySQL, Oracle, MS SQL Facebook, YouTube, Library System • Data related to the videos • Data related to the users • Data related to the library
  • 8. Relationship Definition » When creating a database, common sense dictates that we use separate tables for different types of entities to reduce and overcome redundancy. » We need to establish relationships between these separated tables to provide useful information. » A relationship exists between two database tables when one table has a foreign key that references the primary key of another table. 8 https://www.facebook.com/Oxus20
  • 9. Types of Relationships » One to One Relationships ˃ Both tables can have only one record on either side of the relationship. » One to Many / Many to One Relationships ˃ The primary key table contains only one record that relates to none, one, or many records in the related table. » Many to Many Relationships ˃ Each record in both tables can relate to any number of records (or no records) in the other table. » Self Referencing Relationships ˃ This is used when a table needs to have a relationship with itself. 9 https://www.facebook.com/Oxus20
  • 10. JOINS » When selecting data from multiple tables with relationships, we will be using the JOIN query. » INNER JOIN » Natural JOIN » Left (Outer) JOIN » Right (Outer) JOIN » Cross JOIN 10 https://www.facebook.com/Oxus20
  • 11. JOIN in Live Examples Students Subjects code first_name last_name 20120 Abdul Rahman Sherzad 20121 Cristina Silva 20122 Bob Logan 20123 Ana Nava 20124 Sekila Manzikalla id subject_name 1 Web Development 2 Web Design 3 Concept of Programming 4 Fundamentals of Database Systems 5 Graphic Design 11 https://www.facebook.com/Oxus20
  • 12. Visualizing the Relationships 12 https://www.facebook.com/Oxus20 The database includes a "many-to-many" relationship; each student can take many subjects, while each subject can of course chosen by many students. To represent this, there is students table, subjects table, and enrollments table to show the combinations of the students enrolled in subjects and the subjects which taken by the students.
  • 13. Database Schema DROP SCHEMA IF EXISTS joins; CREATE SCHEMA IF NOT EXISTS joins DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; USE joins; 13 https://www.facebook.com/Oxus20
  • 14. Table Students Schema DROP TABLE IF EXISTS students; CREATE TABLE IF NOT EXISTS students ( code INT NOT NULL, first_name VARCHAR(45) NOT NULL, last_name VARCHAR(45) NOT NULL, PRIMARY KEY (code) ) ENGINE = InnoDB; 14 https://www.facebook.com/Oxus20
  • 15. Table Students Data INSERT INTO students (code, first_name, last_name) VALUES (20120, 'Abdul Rahman', 'Sherzad'), (20121, 'Cristina', 'Silva'), (20122, 'Bob', 'Logan'), (20123, 'Ana', 'Nava'), (20124, 'Sekila', 'Manzikalla'); 15 https://www.facebook.com/Oxus20
  • 16. Table Subjects Schema DROP TABLE IF EXISTS subjects; CREATE TABLE IF NOT EXISTS subjects ( id INT NOT NULL AUTO_INCREMENT, subject_name VARCHAR(45) NULL, PRIMARY KEY (id), UNIQUE INDEX (subject_name) ) ENGINE = InnoDB; 16 https://www.facebook.com/Oxus20
  • 17. Table Subjects Data INSERT INTO subjects (id, subject_name) VALUES (1, 'Web Development'), (2, 'Web Design'), (3, 'Concept of Programming'), (4, 'Fundamentals of Database Systems'), (5, 'Graphic Design'); 17 https://www.facebook.com/Oxus20
  • 18. Table Enrollments Schema DROP TABLE IF EXISTS enrollments; CREATE TABLE IF NOT EXISTS enrollments ( student_code INT NOT NULL, subject_id INT NOT NULL, PRIMARY KEY (student_code, subject_id), FOREIGN KEY (student_code) REFERENCES students (code) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (subject_id) REFERENCES subjects (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB; 18 https://www.facebook.com/Oxus20
  • 19. Table Enrollments Data INSERT INTO enrollments (student_code, subject_id) VALUES (20120, 1), (20120, 2), (20121, 2), (20121, 3), (20122, 3), (20123, 3), (20122, 4), (20123, 4); 19 https://www.facebook.com/Oxus20
  • 20. INNER JOIN (JOIN) » The most frequently used clause is INNER JOIN or just JOIN. » Fetching Matching Records From All the Tables » Let's say we want to see which students taken which subjects. 20 https://www.facebook.com/Oxus20
  • 21. INNER JOIN (JOIN) SELECT code, first_name, last_name, subject_name FROM students INNER JOIN enrollments ON students.code = enrollments.student_code INNER JOIN subjects ON enrollments.subject_id = subjects.id; 21 https://www.facebook.com/Oxus20
  • 22. Alternative I - INNER JOIN (JOIN) SELECT code, first_name, last_name, subject_name FROM students INNER JOIN enrollments INNER JOIN subjects ON students.code = enrollments.student_code AND enrollments.subject_id = subjects.id; 22 https://www.facebook.com/Oxus20
  • 23. Alternative II – Just JOIN SELECT code, first_name, last_name, subject_name FROM students JOIN enrollments ON students.code = enrollments.student_code JOIN subjects ON enrollments.subject_id = subjects.id; 23 https://www.facebook.com/Oxus20
  • 24. Alternative III – Where Clause SELECT code, first_name, last_name, subject_name FROM students, subjects, enrollments WHERE students.code = enrollments.student_code AND enrollments.subject_id = subjects.id; 24 https://www.facebook.com/Oxus20
  • 26. Alternative IV - Alias SELECT code AS 'Student Code', first_name AS 'First Name', last_name AS 'Last Name', subject_name AS 'Subject' FROM students AS stu INNER JOIN enrollments AS en ON stu.code = en.student_code INNER JOIN subjects AS sub ON en.subject_id = sub.id; 26 https://www.facebook.com/Oxus20
  • 27. Alternative V – Alias Refined SELECT code 'Student Code', first_name 'First Name', last_name 'Last Name', subject_name 'Subject' FROM students stu INNER JOIN enrollments en ON stu.code = en.student_code INNER JOIN subjects sub ON en.subject_id = sub.id; 27 https://www.facebook.com/Oxus20
  • 29. RIGHT JOIN (RIGHT OUTER JOIN) » What if we require a list of all students and their subjects even if they are not enrolled on one? » A RIGHT JOIN produces a set of records which matches every entry in the right table (students) regardless of any matching entry in the left table (subjects) and / or (enrollments). 29 https://www.facebook.com/Oxus20
  • 30. RIGHT JOIN (RIGHT OTHER JOIN) SELECT code, first_name, last_name, subject_name FROM subjects INNER JOIN enrollments ON subjects.id = enrollments.subject_id RIGHT JOIN students ON students.code = enrollments.student_code; 30 https://www.facebook.com/Oxus20
  • 32. LEFT JOIN (LEFT OUTER JOIN) » Let's change the scenario, perhaps we require a list of all subjects and students even if the subjects are not chosen by any students? » A LEFT JOIN produces a set of records which matches every entry in the left table (subjects) regardless of any matching entry in the right table (students) and / or enrollments. 32 https://www.facebook.com/Oxus20
  • 33. LEFT JOIN (LEFT OUTER JOIN) SELECT subject_name, code, first_name, last_name FROM subjects LEFT JOIN ( students INNER JOIN enrollments ON students.code = enrollments.student_code ) ON subjects.id = enrollments.subject_id; 33 https://www.facebook.com/Oxus20
  • 34. Alternative – RIGHT JOIN SELECT subject_name, code, first_name, last_name FROM students INNER JOIN enrollments ON students.code = enrollments.student_code RIGHT JOIN subjects ON subjects.id = enrollments.subject_id 34 https://www.facebook.com/Oxus20
  • 36. LEFT JOIN vs. RIGHT JOIN » LEFT (OUTER) JOIN and RIGHT (OUTER) JOIN works exactly the same. » ONLY the order of the tables are reversed! 36 https://www.facebook.com/Oxus20
  • 37. FULL JOIN (or FULL OUTER JOIN) » The OUTER JOIN which returns all records in both tables regardless of any match. Where no match exists, the missing side will contain NULL. » OUTER JOIN is less useful than INNER, LEFT or RIGHT joins and it's not implemented in MySQL. » However, you can work around this restriction using the UNION of a LEFT and RIGHT JOIN. 37 https://www.facebook.com/Oxus20
  • 38. FULL JOIN (or FULL OUTER JOIN) SELECT code, first_name, last_name, subject_name FROM subjects LEFT JOIN ( students INNER JOIN enrollments ON students.code = enrollments.student_code ) ON subjects.id = enrollments.subject_id UNION SELECT code, first_name, last_name, subject_name FROM subjects INNER JOIN enrollments ON subjects.id = enrollments.subject_id RIGHT JOIN students ON students.code = enrollments.student_code; 38 https://www.facebook.com/Oxus20
  • 40. Cross Join » This is the default type of JOIN query when no condition is specified. » The result is a so called "Cartesian Product" of the tables. » It means that each row from the first table is matched with each row of the second table. » Since each table had 5 rows, we ended up getting a result of 25 rows. 40 https://www.facebook.com/Oxus20
  • 41. Cross Join SELECT code, first_name, last_name, subject_name FROM students CROSS JOIN subjects; 41 https://www.facebook.com/Oxus20
  • 42. Cross Join - Alternative SELECT code, first_name, last_name, subject_name FROM Students, subjects; 42 https://www.facebook.com/Oxus20
  • 44. SELF JOIN » The SELF JOIN is used to join a table to itself as if the table were two tables; temporarily renaming at least one table in the SQL statement. » You can view SELF JOIN as two identical tables. But in normalization you cannot create two copies of the table so you just simulate having two tables with SELF JOIN. 44 https://www.facebook.com/Oxus20
  • 45. SELF JOIN » Let's say you have a table named "users" with following structure: ˃ User ID ˃ User Name ˃ User's Manager's ID UserID UserName ManagerID 1 Abdul Rahman Sherzad 0 2 Ana Nava 1 3 Bob Logan 2 4 Cristina Silva 3 https://www.facebook.com/Oxus20 45
  • 46. Table Users Schema CREATE TABLE IF NOT EXISTS users ( UserID int(11) NOT NULL AUTO_INCREMENT, UserName varchar(50) NOT NULL, ManagerID int(11) NOT NULL, PRIMARY KEY (UserID) ) ENGINE=InnoDB; 46 https://www.facebook.com/Oxus20
  • 47. Table Users Data INSERT INTO users (UserID, UserName, ManagerID) VALUES (1, 'Abdul Rahman Sherzad', 0), (2, 'Ana Nava', 1), (3, 'Bob Logan', 2), (4, 'Cristina Silva', 3); 47 https://www.facebook.com/Oxus20
  • 48. SLEF JOIN - Example SELECT u.UserID, u.UserName AS 'User Name', m.UserName AS 'Manager Name' FROM users u INNER JOIN users m ON u.ManagerID = m.UserID; 48 https://www.facebook.com/Oxus20
  • 50. SELF JOIN with LEFT JOIN SELECT u.UserID, u.UserName AS 'User Name', m.UserName AS 'Manager Name' FROM users u LEFT JOIN users m ON u.ManagerID = m.UserID ORDER BY u.UserID ASC; 50 https://www.facebook.com/Oxus20
  • 52. Conclusion » Thank you for reading this presentation. I hope you that it gives you a better understanding of JOINS and helps you write more efficient SQL queries as well as enjoyed it! » Please leave your comments and questions, and have a great day  52 https://www.facebook.com/Oxus20