How would I select 20 random rows in a SQL (PostgreSQL) query?
There's an easy way to show a random record in a table: SELECT * FROM table_name ORDER BY RANDOM() LIMIT 1; But this query might take a while to finish as it reads the whole table first then take out a random record from it.
The random() Function A function that generates a random float from 0 to 1. Example: INSERT INTO test (id) VALUES (trunc(random()*100)); This will generate an id of three digits from 0 to 100 (trunc to make the float an integer).
FETCH retrieves rows using a previously-created cursor. A cursor has an associated position, which is used by FETCH . The cursor position can be before the first row of the query result, on any particular row of the result, or after the last row of the result. When created, a cursor is positioned before the first row.
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 20
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With