I'm trying to order retrieved records by a field on a left outer join in the following SQL query:
@companies = Company.scoped
@companies = @companies.where("companies.is_deleted = 'f' AND companies.state IN (?)", ["draft", "pending"])
@companies = @companies.includes(:events)
@companies = @companies.order("events.created_at DESC")
SELECT "companies"."id" AS t0_r0, "companies"."name" AS t0_r1, "companies"."reference" AS t0_r2, "companies"."state" AS t0_r3, "companies"."description" AS t0_r4, "companies"."remarks" AS t0_r5 "events"."id" AS t2_r0, "events"."eventable_type" AS t2_r1, "events"."eventable_id" AS t2_r2, "events"."event_type" AS t2_r3, "events"."creator_company_id" AS t2_r4, "events"."creator_user_id" AS t2_r5, "events"."created_at" AS t2_r6
FROM "companies"
LEFT OUTER JOIN "events" ON "events"."eventable_id" = "companies"."id" AND "events"."eventable_type" = 'company'
WHERE "companies"."is_deleted" = 'f' AND companies.state IN ('draft','pending')
ORDER BY events.created_at DESC
But the retrieved records are not sorted properly as expected (i.e. by events.created_at)
Any clue how to successfully do that while keeping performance efficient?
ORDER BYworks correctly in Postgres. Please show us an example output of what you think is not correct. Are you aware thatevents.created_atmight contain NULL values due to the outer join?