A
A
AlekseiFlis2019-07-08 13:11:43
PostgreSQL
AlekseiFlis, 2019-07-08 13:11:43

How to get a random record from a database?

How can you retrieve the values ​​of a randomly selected entry from the database?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
kafkiansky, 2019-07-08
@AlekseiFlis

Depends on what fields you have there. If you need by ID, then get the number of IDs (unless, of course, it is uuid), then randomly choose between 1 and the maximum number of id in the database. As an option.
upd: but be careful, I don't know how in postgres, but in muscle, when deleting a record under this ID, the ID is skipped (1..3..4..5), so if the randomizer generates 2, you won't be able to get it record and catch the error. Better wrap it in a try ... catch.

P
Peter, 2019-07-08
@petermzg

Generate a random ID from the range of IDs available in the database and pull out the record with the given ID

D
d-stream, 2019-07-08
@d-stream

Sometimes I use options like
select top 1 * from .... order by newid() to simulate filling the database - this is MSSQL
for pg - order by random() or rand() apparently

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question