SQL
Retrieve Related Data Using SQL JOINs
Master SQL JOINs (INNER, LEFT) to combine data from multiple tables, linking users with their orders, posts, or other related entities.
SELECT
u.username,
p.title AS post_title,
p.content AS post_content,
p.created_at AS post_date
FROM
users u
INNER JOIN
posts p ON u.id = p.user_id
WHERE
u.is_active = TRUE
ORDER BY
p.created_at DESC;
How it works: This snippet illustrates how to use an `INNER JOIN` to combine data from two related tables: `users` and `posts`. It selects the username from the `users` table and post details from the `posts` table, linking them where `user_id` in `posts` matches `id` in `users`. The `WHERE` clause filters for active users, and results are ordered by post creation date.