Prisma, how to reverse order

By

Learn how to reverse the order of results in Prisma by adding an orderBy clause to findMany and sorting by id in descending order to show the newest first.

~~~

To reverse the order of the results in Prisma, add an orderBy option to your query and sort a field in desc (descending) order.

Here’s the situation I was in. I was building a small Twitter clone, and I was getting tweets from the Tweet table:

await prisma.tweet.findMany({})

Prisma returned them from oldest to newest. That’s what you usually get from the database when the id is an autoincrementing integer: rows come back roughly in insertion order.

I wanted the opposite, like Twitter works. The newest tweet shows up first.

How to sort in descending order

I added an orderBy attribute to order by id in descending order:

await prisma.tweet.findMany({
  orderBy: [
    {
      id: 'desc'
    }
  ]
})

The array syntax lets you sort by multiple fields. When you sort by a single field, you can also pass a plain object:

await prisma.tweet.findMany({
  orderBy: {
    id: 'desc'
  }
})

Both versions do the same thing here. Use 'asc' instead of 'desc' to go back to ascending order.

Sorting by date instead of id

Sorting by id works when the id is an autoincrementing integer, because a higher id means a newer row.

But if your model uses cuid() or uuid() ids, that assumption breaks. Those ids are strings, and they don’t grow in insertion order. Sorting them gives you an order that looks random.

In that case, sort by a timestamp field:

await prisma.tweet.findMany({
  orderBy: {
    createdAt: 'desc'
  }
})

This needs a createdAt field in your model:

model Tweet {
  id        Int      @id @default(autoincrement())
  text      String
  createdAt DateTime @default(now())
}

My advice is to add a createdAt field to every model. Sooner or later you’ll want to show things in chronological order, and this makes it trivial.

Don’t rely on the default order

One thing to be careful with: the “oldest to newest” order I got without orderBy was not guaranteed.

Without an explicit orderBy, the database is free to return rows in any order it likes. It often matches insertion order, until one day it doesn’t, for example after updates or when the query planner changes strategy.

If the order matters, always state it in the query.

Tagged: Database · All topics
~~~

Related posts about database: