Introduction to JOIN

Order only stores a user_id, not the user's name or email. That keeps user data in one place.

JOIN reunites split tables by matching a foreign key back to its row.

Order rows alone

Order only carries user_id — no name, no email.

SELECT * FROM "Order";
iduser_idamount
1142.00
2115.50
329.99
Seq Scan on "Order"  (cost=0.00..1.03 rows=3 width=14)

Combine with JOIN

JOIN matches Order.user_id to User.id, pulling both tables into one result.

SELECT "Order".id, "User".name, "Order".amount
FROM "Order"
JOIN "User" ON "User".id = "Order".user_id
ORDER BY "Order".id;
idnameamount
1Ada Lovelace42.00
2Ada Lovelace15.50
3Grace Hopper9.99
Sort  (cost=2.15..2.16 rows=3 width=23)
  Sort Key: "Order".id
  ->  Nested Loop  (cost=0.00..2.12 rows=3 width=23)
        Join Filter: ("User".id = "Order".user_id)
        ->  Seq Scan on "Order"  (cost=0.00..1.03 rows=3 width=14)
        ->  Materialize  (cost=0.00..1.03 rows=2 width=17)
              ->  Seq Scan on "User"  (cost=0.00..1.02 rows=2 width=17)

Try Yourself

Loaded Database:introduction-to-join.database-init

The database for this lesson is already loaded. Write any query you want and run it directly in your browser.

Exercises

0 OF 1 DONE
1.List each order's amount with the user's email, ordered by order id.

What We Learned

  • JOINcombines rows from two relations by matching column values.
  • Foreign keya column referencing another table's primary key.
  • ON clausetells PostgreSQL which columns from each side must match.