CROSS JOIN

SQL JoinsJoinsFree Lesson

Advertisement

CROSS JOIN

The CROSS JOIN keyword returns the cartesian product — every row from a paired with every row from b.

šŸ’” Returns the Cartesian product — every row from A paired with every row from B

Visual Diagram

Table A       JOIN        Table B
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”             ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│  Rows   │  ────────→  │  Rows   │
│  from   │  matched    │  from   │
│  A      │  by key     │  B      │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜             ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Basic Syntax

SELECT columns
FROM table1
CROSS JOIN table2
ON table1.column = table2.column;

Example

SELECT
    c.first_name,
    c.last_name,
    o.total AS order_total
FROM customers c
CROSS JOIN orders o ON c.id = o.customer_id;

āš ļø Always specify the join condition in the ON clause. Omitting it creates a CROSS JOIN (Cartesian product)!

āœ… Key Takeaways

  1. CROSS JOIN combines rows from two tables based on a related column
  2. The ON clause specifies how the tables are related
  3. Use table aliases to make queries more readable
  4. Different join types determine which rows are included
  5. Practice joins with sample data to understand the differences

Advertisement

Need Expert SQL Help?

Get personalized SQL training or database consulting.

Advertisement