SQL
Retrieve Data from Multiple Tables Using LEFT JOIN
Understand how to combine rows from multiple tables using a LEFT JOIN, ensuring all records from the left table are included, even if no match exists in the right table.
SELECT
u.id AS user_id,
u.username,
p.title AS post_title,
p.created_at AS post_date
FROM
users u
LEFT JOIN
posts p ON u.id = p.user_id
WHERE
u.is_active = TRUE
ORDER BY
u.id, p.created_at DESC;
How it works: This query uses a `LEFT JOIN` to combine data from the `users` and `posts` tables. It selects all active users and their associated posts. If a user has no posts, their details will still appear in the result set, with `NULL` values for the post columns, demonstrating the utility of a `LEFT JOIN` when you want to retain all records from the left table.