CodingDatabases
One can analyze data from multiple tables simultaneously by using one of the four JOIN
operators, or the UNION
, INTERSECT
and EXCEPT
operators.
A JOIN
operation appends new columns to the results table consists of three parts:
SELECT
- specifies the columns to returntable1 JOIN table2
- the names of the tables being joinedON
- specifies the column common to both tables
The UNION
/INTERSECT
/EXCEPT
operations append/remove rows from two resulting queries where the the columns match in number, data types, and order:
UNION
- concatenates the results of two queries, removing duplicates (only get unique rows)UNION ALL
- concatenates the results of two queries, including duplicatesINTERSECT
- return the common rows from the two queriesEXCEPT
- return unique rows from the first query but not in the second
A generic query might look like:
SELECT *
FROM table1
JOIN table2
ON table1.column = table2.column
AND condition;
The four types of JOIN
operations are
table1 INNER JOIN table2
- return only the rows with values in both tablestable1 LEFT JOIN
- return all rows fromtable1
and impute missing data fromtable2
withNULL
table1 RIGHT JOIN table2
- return all rows from thetable2
and impute missing data fromtable1
withNULL
table1 FULL OUTER JOIN table2
- return all rows from both tables and impute missing data from each withNULL
(WARNING: can create duplicate rows)