prisma: Order by aggregate group always returns empty group as last

Bug description

When querying a model with a group-by based on a column that can have empty values, with an aggregate and a sort on this aggregate, the empty value group is always returned last even if the aggregate result is greater than other groups.

How to reproduce

res = [
  { _count: 2, familySituation: "Divorced" },
  { _count: 1, familySituation: "CoupleWithChildren" },
  { _count: 8, familySituation: null }
]

Expected behavior

res = [
  { _count: 8, familySituation: null },
  { _count: 2, familySituation: "Divorced" },
  { _count: 1, familySituation: "CoupleWithChildren" }
]

Prisma information

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["fullTextSearch", "filteredRelationCount"]
  binaryTargets   = ["native", "debian-openssl-1.1.x"]
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

enum BeneficiaryFamilySituation {
  Married
  Single
  Widow
  Cohabitation
  CivilUnion
  CoupleWithChildren
  Divorced
  Separated
  SingleParentWithChildren
  Other
}

model Beneficiary {
  id String @id @default(uuid()) @db.Uuid
  
  familySituation                    BeneficiaryFamilySituation?   @map("family_situation")

  @@map("beneficiary")
}

An example really closed to the documentation example:

const res = await prismaClient.beneficiary.groupBy({
    by: ['familySituation'],
    _count: true,
    orderBy: { _count: { familySituation: 'desc' } }
  })

The executed SQL query is:

SELECT COUNT(*), "public"."beneficiary"."family_situation" FROM "public"."beneficiary" GROUP BY "public"."beneficiary"."family_situation" ORDER BY COUNT("public"."beneficiary"."family_situation") DESC;

The following SQL query returns the correct result:

SELECT COUNT(*) as count, "public"."beneficiary"."family_situation" FROM "public"."beneficiary" GROUP BY "public"."beneficiary"."family_situation" ORDER BY count DESC;

Environment & setup

  • OS: macOS
  • Database: PostgreSQL
  • Node.js version: v18.14.2

Prisma Version

prisma                  : 4.13.0
@prisma/client          : 4.13.0
Current platform        : darwin
Query Engine (Node-API) : libquery-engine 1e7af066ee9cb95cf3a403c78d9aab3e6b04f37a (at node_modules/.pnpm/@prisma+engines@4.13.0/node_modules/@prisma/engines/libquery_engine-darwin.dylib.node)
Migration Engine        : migration-engine-cli 1e7af066ee9cb95cf3a403c78d9aab3e6b04f37a (at node_modules/.pnpm/@prisma+engines@4.13.0/node_modules/@prisma/engines/migration-engine-darwin)
Format Wasm             : @prisma/prisma-fmt-wasm 4.13.0-50.1e7af066ee9cb95cf3a403c78d9aab3e6b04f37a
Default Engines Hash    : 1e7af066ee9cb95cf3a403c78d9aab3e6b04f37a
Studio                  : 0.484.0
Preview Features        : fullTextSearch, filteredRelationCount

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 15 (10 by maintainers)

Most upvoted comments

I may not be clear. What I want to achieve, is to order by count, no matter if the value is null. So I want to have the following results:

res = [
  { _count: 8, familySituation: null },
  { _count: 2, familySituation: "Divorced" },
  { _count: 1, familySituation: "CoupleWithChildren" }
]

res = [
  { _count: 8, familySituation: "Divorced" },
  { _count: 2, familySituation: null },
  { _count: 1, familySituation: "CoupleWithChildren" }
]

res = [
  { _count: 8, familySituation: "Divorced" },
  { _count: 2, familySituation: "CoupleWithChildren" }
  { _count: 1, familySituation: null },
]

To get these results, I use the following query:

const res = await prismaClient.beneficiary.groupBy({
    by: ['familySituation'],
    _count: true,
    orderBy: { _count: { familySituation: 'desc' } }
  })

But the results I actually gets are:

res = [
  { _count: 2, familySituation: "Divorced" },
  { _count: 1, familySituation: "CoupleWithChildren" },
  { _count: 8, familySituation: null }
]

res = [
  { _count: 8, familySituation: "Divorced" },
  { _count: 1, familySituation: "CoupleWithChildren" },
  { _count: 2, familySituation: null },
]

res = [
  { _count: 8, familySituation: "Divorced" },
  { _count: 2, familySituation: "CoupleWithChildren" }
  { _count: 1, familySituation: null },
]

I remind that I am running with Prisma v4.13.0. Yesterday, I tried to update to v4.16.0 but I struggled with type issues (unreleated to this issue).

EDIT: I just tried again today to update to v4.16.2 and this sort issue is persisting. EDIT: And it does exist on v5.0.0 too.

Hi @mlbiche,

The behavior in your example might be confusing, but I don’t think it’s a bug. To clarify, the _count: true and _count: { familySituation: 'desc' } options have different implications:

  • _count: true: Counts all rows, including those with null values for the specified column.
  • _count: { familySituation: 'desc' }: Counts only rows with non-null values for the familySituation column.

To highlight the issue, it might be worth considering slightly modified code that selects the column in both cases:

await prisma.beneficiary.groupBy({
    by: ['familySituation'],
    _count: { familySituation: true },
    orderBy: { _count: { familySituation: 'desc' } },
})
Output before
[
  { _count: 2, familySituation: 'Divorced' },
  { _count: 1, familySituation: 'CoupleWithChildren' },
  { _count: 8, familySituation: null }
]
Output after
[
  { _count: { familySituation: 2 }, familySituation: 'Divorced' },
  {
    _count: { familySituation: 1 },
    familySituation: 'CoupleWithChildren'
  },
  { _count: { familySituation: 0 }, familySituation: null }
]
In the modified example, the ordering of the results is consistent with the counts returned, because both will ignore null values.

I think this bug report actually highlights a potential missing feature, not a bug: being able to count all rows inside of orderBy, something like this (invented, currently unsupported syntax):

await prisma.beneficiary.groupBy({
    by: ['familySituation'],
    _count: true,
    orderBy: { _count: { "*": "desc" } },
})

Thanks, I definitely misunderstood you initially. Sorry.

Not sure because in my case, null record could be first or last based on their occurrence.