Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 6

Display data from multiple tables

Definition
A join is a select statement that retrieves data from two or more tables and connects that
data together to produce a combined set of output.
Tables that share common data elements that support joins are said to be related to each
other.
Types of joins:
1) Equijoins – use the equality operator
2) Non equity joins – do not use the equality operator
3) Inner joins
4) Outer joins
5) Natural joins
6) Cross joins (also known as Cartesian products)
7) Self joins.
Key relationships
- Primary Key
- Foreign Key
Primary key and foreign key relationships help to protect the integrity of data in columns
that are intended to join tables, but their presence is not required in order to create a
successful join.
Entity relationship Diagram (ERD) can be referred in the exam.
It is a diagram that shows the keys and the relationships between two or more tables.
Note
You can join tables without the presence of PRIMARY KEY and FOREIGN KEY constraints.
There is no official connection in the database between key constraints and table joins. Key
constraints are helpful to provide data integrity and to increase odds of successful and
meaningful results from table joins. They are not required.
Inner versus Outer JOINS
3) Inner Joins – connect rows in two or more tables only if there are matched rows in all the
tables that are being joined.
4) Outer Joins – connect rows in two or more tables in a more inclusive way – if data exists
in one table that has no matching value in another, the unmatched rows will be still be
included in the output.
Equijoins versus Non-equijoins
1) Equijoins - connect data in two or more tables by looking for common data among the
tables’ columns.
2) Non-equijons - connect data by looking for relationships that don’t involve equality,
such as “less than” or “greater than” relationships, or situations where data in one table
is within a range of values in another table.
Other joins – 5),6),7) fall into the categories that we have already seen of inner and outer
joins, or equijoins and non-equijoins
3) Inner joins
Example:
PORTS table:
PORT_ID PORT_NAME
---------------------- --------------------
1 Baltimore
2 Charleston
3 Tampa
4 Miami
Next, the SHIPS table:

SHIP_ID SHIP_NAME HOME_PORT_ID


---------------------- -------------------- -------------------
1 Codd Crystal 1
2 Codd Elegance 3
3 Codd Champion
4 Codd Victorious 3
5 Codd Grandeur 2
6 Codd Prince 2

Here’s the code for an inner join:

SELECT SHIP_ID, SHIP_NAME, PORT_NAME


FROM SHIPS [INNER] JOIN PORTS
ON HOME_PORT_ID = PORT_ID
ORDER BY SHIP_ID;
Older Inner Join Sintax
Here’s the code for an inner join:
SELECT SHIP_ID, SHIP_NAME, PORT_NAME
FROM SHIPS INNER JOIN PORTS
ON HOME_PORT_ID = PORT_ID
ORDER BY SHIP_ID;
The newer syntax is preferred because it consists with the ANSI standards for SQL joins.
4) Outer Joins
An outer join is a join that displays data from the same rows an inner join does, but also
adds data from rows that don’t necessarily have matches in all the tables that are joined
together. There are three types of outer joins—LEFT, RIGHT, and FULL.
Left Outer Join
Example:
SELECT SHIP_ID, SHIP_NAME, PORT_NAME
FROM SHIPS LEFT [OUTER] JOIN PORTS
ON HOME_PORT_ID = PORT_ID
ORDER BY SHIP_ID;
Result:
SHIP_ID SHIP_NAME PORT_NAME
---------------------- -------------------- --------------------
1 Codd Crystal Baltimore
2 Codd Elegance Tampa
3 Codd Champion
4 Codd Victorious Tampa
5 Codd Grandeur Charleston
6 Codd Prince Charleston
Right Outer Join
Example:
SELECT SHIP_ID, SHIP_NAME, PORT_NAME
FROM SHIPS RIGHT [OUTER] JOIN PORTS
ON HOME_PORT_ID = PORT_ID
ORDER BY SHIP_ID;
Result:
SHIP_ID SHIP_NAME PORT_NAME
---------------------- -------------------- --------------------
1 Codd Crystal Baltimore
2 Codd Elegance Tampa
4 Codd Victorious Tampa
5 Codd Grandeur Charleston
6 Codd Prince Charleston
Miami
Full Outer Join
Combines the effects of Left Outer Join and Right Outer Join.
Example:
SELECT SHIP_ID, SHIP_NAME, PORT_NAME
FROM SHIPS FULL [OUTER] JOIN PORTS
ON HOME_PORT_ID = PORT_ID
ORDER BY SHIP_ID;
Result:
SHIP_ID SHIP_NAME PORT_NAME
---------------------- -------------------- --------------------
1 Codd Crystal Baltimore
2 Codd Elegance Tampa
3 Codd Champion
4 Codd Victorious Tampa
5 Codd Grandeur Charleston
6 Codd Prince Charleston
Miami
Deprecated Outer Join syntax (+)
For the Left Outer Join example from above the deprecated syntax is:
SELECT SHIP_ID, SHIP_NAME, PORT_NAME
FROM SHIPS, PORTS
WHERE HOME_PORT_ID = PORT_ID(+)
ORDER BY SHIP_ID;
It still works but you will not be tested on it at the exam.
Using table aliases
- The table alias only exists for the duration of the SQL statement in which it is declared.
- When writing any query in which a column reference is ambiguous, you must do something
to identify the column clearly to the SQL statement. Otherwise, you’ll get an error message
and the SQL statement won’t execute.
- The use of table prefixes and table aliases is on the exam.
- Table aliases can be used in INSERT, UPDATE, and DELETE statements, as well as SELECT.
- We commonly use table aliases.
5) Natural Joins
Example:
SELECT EMPLOYEE_ID, LAST_NAME, STREET_ADDRESS FROM EMPLOYEES
NATURAL JOIN ADDRESSES;
- Notice the use of the keyword NATURAL JOIN
- Notice that we don’t use the keyword ON anywhere
- Although there are two EMPLOYEE_ID columns—one in EMPLOYEES and one in
ADDRESSES, table prefixes are allowed on other columns—but not the join columns in a
natural join.
- A natural join is an inner join, that is why the EMPLOYEE_ID column will always have the
same value, regardless of which table’s EMPLOYEE_ID is intended. Unmatched rows are
omitted in an inner join.
* Using
Example:
SELECT EMPLOYEE_ID, LAST_NAME, STREET_ADDRESS FROM EMPLOYEES LEFT JOIN
ADDRESSES USING (EMPLOYEE_ID);
- No table prefix is allowed anywhere in the statement.
- USING keyword does basically the same thing as the natural join in the sense that the
connection between the joined tables is performed automatically. The difference is that
USING lets us perform an outer join as well as an inner join.
Multitable Joins
Joins can connect two, three or more tables.
Example:
SELECT P.PORT_NAME, S.SHIP_NAME, SC.ROOM_NUMBER FROM PORTS P JOIN SHIPS S ON
P.PORT_ID = S.HOME_PORT_ID JOIN SHIP_CABINS SC ON S.SHIP_ID = SC.SHIP_ID;
Non-Equijoins
We have 2 tables:
SCORES:
SCORE_ID TEST_SCORE
---------------------- ----------
1 95
2 55
3 83
Next, GRADING:
GRADING_ID GRADE SCORE_MIN SCORE_MAX
---------------------- ----- ---------------------- ------------
1 A 90 100
2 B 80 89
3 C 70 79
4 D 60 69
5 E 50 59
The following select statement determines each score’s grades:
SELECT S.SCORE_ID, S.TEST_SCORE, G.GRADE FROM SCORES S JOIN GRADING G ON
S.TEST_SCORE BETWEEN G.SCORE_MIN AND G.SCORE_MAX;
7) Self Joins
- Self-joins can also be referred to as recursive joins.
- A self-join is a table that is joined to itself.
- A self-join connects a column in a table with a column—often a different column—in the
same table.
- Syntactically you can join a column to itself in the same table, as opposed to a different
column in the same table. It doesn’t do much logically, but the syntax will execute.
- Self-joins can be inner joins or outer joins, equijoins or nonequijoins, etc.
Here’s a listing of some of the columns in the POSITIONS table:
POSITION_ID POSITION REPORTS_TO
---------------------- -------------------- ----------------
1 Captain
2 Director 1
3 Manager 2
4 Crew Chief 2
5 Crew 4
* Self referencing foreign key
Example:
ALTER TABLE POSITIONS
ADD CONSTRAINT FK_PO_PO FOREIGN KEY (REPORTS_TO)
REFERENCES POSITIONS (POSITION_ID);
- Note that a foreign key is advised, but not required in order to perform the self-join.
* Self join syntax
In order to create a self join we need to do the following:
1) Identify the table twice in the from clause
2) Define our join criteria
3) Apply a table alias to all appropriate references
Example:
SELECT A.POSITION_ID, A.POSITION, B.POSITION BOSS
FROM POSITIONS A LEFT OUTER JOIN POSITIONS B
ON A.REPORTS_TO = B.POSITION_ID
ORDER BY A.POSITION_ID;
Result:
POSITION_ID POSITION BOSS
---------------------- -------------------- --------------------
1 Captain
2 Director Captain
3 Manager Director
4 Crew Chief Director
5 Crew Crew Chief
Generate a Cartesian Product of all rows from two or more tables
8) Cross joins
- A Cartesian product occurs when two or more tables are included in a SELECT statement
without a join condition.
- When a SELECT statement references two or more tables in the FROM clause without a
JOIN, SQL will still execute the statement, connecting each row in one table with every row
in the other.
Example:
Table VENDORS:
VENDOR_ID VENDOR_NAME
--------- -----------
1 Acme Steaks
2 Acme Poker Chips
Table ONLINE_SUBSCRIBERS:
ONLINE_SUBSCRIBER_ID LASTNAME
-------------------- --------
1 KLINE
2 bryant
3 McLean
Syntax of creating a Cartesian Product on these two tables:
SELECT * FROM VENDORS, ONLINE_SUBSCRIBERS;
Syntax of creating a cross join between the two tables is:
SELECT * FROM VENDORS CROSS JOIN ONLINE_SUBSCRIBERS;
The output for both is as follows:
VENDOR_ID VENDOR_NAME ONLINE_SUBSCRIBER_ID LASTNAME
---------------------- -------------------- ---------------------- -----------
1 Acme Steaks 1 KLINE
1 Acme Steaks 2 bryant
1 Acme Steaks 3 McLean
2 Acme Poker Chips 1 KLINE
2 Acme Poker Chips 2 bryant
2 Acme Poker Chips 3 McLean
* Cartesian Products are generally considered to be a “mistake” in professional applications.

You might also like