I have an objects table and votes table. I am currently grouping them and sorting by most recent vote:
SELECT objects.id, objects.name, MAX(votes.created_at) AS mv
FROM "objects"
INNER JOIN "votes" ON "votes"."object_id" = "objects"."id"
GROUP BY objects.id, objects.name
ORDER BY mv DESC
However, this only returns the objects that have votes. I searched on SO and found answers regarding how to include results that don’t exist, but I’m looking to include both those that exist and those that do not.
Is there a way to tack onto the end of the above all of the objects that don’t have votes as well?
With a
LEFT JOIN,NULLvalues are filled in where no matching rows are found – as you found out yourself:Now,
NULLis normally sorted last. But reversed withDESCit comes first. In Postgres you can useNULLS LASTto explicitly sortNULLto the end (since version 8.3):If
objects.idis the primary key you can simplify theGROUP BY(in Postgres 9.1 or later):