HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

How to join with null value?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
withnullvaluejoinhow

Problem

This code returns only posts having a rating. How I can get all posts with null value where the post does not have a rating?

select
posts.id,
posts.user_id,
posts.name,
posts.created_at,
ratings.post_id,
ratings.avg,
ratings.count
from
posts
join (
select
post_id,
avg(rating) as avg,
count(rating) as count
from
ratings
group by
ratings.post_id
) ratings
on ratings.post_id = posts.id

Solution

Have you tried using a LEFT OUTER JOIN? A LEFT OUTER JOIN will keep all the rows from the 'left' side of the join statement (posts table) that do not have a correponding row on the 'right' side of the statement (ratings table). The missing rows from the 'right' side will be filled with NULLS.

Context

StackExchange Database Administrators Q#151201, answer score: 8

Revisions (0)

No revisions yet.