Sikau

Databases and SQL · Day 9 · about 35 min

JOINs

Combine tables in one query.

Put the pieces back together

Data is split across tables; questions usually aren't: "which customer placed each order?". A JOIN matches rows from two tables on a column — most often a foreign key and the primary key it points to.

INNER and LEFT JOIN

SELECT o.id, c.name, o.ordered_at, o.status
FROM orders o
JOIN customers c ON c.id = o.customer_id
ORDER BY o.id;

SELECT c.name, count(o.id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.name
ORDER BY orders DESC, c.name;

SELECT o.id, d.name, oi.qty, d.price * oi.qty AS line_total
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
JOIN dishes d ON d.id = oi.dish_id
WHERE o.id = 1;

The rest of this lesson

  • Joining three tablesexplain
  • Counting with LEFT JOINexplain
  • Who's missing?predict
  • count(*) after LEFT JOINpredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 17 lessons of Databases and SQL