Sub topic 14
Reading Older Comma-Style Joins
This chapter assumes that you know basic SELECT, FROM, WHERE, and ORDER BY syntax, and that you understand primary and foreign keys.
Before explicit INNER JOIN syntax became common, SQL queries often listed tables separated by commas. The query then placed the matching condition in the WHERE clause. This is called a comma-style join or an implicit join.
SELECT c.name, o.id AS order_id, o.total
FROM customers AS c, orders AS o
WHERE o.customer_id = c.id;This query returns the same rows as the following explicit inner join:
SELECT c.name, o.id AS order_id, o.total
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.id;Both queries match each order to the customer whose primary key equals the order's customer ID. Customers without orders and orders without a customer are excluded.
What the comma means
A comma in the FROM clause first creates every possible pair of rows. This result is called a Cartesian product. If one table has three rows and another has four rows, the product has twelve possible pairs.
The condition in the WHERE clause then keeps only the pairs that match.
With the sample data, the Cartesian product includes pairs such as Ada with order 103 and Chloe with order 101. The WHERE condition removes those unrelated pairs.
Separating join conditions from filters
A comma-style query can have several conditions in its WHERE clause. The join condition connects tables. Other conditions filter the matched rows.
SELECT c.name, o.id AS order_id, o.order_date
FROM customers AS c, orders AS o
WHERE o.customer_id = c.id
AND o.total > 30
ORDER BY o.order_date;The first condition is the join condition. The second condition is a regular filter. Keeping this distinction clear helps when reading older SQL.
The main danger: forgetting the match
If you omit the relationship condition, the database returns every possible pair:
SELECT c.name, o.id AS order_id
FROM customers AS c, orders AS o;This may run successfully while producing incorrect results. It can also create a very large result. For example, 10,000 customers and 50,000 orders produce up to 500 million pairs before filtering.
Explicit joins make the relationship easier to see and make accidental cross joins less likely. Prefer explicit INNER JOIN ... ON syntax in new queries. Learn comma-style syntax mainly so you can understand and safely maintain older code.
Exercise
Rewrite this comma-style query using explicit join syntax: SELECT c.name, o.id FROM customers AS c, orders AS o WHERE c.id = o.customer_id AND o.total >= 50;
Show answer
SELECT c.name, o.id FROM customers AS c INNER JOIN orders AS o ON o.customer_id = c.id WHERE o.total >= 50;