An SQL JOINÂ returns rows from multiple tables based on a common field between them. Consider the following users and orders tables:
users table
user_id | first_name | last_name | |
---|---|---|---|
1 | John | Adams | johna@gmail.com |
2 | Mark | Smith | msmith@aol.com |
3 | Tom | Williamson | twilliamson@gmail.com |
orders table
order_id | user_id | total | date |
---|---|---|---|
1001 | 2 | 500.99 | 2015-08-02 |
1002 | 2 | 59.99 | 2015-08-03 |
1003 | 3 | 60 | 2015-08-04 |
Typically JOIN is synonymous with INNER JOIN. Let’s perform an INNER JOIN on the users and orders table:
SELECT users.user_id, users.first_name, users.last_name, orders.total FROM users INNER JOIN orders ON users.user_id = orders.user_id ORDER BY users.user_id
Our result, which merges the users and orders tables by matching the user_id field, gets the user_id, first_name, last_name, and total, and finally sorts them by user_id:
user_id | first_name | last_name | total |
---|---|---|---|
2 | Mark | Smith | 500.99 |
2 | Mark | Smith | 59.99 |
3 | Tom | Williamson | 60 |
An INNER JOIN is similar to the intersection of a set in mathematics, or the intersection of a Venn Diagram. The result includes all the rows with a match on users. canary feather mites oral ivermectin user_id = orders.user_id. The result will not include any rows from the left or right table (users and orders, respectively) that do not contain a match within the ON clause. klinghardt parasite ivermectin
A LEFT OUTER JOIN will return the same result as an INNER JOIN, however it will also include every row in the left table (users), even if there is no match within the ON clause. Fields that do not match will be marked with NULL:
SELECT users.user_id, users.first_name, users.last_name, orders.total FROM users LEFT OUTER JOIN orders ON users.user_id = orders.user_id ORDER BY users.user_id
user_id | first_name | last_name | total |
---|---|---|---|
1 | John | Adams | NULL |
2 | Mark | Smith | 500.99 |
2 | Mark | Smith | 59.99 |
3 | Tom | Williamson | 60 |
Likewise a RIGHT OUTER JOIN will include all of the rows from the right table (orders) and mark non-matches with a NULL:
user_id | first_name | last_name | total |
---|---|---|---|
2 | Mark | Smith | 500.99 |
2 | Mark | Smith | 59.99 |
3 | Tom | Williamson | 60 |
In this particular example, every row in the right table (orders) has a match and no NULL fields are returned.
Finally, if not evident from the examples given above, it should be noted that LEFT and RIGHT refer to the order of the tables listed in the SQL statement. Intermectin ivermectin for dogs In our example, users is listed first (becoming the left table) and orders is listed next (effectively making it the right table).