AI Hints
Home›PostgreSQL Tutorial›Joins, LATERAL and FILTER
PostgreSQL · Lesson 25 of 120

Joins Refresher

Combine tables.

⏱ 2 min read▶ Video at 20:55🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

An order only stores a customer ID. To show the customer's name, we join orders to customers, matching the IDs.

  • orders.customer_id
  • customers.customer_id
  • JOIN

Orders with names

Join customers using customer ID matches rows where the IDs are equal. The short names o and c save typing. Run it. Each order, with the customer's name and country.

query.sqlsql
SELECT o.order_id, o.order_date, c.first_name, c.country
FROM orders o
JOIN customers c USING (customer_id)
ORDER BY o.order_id
LIMIT 4;
Output
 order_id | order_date | first_name |  country
----------+------------+------------+-----------
     1001 | 2025-03-06 | Tara       | Canada
     1002 | 2024-11-24 | Tara       | Canada
     1003 | 2024-06-22 | Grace      | Australia
     1004 | 2025-02-19 | Grace      | Australia
(4 rows)

Customers with no orders

A left join keeps every customer, even those with no orders. Their order columns are null. So where order ID is null finds customers who never ordered. Run it. Customers who signed up but never bought.

query.sqlsql
SELECT c.first_name, c.last_name, c.joined
FROM customers c
LEFT JOIN orders o USING (customer_id)
WHERE o.order_id IS NULL
LIMIT 3;
Output
 first_name | last_name |   joined
------------+-----------+------------
 Bruno      | Haddad    | 2024-05-15
 Will       | Silva     | 2025-06-07
 Daniel     | Smith     | 2025-01-02
(3 rows)

Summary

Inner joins keep matches, and left joins keep every row from the left table. Next, a powerful Postgres join, lateral.

Key takeaways
  • JOIN
  • LEFT JOIN
  • IS NULL
Next up: LATERAL Joins — a subquery per row