Hello friends :wave: Anyone know whether it's poss...
# orm-help
k
Hello friends 👋 Anyone know whether it's possible to get a random row in the db via the query without pulling everything and grabbing a random one in the client/node?
j
I think you could for example generate random integer before querying the table. If you have an integer id column in the table you can just then query prisma.mytable.findOne({where: {id: randomId}}}) Of course in this case you would have to first find the max id the table contains.
k
Thanks for the idea, but I'd rather not use integers and query for the max id 😅
p
You can get the count of the table, get a random number between 0 and the number of rows, then do a select with`LIMIT 1 OFFSET $RANDOMNUMBER` . I’m sure you can add these parameters to a query, just not sure what is the equivalent in prisma API
I believe this should work:
Copy code
const count = await prisma.table.count();
const randomRowNumber = Math.floor(Math.random() * count);
const randomRow = await prisma.table.findMany({ take: 1, skip: randomRowNumber });
k
Was hoping I could do this in one query, but that definitely is better! Thanks @Pierre Ortega!
p
Yeah… I don’t see a way of doing in one query without writing the SQL query ourselves and using
queryRaw
. Maybe I’m wrong
k
That's ok, this will work great. Thank you!
🙌 1