SQL JOINs
JOINs merge related data from multiple tables together in to result set.
The two most common types of joins are:
INNER JOIN
OUTER JOIN
INNER JOINs
INNER JOINs return rows that match from both tables.
SELECT <columns> FROM <table 1>
INNER JOIN <table 2> ON <table 1>.<column> = <table 2>.<column>;
SELECT <columns> FROM <table 1> AS <table 1 alias>
INNER JOIN <table 2> AS <table 2 alias> ON <table 1 alias>.<column> = <table 2 alias>.<column>;Examples:
SELECT product_name, category FROM products
INNER JOIN product_categories ON products.category_id = product_categories.id;
SELECT products.product_name, product_categories.category FROM products
INNER JOIN product_categories ON products.category_id = product_categories.id;
SELECT p.product_name, c.category FROM products AS p
INNER JOIN product_categories AS c ON p.category_id = c.id;INNER JOINing multiple tables:
Examples:
OUTER JOINs
There are 3 types of OUTER JOINs:
LEFT OUTER JOIN - JOINs all matching data and all non-matching rows from the left table in the query
RIGHT OUTER JOIN - JOINs all matching data and all non-matching rows from the right table in the query
FULL OUTER JOIN - JOINs all matching data and then all non-matching rows from both tables.
Example
If you wanted to get the product count for every category, even categories without products, an OUTER JOIN is the best solution. The following two examples will yield the same results, however one is an
Last updated
Was this helpful?