Retrieve one row of data
Expect exactly one row. Returns a Hash; raises on 0 or more than 1.
Flip the response shape to a single row. Lives on the select builder. Sets Accept: application/vnd.pgrst.object+json so PostgREST itself enforces the contract — the wire request returns the row as an object (not an array of length 1), and the server returns 406 Not Acceptable when the result set is empty or has more than one row.
See maybe_single for the "0-or-1" variant that returns nil on no rows.
Signature
builder.singleParameters
This method has no parameters.
Returns
A builder that, when .execute'd, returns a SingleAPIResponse whose data is the single row as a Hash (not wrapped in an array). Raises Supabase::Postgrest::Errors::APIError (code PGRST116) when the result set is not exactly one row.
Example — fetch one row by id
response = supabase
.from("countries")
.select("*")
.eq("id", 1)
.single
.execute
response.data # => { "id" => 1, "name" => "Algeria", ... }Compare without .single — the same query would return a one-element array:
response = supabase.from("countries").select("*").eq("id", 1).execute
response.data # => [{ "id" => 1, "name" => "Algeria", ... }]Example — raises when the row doesn't exist
PostgREST refuses to coerce 0 rows to an object, so .single over a non-matching filter raises:
begin
supabase.from("countries").select("*").eq("id", -1).single.execute
rescue Supabase::Postgrest::Errors::APIError => e
e.code # => "PGRST116"
e.message # => "Cannot coerce the result to a single JSON object"
endUse maybe_single when "no row" is a valid case and you want nil instead of an exception.
single vs maybe_single
single | maybe_single | |
|---|---|---|
Sets Accept: application/vnd.pgrst.object+json | yes | no (SELECT chain) |
| 0 rows | raises APIError (PGRST116) — server-side | returns nil — client-side check |
| 1 row | data is the row as a Hash | data is the row as a Hash |
| more than 1 row | raises APIError (PGRST116) — server-side | raises APIError ("Cannot coerce…") — client-side check |
| Use when | the row must exist (PK lookup) | the row may or may not exist (optional lookup) |
Both raise on >1, but single enforces the contract on the wire (PostgREST returns 406 with no body), while maybe_single issues a normal array request and inspects the result client-side. Pick maybe_single whenever 0 is a valid outcome.