JOIN Operations

Combine data from multiple tables

#joins #inner-join #left-join #relationships

JOIN Operations

JOINs combine rows from two or more tables based on related columns.

INNER JOIN

-- Returns only matching rows from both tables
SELECT users.name, orders.total
FROM users
INNER JOIN orders ON users.id = orders.user_id;

LEFT JOIN

-- Returns all rows from left table, matching rows from right
SELECT users.name, orders.total
FROM users
LEFT JOIN orders ON users.id = orders.user_id;

RIGHT JOIN

-- Returns all rows from right table, matching rows from left
SELECT users.name, orders.total
FROM users
RIGHT JOIN orders ON users.id = orders.user_id;

Multiple JOINs

SELECT
  users.name,
  orders.order_date,
  products.name AS product_name
FROM users
INNER JOIN orders ON users.id = orders.user_id
INNER JOIN order_items ON orders.id = order_items.order_id
INNER JOIN products ON order_items.product_id = products.id;

Discover another handy tool from EditPDF.pro