Lecture 08
Lecture 08
Sapna Kumari
DATABASE SYSTEMS- LECTURE 08 Lecturer, CS-SZABIST
Sapna.kumari@hyd.szabist.edu.pk
OUTLINE
• Joins
• Types of Joins
-Inner Join
-Left Join
- Right Join
- Full Join
- Self Join
JOINS
A relational database consists of multiple related tables linking together using
common columns which are known as foreign key columns. Because of this, data in
each table is incomplete from the business perspective.
By using joins, you can retrieve data from two or more tables based on logical
relationships between the tables. Joins indicate how SQL should use data from one
table to select the rows in another table.
A join condition defines the way two tables are related in a query by:
• Specifying the column from each table to be used for the join. A typical join
condition specifies a foreign key from one table and its associated key in the other
table.
• Specifying a logical operator (for example, = or <>,) to be used in comparing
values from the columns.
JOINS-TYPES
-Inner Join
-Left Join
- Right Join
- Full Join
- Self Join
INNER JOIN
The INNER JOIN keyword selects records that have matching values in both tables.
Syntax:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
If the join condition uses the equal operator (=) and the column
names in both tables used for matching are the same,
you can use the USING clause instead:
INNER JOIN-EXAMPLE
SELECT * FROM TableA
INNER JOIN TableB ON
TableA.PK = TableB.PK
INNER JOIN-EXAMPLE
LEFT JOIN
The LEFT JOIN keyword returns all records from the left table (table1), and the matched records from
the right table (table2). The result is NULL from the right side, if there is no match.
Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.
LEFT JOIN-EXAMPLE
SELECT * FROM TableA
LEFT JOIN TableB ON
TableA.PK = TableB.PK
LEFT JOIN-EXAMPLE
RIGHT JOIN
The RIGHT JOIN keyword returns all records from the right table (table2), and the
matched records from the left table (table1). The result is NULL from the left side,
when there is no match.
Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;