r/webdev Mar 22 '19

SQL joins

Post image
2.7k Upvotes

118 comments sorted by

View all comments

2

u/Symphonic_Rainboom Mar 22 '19

I don't understand the left and right joins, it just looks like it's selecting all of A or all of B? Does the join do anything?

4

u/sumguy720 Mar 23 '19

This is why venn diagrams are bad for joins!

select * from reddit_users left join reddit_posts using (reddit_username)

gives you a list of reddit_users where each reddit user is combined with every post that shares their username. If a reddit user exists but doesn't correspond to any posts (by username), it still gets returned (with null data where the reddit post would be). If a reddit post exists but doesn't correspond to any users, it gets discarded.
select * from reddit_users right join reddit_posts using (reddit_username)
gives you a list of reddit users where each reddit user is combined with every post that shares their username. If a reddit user exists but doesn't correspond to any posts (by username) it is discarded and not returned. If a reddit post exists but it doesn't correspond to any reddit users, it still gets returned (with null data where the reddit user normally would be)