Two tables: Categories :id, :name Instances :id, :category_id, :another_id, :quantity Category. joins('LEFT JOIN "instances" ON "instances"."category_id" = "categories"."id"'). select("SUM(instances.quantity) as quantity, "). group("instances.category_id") But I need to filter by :another_id and I have no idea how to without removing some categories without any instances with that id