I have a table Responses and a table Votes. The Votes table has a column vote_value which can either be 1 or -1 depending on whether people vote up or down on a given response. I’m wondering how I can sort responses by the sum of the votes on them.
The problem with doing a join and simply ordering by SUM(vote.vote_value) as score (descending) is that some responses don’t have votes, so a response with a score of -1 will be higher up than a response with no votes on it (which would be a score of 0 really).
If there’s no way to do this with SQL, I suppose I could just do the sorting myself in the application code.
Use COALESCE to select a value when SUM returns NULL: