Random row in table #2299
-
Hello, so I have this problem to solve. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
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 } = await supabase
.rpc('get_random_game') |
Beta Was this translation helpful? Give feedback.
-
I've handled it like this create function get_random_row (user_email varchar) returns uuid as $$
select id from games tablesample system_rows(1) where not user_email=ANY(guessed_by);
$$ language sql; And calling it from javascript like this let { data, error } = await supabase
.rpc('get_random_row', {
user_email
})
if (error) console.error(error)
else console.log(data) |
Beta Was this translation helpful? Give feedback.
Hey @sk0le,
For getting a random row, you can use the TABLESAMPLE SQL clause:
The randomness of the above method depends on the amount of rows you have. If you have few rows, you could do:
You can wrap one of the above methods on a SQL function and then call it through supabase rpc.