Skip to content

Distinct On

Carlos edited this page Aug 18, 2019 · 3 revisions

MySQL-like group by statements on queries. It keeps only the first row of each set of rows where the given expressions evaluate to equal. PostgreSQL Docs

How it works

distinct_on(*columns)

Just send the list of fields to be included on the DISTINCT ON statement:

# SELECT DISTINCT ON ( "users"."name" ) "users".* FROM "users"
User.distinct_on(:name).all

You can use where-like syntax to find more complex columns:

# SELECT DISTINCT ON ( "photos"."type" ) "users".* FROM "users" INNER JOIN "photos" ON "users"."id" = "photos"."user_id"
User.joins(:photos).distinct_on(photos: :type).all

# SELECT DISTINCT ON ( "photos"."type", "photos"."size" ) "users".* FROM "users" INNER JOIN "photos" ON "users"."id" = "photos"."user_id"
User.joins(:photos).distinct_on(photos: [:type, :size]).all
Clone this wiki locally