You are on page 1of 22

Displaying Data from Multiple Tables

In real applications of databases, it is required to produce reports


which need data from more than one tables. SQL allows us to write
statements which retrieve data from multiple tables.






Cartesian Product
or
Cross Join of tables
Cartesian Product of two tables is a table obtained by pairing up each
row of one table with each row of the other table without any
condition.

Eg:
Table A contain 3 rows and 4 columns
Table B contains 2 rows and 3 columns
Cartesian product will contain
6 (=3x2) rows and 7 (=4+3) columns
Cardinality:
Number of records/rows/tuples in a table.

Degree:
Number of columns/attributes/columns in a table.

In a Cartesian Product of two tables,


• Cardinality is the product of cardinality of the two tables.
• Degree is the sum of degree of the two tables.
In a Cartesian product, MySQL will pair the rows of the tables involved:
Cartesian Product is given below:

SELECT * FROM ORDER_TABLE, PRODUCT;

Cardinality : 6
Degree: 5
SQL query to find the Cartesian Product
Consider the tables product and order_table,

SELECT * FROM PRODUCT, ORDER_TABLE;


OR
SELECT * FROM PRODUCT CROSS JOIN ORDER_TABLE;
OR
SELECT PRODUCT.*, ORDER_TABLE.* FROM PRODUCT, ORDER_TABLE;
OR
SELECT A.*, B.* FROM PRODUCT A, ORDER_TABLE B;
OR
SELECT ORDER_NO, P_CODE, SUP_CODE, CODE, NAME
FROM PRODUCT, ORDER_TABLE;
In some cases, the complete Cartesian product of two
tables may give some confusing information. But we can
extract meaningful information from the Cartesian product
by placing some conditions in the statement.
Equi Join

The join in which columns are compared for equality is called


Equi-Join. It contains tables based on matching values in
specified columns.

In case of Equi Join:


• The column names involved in comparison need not to be
the same.
• The resultant table contains repeated columns.
• It is possible to perform an equi join on more than two
tables.
Equi Join
Equi Join

Equi Join
Equi Join
Natural Join
Natural Join

Natural Join
Natural Join

Equi Join Natural Join


1. Joins two tables on the basis of 1. Joins two tables based on same
the explicitly specified column attribute name and data types
on the on clause.
2. Resulting table contain all the 2. Unlike Equi join only one copy of
attributes of both the tables the common columns exists.
including duplicate columns.

3. SELECT * FROM TABLE1,TABLE2


3. SELECT * FROM TABLE1 NATURAL JOIN
WHERE TABLE1.COL1 = TABLE2.COL2; TABLE2;
Self Join
A self join is a regular join, but the table is joined with itself.

SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE T1.colname1=T2.colname2;
Self Join
A self join is a regular join, but the table is joined with itself.

SELECT A.EMP_ID, A.EMP_NAME, B.EMP_NAME as ‘MANAGER’


FROM EMP A, EMP B WHERE A.MANAGER_ID= B.EMP_ID ORDER BY A.EMP_NAME;

Self Join>>

You might also like