SQL
Combine Data from Multiple Tables with LEFT JOIN
Retrieve all records from one table and their matching records from another, ensuring no data loss from the primary table, using a LEFT JOIN operation.
SELECT
u.id AS user_id,
u.username,
o.id AS order_id,
o.order_date,
o.total_amount
FROM
users u
LEFT JOIN
orders o ON u.id = o.user_id
WHERE
u.status = 'active';
How it works: The LEFT JOIN clause is essential for combining rows from two or more tables based on a related column between them. This snippet joins the 'users' table with the 'orders' table, using 'user_id' as the common column. It retrieves all active users and their corresponding order details. If a user has no orders, the columns from the 'orders' table will show NULL, ensuring all users from the left table ('users') are included in the result set.