SQL
Retrieve Related Data Using LEFT JOIN
Master the `LEFT JOIN` in SQL to combine rows from two or more tables, ensuring all records from the left table are included, even without a match.
SELECT u.id, u.username, o.order_id, o.order_date
FROM users AS u
LEFT JOIN orders AS o ON u.id = o.user_id
WHERE u.status = 'active'
ORDER BY u.username, o.order_date DESC;
How it works: This query fetches user details along with their order information. A `LEFT JOIN` ensures that all users are listed, even if they have not placed any orders. If a user has no orders, the `order_id` and `order_date` columns will show `NULL`. The `WHERE` clause filters for active users, and results are ordered by username and then order date.