Skip to main content

distinct

The distinct method returns all unique records matching the given distinct field:

const users = await User.distinct('name').all()

select distinct on ("users"."name") "users".* from "users"

Distinct on the primary key, or clearing distinct

Calling distinct() with no argument, or distinct(true), distincts on the primary key. distinct(false) clears a distinct applied earlier in the chain:

await Host.query().distinct().all() // DISTINCT on the primary key
await Host.query().distinct(true).all() // same as above
await Host.query().distinct('familyName').distinct(false).all() // distinct cleared

Chaining

Similar to other execution methods, distinct is chainable to other query-building methods, such as where:

const count = await User.innerJoin('pets as p', { name: 'Aster' })
.distinct('p.name')
.count()

select count(DISTINCT $1) as "tablecount" from "users"
inner join "pets" as "p" on "users"."id" = "p"."user_id"