Skip to content

Results of findDistinct not guaranteed to be distinct sorting by a field other than the desired field #15084

@malee31

Description

@malee31

Documentation Issue

The documentation for findDistinct (Link) says that the values will be an array of distinct values and also shows an example of how to sort in the results as well.
But when sorting by a field other than the field, the results end up no longer being distinct.

Example:

await payload.create({
  collection: "links",
  data: { link: "1" }
});
await payload.create({
  collection: "links",
  data: { link: "1" }
});
await payload.create({
  collection: "links",
  data: { link: "2" }
});

const result = await payload.findDistinct({
  collection: "links",
  field: "link",
  sort: "-updated_at",
});
console.log(result);
// Debug SQL: `Query: select distinct "link", "updated_at" from "links" order by "links"."updated_at" desc`
// ["2", "1", "1"]

The resulting SQL statement has findDistinct querying for all columns to be distinct together before Payload/Drizzle throws away the sort column, so if the sort column isn't always the same, we get duplicate values.
This might also be a bug.

Additional Details

Above example is from a snippet of code with table names changed.
Using current latest (3.69.0) with db-postgres

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions