View on GitHub

Notes

reference notes

Joining Tables Using SQL:1999 Syntax

Use a join to query data from more than one table:

SELECT tablel.column, table2.column
FROM tablel
[NATURAL JOIN table2] |
[JOIN table2 USING (column_name)] |
[JOIN table2
ON (table1.column_name = table2.column_name)] |
[LEFT RIGHT | FULL OUTER JOIN table2
ON (tablel.column name table2.column_name)] = [CROSS JOIN table2];

Qualifying Ambiguous Column Names

Creating Natural Joins

In a natural join, SQL will decide what is the joining condition not the user themselves.

Depending on the column names: SQL will check if there is any column that has the same name in both tables and then it will join the tables based on that column. if no matching column is found, it will return a cartesian product.

Creating Joins with the USING Clause

Using Table Aliases with the USING Clause

Creating Joins with the ON Clause

SELECT employee_id, city, department_name
FROM employees e
JOIN departments d
ON d.department_id = e.department_id
JOIN locations 1
ON d.location_id = 1.location_id;

Applying Additional Conditions to a Join

Use the AND clause or the WHERE clause to apply additional conditions:

SELECT e.employee_id, e.last_name, e.department_id, d. department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id)
WHERE e.manager_id = 149;

OR

SELECT e.employee_id, e.last_name, e.department_id, d. department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id)
AND e.manager_id = 149;

Self-Joins Using the ON Clause

SELECT worker.last_name emp, manager.last_name mgr
FROM employees worker JOIN employees manager
ON (worker.manager_id = manager.employee_id);

Equijoin vs Non-Equijoin

Equijoin

Non-Equijoin

INNER Versus OUTER Joins

LEFT OUTER JOIN

RIGHT OUTER JOIN

FULL OUTER JOIN

Cartesian Products

A Cartesian product is formed when:

Always include a valid join condition if you want to avoid a Cartesian product.

Creating Cross Joins

– The returned result set has 6*5 = 30 rows. CROSS JOIN is going to match every employee with each department. ``` Whenever you have a table that you want to join with another table but there is no common column between them, you can use the CROSS JOIN clause to create a Cartesian product between the two tables.

Summary