How to get random recrods from findMany? #5886
-
As discussed in Prisma 1 forum, I'd like to know how to find random records in The below query should work in
|
Beta Was this translation helpful? Give feedback.
Replies: 15 comments 23 replies
-
Hey @hyochan, thanks a lot for raising this! I don't think returning items from Alternatively, you can of course use the SQL query that you posted above and send it to the DB using Prisma Client's In any case, I think this is a really interesting feature request, would you mind persisting it in a GitHub issue so that our Product and Engineering teams can look into it? |
Beta Was this translation helpful? Give feedback.
-
Try something like this const productsCount = await prisma.product.count();
const skip = Math.floor(Math.random() * productsCount);
return await prisma.product.findMany({
take: 5,
skip: skip,
orderBy: {
sellingCount: 'desc',
},
}); |
Beta Was this translation helpful? Give feedback.
-
My current attempt: async pickRandom(count: number): Promise<CognitiveTest[]>{
const itemCount = await this.prisma.cognitiveTest.count();
const skip = Math.max(0, Math.floor(Math.random() * itemCount) - count);
const orderBy = randomPick(['id', 'field1', 'field2']);
const orderDir = randomPick([SortOrder.asc, SortOrder.desc]);
return this.prisma.cognitiveTest.findMany({
take: count,
skip: skip,
orderBy: { [orderBy]: orderDir },
});
} |
Beta Was this translation helpful? Give feedback.
-
Yet another problem, that could be easily solved by allowing raw sql in Prisma API. See #5560 If raw sql would be allowed in Prisma API, the solution to this problem could look like this: prisma.users.findMany({
orderBy: raw`random()`,
take: 1
}); |
Beta Was this translation helpful? Give feedback.
-
I wait the issue to be completed but if you need a temporary solution :
|
Beta Was this translation helpful? Give feedback.
-
To simplify all the above: results = await prisma.$queryRawUnsafe(
// DO NOT pass in or accept user input here
`SELECT * FROM "Post" ORDER BY RANDOM() LIMIT 30;`,
) |
Beta Was this translation helpful? Give feedback.
-
For MySQL or PlanetScale, a sample code: return await prisma.$queryRaw`SELECT * FROM accounts WHERE is_public = 1 ${
adminId ? Prisma.sql`AND admin_id <> ${adminId}` : Prisma.empty
} ORDER BY RAND() LIMIT 3`; |
Beta Was this translation helpful? Give feedback.
-
With the new Views feature in Prisma you could create a view with
and then create a view model in your Prisma schema that mirrors your user model. |
Beta Was this translation helpful? Give feedback.
-
things to keep in mind: Using Can be an issue with large tables |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
This comment was marked as disruptive content.
This comment was marked as disruptive content.
-
function getRandomGifts() {
const allIds = await this.databaseService.gift.findMany({
select: {
id: true,
},
})
allIds.sort(() => Math.random() - 0.5)
const randomIds = allIds.slice(0, 20).map((gift) => gift.id)
return await this.databaseService.gift.findMany({
where: { id: { in: randomIds } },
})
} |
Beta Was this translation helpful? Give feedback.
-
Prisma still doesn't support this yet lol Why should everyone suffer by not providing About 3 years have passed, but nothing has changed. This isn't even a special feature. It is used by many developers. I really wonder that the Prisma development team consider some useful tools for web developer. |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
Hey @hyochan, thanks a lot for raising this! I don't think returning items from
findMany
in a random order is natively supported by Prisma Client yet and I don't think there's another way how you could retrieve a random element with Prisma Client. If you only care about getting a single item though and not really about the randomness, you can usefindFirst
.Alternatively, you can of course use the SQL query that you posted above and send it to the DB using Prisma Client's
$queryRaw
method.In any case, I think this is a really interesting feature request, would you mind persisting it in a GitHub issue so that our Product and Engineering teams can look into it?