Skip to content

Random row in table #2299

Answered by steve-chavez
sk0le asked this question in Questions
Jul 9, 2021 · 2 comments · 5 replies
Discussion options

You must be logged in to vote

Hey @sk0le,

For getting a random row, you can use the TABLESAMPLE SQL clause:

-- first you'll need to enable this extension
create extension TSM_SYSTEM_ROWS;

-- get one random row
select *  from <your_table> tablesample system_rows(1);

The randomness of the above method depends on the amount of rows you have. If you have few rows, you could do:

-- this will be too slow on big tables
select * from <your_table> order by random() LIMIT 1;

You can wrap one of the above methods on a SQL function and then call it through supabase rpc.

create or replace function get_random_game() returns int as $$
  select id  from <your_table> tablesample system_rows(1);
$$ language sql;
const { data, error } = 

Replies: 2 comments 5 replies

Comment options

You must be logged in to vote
3 replies
@alvaaz
Comment options

@sk0le
Comment options

@steve-chavez
Comment options

Answer selected by steve-chavez
Comment options

You must be logged in to vote
2 replies
@carlocodes
Comment options

@steve-chavez
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
4 participants