0

There is any way to get the table count in rest mode?

I'm using query params like:

https://urt.to.supabase/rest/v1/table?select=field,another_field

I was googling it out but without success.

dshukertjr
  • 15,244
  • 11
  • 57
  • 94
Diego Ulloa
  • 500
  • 8
  • 19

1 Answers1

0

What you need to do is to add Prefer: count=exact to the request header.

Example of this using curl would be like this:

curl "https://urt.to.supabase/rest/v1/table?select=field,another_field" -I \
  -H "Prefer: count=exact"

The count value will be the number after / on the content-range header on your response. In the following example, row count is 3573458.

Content-Range: 0-24/3573458

You can read more about it on postgrest documentation here.

Note that with the Supabase.js library, you easily get the count of

const { data, error, count } = await supabase
  .from('cities')
  .select('name', { count: 'exact' })

You can read more about it on the official docs.

dshukertjr
  • 15,244
  • 11
  • 57
  • 94
  • I already tried sending the Prefer header to "count=exact" and I'm only receiving the rows, no count – Diego Ulloa Jun 08 '22 at 02:30
  • 1
    @DiegoUlloa The count will not be returned as a body, but will be included in `content-range` header as stated here. https://postgrest.org/en/stable/api.html?highlight=count#exact-count Could you check if you are getting the proper count value in the header of your response? – dshukertjr Jun 08 '22 at 02:43
  • If I specify the `count=exact` Prefer header I get `content-range: 0-12/13`, otherwise `content-range: 0-12/*`. I'm using SWR to fetch data, so I'm researching how to get it – Diego Ulloa Jun 08 '22 at 04:42
  • @DiegoUlloa Yup, in that case, 13 is the count that you are looking for! – dshukertjr Jun 08 '22 at 05:25
  • do you know how to send the `{ head: true }` param into the header according to this extract from the documentation?: `if you don't want to return any rows, you can use { count: 'exact', head: true }` – Diego Ulloa Jun 08 '22 at 19:55
  • things I tried: `{ Prefer: "count=exact; head=true" }`, `{ Prefer: "count=exact, head=true" }`, `{ Prefer: "count=exact; head=1" }`, `{ Prefer: "count=exact, head=1" }` – Diego Ulloa Jun 08 '22 at 19:57
  • 1
    @DiegoUlloa Yup, `{ head: true }` just changes the http method to a `HEAD` request instead of a `GET` request. No need to change any header parameters! https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods – dshukertjr Jun 09 '22 at 00:19