Easy sql postgresql

How many rows does a comma join return, and what happens when one table is empty?

The 30 second answer

With ten rows in the first table and twenty in the second, the query returns two hundred rows, because every row pairs with every row on the other side. If the first table becomes empty, the result has zero rows, not twenty. This is a cross join, not an outer join. I write cross join explicitly when I really want all combinations, so a missing join condition is easier to spot.

SELECT * FROM A, B returns 200 rows when A has ten rows and B has twenty, assuming no additional clauses change the result. A comma-separated two-table FROM list forms a Cartesian product: every row of A is paired with every row of B. PostgreSQL defines its cardinality as N × M and documents its equivalence to A CROSS JOIN B and A INNER JOIN B ON TRUE.

After A is empty, the same query returns zero rows: zero × twenty is zero. CROSS JOIN does not preserve unmatched rows or manufacture NULL-extended rows. That behavior belongs to outer joins. For comparison, with A empty and B holding twenty rows, A RIGHT JOIN B ON TRUE preserves B and returns twenty NULL-extended rows for A.

An intentional Cartesian product can generate every size-and-color combination for a product catalog. An accidental one can multiply a report dramatically when the relationship predicate is omitted. My preference is explicit CROSS JOIN for deliberate combinations and an explicit JOIN ... ON for relationships; that is a readability recommendation, not a claim that the syntax is inherently faster.

The multiplication describes the logical result before subsequent filtering or aggregation, not a promise that the database physically materializes every intermediate pair. Also, with more than two inputs, do not blindly exchange commas and JOIN clauses: JOIN binds more tightly than comma, which changes the names an ON condition can reference.

Sources (1)
  1. PostgreSQL: joined-table semantics