I have two columns in a table:
rating_total integer
rating_count integer
rating_total is a sum of total rates, and rating count is a number of total rating. I want to order by average rate:
ORDER BY (rating_total/rating_count) DESC, id ASC
Should I create separate column for average_rate
? Or it is possible to create some index to speed this up?
I've managed to create index like this:
CREATE INDEX "posts-avg-rating-index"
ON "Posts" (("rating_total"::float/(CASE "rating_count" WHEN 0 THEN NULL ELSE "rating_count" END)) DESC NULLS LAST, id DESC);'
Which works for ordering like this:
ORDER BY (("rating_total"::float/(CASE "rating_count" WHEN 0 THEN NULL ELSE "rating_count" END)) DESC NULLS LAST, id DESC)