SQL
Retrieve Data Across Multiple Tables Using LEFT JOIN
Combine data from two tables, showing all records from the left table and matching records from the right, or NULLs if no match, using LEFT JOIN.
SELECT u.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.username, p.created_at DESC;
How it works: This snippet illustrates how to combine information from the 'users' and 'posts' tables using a 'LEFT JOIN'. It ensures that all users (from the 'left' table) are included in the result, even if they haven't made any posts. If a user has no corresponding posts, the post-related columns will show NULLs. This is ideal for displaying a list of all users and their associated content, if any.