Databases Lesson 3: Joins

🗄️ Databases CourseLesson 3 of 10 · 30% complete

Joins combine data from multiple tables. They’re what make relational databases powerful — data is normalized into separate tables and joined at query time.

Types of Joins

-- Setup:
CREATE TABLE orders (
  id SERIAL PRIMARY KEY,
  user_id INTEGER REFERENCES users(id),
  product VARCHAR(100),
  total DECIMAL(10,2),
  status VARCHAR(20)
);

-- INNER JOIN: only rows that match in BOTH tables
SELECT u.name, o.product, o.total
FROM users u
INNER JOIN orders o ON u.id = o.user_id;

-- LEFT JOIN: all from left + matching from right (nulls if no match)
SELECT u.name, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.name;

-- Right JOIN, FULL OUTER JOIN also exist

Multi-Table Join

SELECT
  u.name as customer,
  p.name as product,
  oi.quantity,
  oi.quantity * p.price as subtotal
FROM users u
JOIN orders o ON u.id = o.user_id
JOIN order_items oi ON o.id = oi.order_id
JOIN products p ON oi.product_id = p.id
WHERE o.status = 'completed'
ORDER BY subtotal DESC;

🏋️ Practice Task

Create 3 tables: authors, books, categories. authors: id,name,bio. books: id,title,author_id,category_id,price,year. categories: id,name. Write joins: all books with author names, most prolific author, average book price per category, books published after 2000 with their authors and categories.

💡 Hint: SELECT a.name, COUNT(b.id) as books FROM authors a LEFT JOIN books b ON a.id=b.author_id GROUP BY a.name ORDER BY books DESC

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *