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

Chapter 8 - JOINS and SET Operations

The document discusses joining tables and performing set operations on relations in SQL. It covers joining tables through equijoins, natural joins, and using aliases. It also discusses left and right outer joins. Set operations like union, intersection and minus are also introduced.

Uploaded by

Anjana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
506 views

Chapter 8 - JOINS and SET Operations

The document discusses joining tables and performing set operations on relations in SQL. It covers joining tables through equijoins, natural joins, and using aliases. It also discusses left and right outer joins. Set operations like union, intersection and minus are also introduced.

Uploaded by

Anjana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

JOINS and SET Operation

outline

Introduction
Joining Tables
Performing SET Operations on Relations
8.1ntroduction

• You must have encountered some sutuation where the simple queries could not work up
to your expectation.
• For instance , you might have wanted to extract columns from more than one table or to
group records coming from multiple tables (relations) or to find common records of two
tables.
• Two important concept of SQL -


will be covered in this chapter.


8.2 Joining Tables
A join is a query that combines rows from two or more tables.

In a join-query , more than one table are listed in the FROM clause
of SELECT query.

The function of combining data from multiple tables is called


joining.

The joining of two tables can be restricted or unrestricted.


8.2.1 Unrestricted Join (Cartesian Product)
• When two tables are joined without any binding condition, such type of join
is called unrestricted join and the result produced is called the Cartesian
products.
• A Cartesian product of two table consists of all possible combination of rows
coming from two tables. See, no condition is given (WHERE clause is missing)
it will result into Cartesian product
SELECT *
FROM EMP1 , DEPT ;
It returns n1 x n2 rows where n1 is the number of rows in first table and n2
is the number of rows in second table.
A Cartesian product is formed when :
 A Join condition is omitted
 A join condition is invalid
 All rows in the first table are joined to all rows in the second table.
8.2.2 Restricted Join (Join)
 A restricted join or simply a join is quddery that combines rows from two or more tables
based on a condition.
 Consider the empl table,you have been using in earlier chapters and table Dept

Table 8.1 Table empl Table 8.2 Table Dept


In Order to find the location of the employee named ANOOP , we would use the
following query :
mysql > SELECT ENAME , LOC Addittional condition along with
the join condition
FROM EMPL , DEPT
WHERE ENAME = ‘ANOOP’
AND EMP.DEPTNO = DEPT.DEPTNO ;
Output
ename loc
ANOOP CHENNAI

Thus we can say that a join is used when an SQL query requires data
from more than on table on database
Qualified Names
If we say deptno field from joining tables empl and dept , it will lead
to an ambiguity that “ deptno field from which table ? “
To avoid such ambiguity , the qualified field names are used.

• Qualified field names are specifies using the following syntax:


<tablename>.<fieldname>
• Qualified field names are very useful in identifying a field if the
joining tables have fields with same name.
8.2.3 Using Table Aliases
• To give a temporary name, to a table , Aliases are used in MySQL.
• By using Aliases ,we can save the amount of typing required in our queries.
• A table alias can be used anywhere in the SELECT statement.
• An alias only exists for the duration of that query.
For example if we want to use the abbreviation ‘E’ for the EMPL table , we need to tell
MySQL that EMPL will be referenced by E in the FROM clause.
8.2.4 Additional Search Conditions in Join
• Once you have joined tables, you can filter information from joined table by
incorporating additional search conditions.
8.2.5 Joining More Than Two Tables

Sometimes you need to extract information from more than two tables.In
this case you need to join more rhan two tables.

This can be achieved by specifying all the required table names in FROM
clause and by providing all join conditions using AND operator.
OUTPUT
8.2.6 Equi - join
The join, in which columns are compared for equality, is called
Equi - Join.
An equal sign ( = ) is used as comparison operator in the where
clause to refer equality.
Recall the output of example 1.

mysql > SELECT * FROM empl, dept


-> WHERE empl.deptno = dept.deptno;
8.2.7 Non- Equi - join
A non-equi-join is a query that specifies some relationship other than
equality between the columns.
• The non-equi join uses comparision operator insted of the equal sign like >,
<, >=, <= along with conditions.
8.2.8 Natural join
The result of an equijoin contain two identical columns.
One of the two identical columns can be eliminated by restating the query.
This result is called a Natural Join (Equi join minus one of the two identical
columns).
“ The join in which only one of the identical columns exists, is called
Natural Join. ”
Example
mysql > SELECT empl.*,dname,loc
-> FROM empl, dept
-> WHERE empl.deptno = dept.deptno;
8.2.9 Joining Tables using JOIN Clauses of SQL SELECT
 MySQL also supports special JOIN clauses , as part of SQL SELECT
statement.
There are two types of join Cross Join & Natural Join
 The syntax for using JOIN is :
SELECT *
FROM <table>
[CROSS] [NATURAL] JOIN <table 2>
[ ON (<Join - Condition>) | USING <joinfields > ) ];

It works as follows :
-> To create Cartesian product ofif two tables (say empl and dept ) write query as:
no join-condition is specified with a
SELECT * JOIN clause, cartesian-product will be output.

FROM empl JOIN dept;


Cross Join : The cartesian product of two tables is also known as CROSS JOIN. The cross
join ( or cartesian product ) is a very basic type of join that simply matches each row from
one table to every row from another table. Cross join, by default, does not apply any filtering
condition on the joined data. However , if you want to filter, you can use WHERE clause of
SELECT query.
cartesian product using CROSS JOIN
SELECT *
FROM empl CROSS JOIN dept ;

To create equijoin on some common field (say deptno) of two tables (empl and dept
here ), write query as :
SELECT * Join condition is specified with ON clause
FROM empl e
JOIN dept d
ON (e.deptno = d.deptno);
Cross Join : MySQL provide a NATURAL JOIN clause for you that , one of the
duplicate columns get removed from thr output.

SELECT *
FROM <table 1>
NATURAL JOIN <table2> ;

That is , above query will now become:

SELECT *
FROM empl
NATURAL JOIN dept ;
Filtering Output : We can further filter the join output, by using the WHERE
clause.
For instance, following query will first create a natural join from tables empl
and dept and then extract only those records where sal is more than 2000.
mysql > SELECT FROM empl e
-> NATURAL JOIN dept d
-> WHERE sal > 2000 ;
Similarly , the following query will first create equi-join from tables empl and
dept and then filter those records where sal is < 2000
mysql > SELECT * FROM empl
-> JOIN dept ON (empl.deptno = dept.deptno)
-> WHERE sal < 2000 ;
USING vs ON Clause : We can also use the USING clause in place of ON clause
but with USING clause we just have to specify the name of join-field.That is
above query can also be reframes as:
SELECT *
FROM empl
JOIN dept
USING (deptno);
Difference between ON and USING sub clauses of JOIN clause of SELECT

1. ON cluase requires a complete join-condition whereas USING clause requires just


the name of a join field.
2. USING subclause produces natural join whereas ON clause produces equi-join.
8.2.9 LEFT, RIGHT Joins
• When you join tables based on some condition,you may find that only some,
not all rows from either table match with rows of other table.When you
display an equi-join or natural join, it shows only the matched rows.
• What if you want to know which all rows from a table did not match
with other.
• In such case , Mysql left or right JOIN can be very helpful and it refers to the
order in which the tables are put together and the results are displayed.
LEFT Join : Left join returns all rows from the first table, whether there are
matches in the second table or not.
For unmatched rows of first table, NULL is shown in clumns of second table.
Syntax: SELECT <slect-list>
FROM <table 1 > LEFT JOIN <table 2 >
Consider the tables empl and dept. Table dept has now the following records(
notice the new records )

This is the first table, hence all the rows


from dept table will be returned and
unmatched rows will be filled with
NULL for the right table’s columns.

Now if we write a query as shown below:


SELECT dept.* , ename, mgr FROM dept LEFT JOIN empl
ON dept.deptnno = empl.deptno
it will produce the output as follows.
RIGHTT Join : RIGHT JOIN works just like the LEFT JOIN but with table order
reversed..RIGHT join returns all rows from the second table, whether there are
matches in the first table or not.
Syntax: SELECT <slect-list>
FROM <table 1 > RIGHT JOIN <table 2 >
ON <joining condition>;
8.3 Performing SET Operations on Relations
• SQL SET Operations ( UNION, INTERSECTION, MINUS ) combine the rows
coming from two or more relations(tables).
• SQL SET operations combine the relations on rows, i.e. rows from one
relation are appended beneath other.

SQL joins tend to combine columns from two or more tables (i.e. width
wise) and SQL SET Operation tend to combine rows from two or more
tables (i.e. length wise)
There are three SET Operations.
1. UNION
2. INTERSECT
3. MINUS
8.3.1 UNION
Multiple queries can be combined into one by forming a union of
them.

The SQL UNION operator allows manipulation of results returned


by two or more queries by combining the results of each query into
a single result set.

Consider the data given below:


UNION ALL will retain all the duplicates
rows from tables in the final output
while UNION will remove the duplicate
rows from the final output.
8.3.1A Rules of Using UNION Operator
1. The column list of select statements must have same nnumber of columns
having similar data types and order.For example the following two union
queries are invalid
SELECT ecode,ename FROM branch1 SELECT ecode,ename,gender FROM branch1
UNION UNION
SELECT ename,ecode FROM brach2; SELECT ecode,ename,gender,grade FROM branch2;

2. The ORDER BY clause can occur onlyat the end of the UNION statement .It
can’t be used within the individual queries that make the UNION statement.

3. The GROUP BY and HAVING clauses are allowd only within indiviual queries
.These clauses cannot be used to affect the final result set.
8.3.1B UNION vs. UNION ALL
Both UNION and UNION ALL give the combine rows of two tables, but UNION
removes the duplicate entries while UNION ALL retains the duplicate entries.
8.3.2 MINUS Operator
• The MINUS operator is used to get the unique rows from the table1, i.e. the
rows which are in table1 but not in table2.
• MINUS is also known as EXCEPT.
• We need to be careful with the order of SELECT statements.table1 MINUS
table2 is not the same as table2 MINUS table1.

The MINUS operator is used as:


SELECT * FROM table1
MINUS
SELECT * FROM table2;
• MySQL does not supprot MINUS operator directly but you can simulate
MINUS operator by using LEFT JOIN.
SELECT <list> FROM <table1>
LEFT JOIN <table2>
ON <table1>.<common column> = <table2>.<common column>
WHERE<table2>.<common column> IS NULL;
Suppose if you have following tables:

Then the following query OUTPUT


SELECT NAME FROM Vendor
MINUS ABC Com.
SELECT NAME FROM CUTOMER;
But if we swap the tables
OUTPUT
SELECT NAME FROM CUTOMER
MINUS XYZ P Ltd.
SELECT NAME FROM Vendor ;
8.3.3 INTERSECT Operator
• INTERSECT operation returns common rows from both the left and right
tables.
• This is useful when you want to find result that are in common between two
queries.
If you want to find out about vendor that are also
cutomers, you can use INTERSECT operator as-
<SELECT query1>
INTERSECT
<SELECT query2> OUTPUT
eg
K Creations
SELECT Name FROM Vendor
INTERSECT
SELECT Name FROM Cutomer;
r
• We can also use an INNER JOIN to answer the same question
SELECT Distnict V.Name
FROM Vendor V
INNER JOIN Cutomer C
ON V.Name = C.Name
r
Rules applicable to al set operators (UNION , INTERSECT , MINUS)

 column count must be the same in the select list.


 data types of restricted columns should match or at least should be implicitly
convertible by database
 the order of columns in all select lists should be compatible.
r

You might also like