Query random item(s) from database (Supabase)

Hi I am building a quiz app, I wonder how to query random single question from my questions table in supabase. For example I want to query a question 1 by 1 each page.

I figured I need to make another query to find the length first, which returns all the id, get the length of the collections, and used it for the other query. I guess this will cause some leakage of data. If you found better solution please help

Not only a leakage of data but also a waterfall of requests that will slow down the load of your quiz (wait for first query and then wait for the second query with the data you need).

With supabase you can create database functions that allow you to do get a random row with only one request.
Have a look at the documentation.

In short:

  • create and run this SQL snippet:
create or replace function get_random_quiz()
returns setof quiz
language sql
as $$
   select * from quiz 
   order by random()
   limit 1;
$$;
  • call the supabase REST API in your workflow with a GET request to the url https://<project_ref>.supabase.co/rest/v1/rpc/get_random_quiz. Be sure to switch on the option to make the request with the server and to add two header to the request:
    • apikey: <SUPABASE_ANON_KEY>
    • Authorization: Bearer <SUPABASE_ANON_KEY>

This specific way of getting a random row (order by random()) is good only for small tables. If you are going to work with big tables you can modify the query to randomly select in a more performant way.

2 Likes

Thank you so much @dorilama :pray: :pray: :pray:, I will try it and update the outcome

1 Like

@dorilama I came across this video after watching @Quentin live on supabase views. So basically I generated a new view that contains random order of my quiz. Really quick and easy solution. Thank you!

Also @Quentin the video was very helpful. I am just getting the hang of backend, I think we need more on those since us no-coders never touched on API before, so we don’t know what’s the best practices for databases and backend.

1 Like

This is also another good way to get the same result.
Now you can choose between two solutions :slight_smile:

1 Like

keep in mind that with the solution in the video you is using order by random() as well, so you will hit the same performance problem if your table is big.

2 Likes