22

I know currently Prisma doesn't support ordering by multiple scalars fields, (see this issue: https://github.com/prisma/prisma/issues/62). But, I'm wondering if there is someone who found a solution to work around this issue without using executeRaw mutation (raw SQL) because I have many places in my code where I need to order by multiple fields and I don't want to use executeRaw in so many places. I will appreciate any suggestions. Thank you!

2 Answers 2

61

Since Prisma 2.4 this should be basically possible by using array in orderBy:

const users = await prisma.user.findMany({
   select: {
      email: true,
      role: true,
   },
   orderBy: [
      {
         email: 'desc',
      },
      {
         role: 'desc',
      }
   ],
})

Find more in docs: https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#sort-user-by-multiple-fields---email-and-role

Sign up to request clarification or add additional context in comments.

3 Comments

Ok, but how do I write ... ORDER BY (foo = 1) DESC, bar ASC, foo ASC, baz ASC;?
What do you mean by (foo = 1) ?
I want rows where foo equals to 1 be sorted before the rest. In SQL you can do that as I've written it.
1

I don't think there's a solution, In my project, I need random order, increment/decrement, aggregation... use raw finally.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.