When a SQL query is joining n tables (with n>=2), it is expected to have join conditions defined to determine on which columns these n tables
should be joined. At minimum, for n joined tables, the SQL query should contain (n-1) join conditions involving all the joined table to avoid a full
cartesian product between the rows of the n tables.
Not doing so will imply that too many rows will be returned. If this is not the case and unless this has been done on purpose, the SQL query should
be reviewed and missing conditions should be added or useless tables should be removed from the SQL query.
This rule is raising no issue when the SQL query is involving CROSS JOIN
, NATURAL JOIN
statements.
Noncompliant code example
SELECT c.id, c.name, o.id, o.item_id, o.item_quantity
FROM ORDERS o, CUSTOMERS c; -- Noncompliant; no JOIN condition at all
SELECT c.id, c.name, o.id, o.item_id, o.item_quantity
FROM ORDERS o
JOIN CUSTOMERS c ON o.customer_id = o.id; -- Noncompliant; no condition related to CUSTOMERS
SELECT f.name, d.title, l.*
FROM FOLDERS f, DOCUMENTS d, DOC_LINES l -- Noncompliant; missing at least one condition related to DOC_LINES
WHERE f.id = d.folder_id;
Compliant solution
SELECT c.id, c.name, o.id, o.item_id, o.item_quantity
FROM ORDERS o, CUSTOMERS c
WHERE o.customer_id = c.id; -- Compliant
SELECT c.id, c.name, o.id, o.item_id, o.item_quantity
FROM ORDERS o
JOIN CUSTOMERS c ON o.customer_id = c.id; -- Compliant
SELECT f.name, d.title, l.*
FROM FOLDERS f, DOCUMENTS d, DOC_LINES l
WHERE f.id = d.folder_id
AND d.id = l.document_id; -- Compliant