Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 31 ยท Supabase Postgres Database

Querying with supabase-js

Read and write your Supabase Postgres data from JavaScript: select, insert, update, delete, upsert, filters, order, range, joins, RPC calls and error handling.

Supabase turns each table in your public schema into an HTTP API (using a tool called PostgREST), and the supabase-js library wraps that API in a chainable query builder. You write supabase.from("todos").select("*").eq("done", false) and the library turns it into a request, runs it as SQL on your Postgres database, and gives you back plain JavaScript objects.

The builder reads almost like English, so it is quick to learn. The important habits are less obvious: every call returns { data, error } instead of throwing, filters decide which rows change, and what you can see is decided by security policies you will meet in Row Level Security.

Real supabase-js needs a Supabase project, so SDK code is read-only in this lesson. The runnable examples are stand-ins: a tiny query builder over an array in memory. It copies the shape of the API (chaining, { data, error }) but is not the real library or PostgREST.

Creating the client

JavaScript
import { createClient } from "@supabase/supabase-js";

const supabase = createClient(
  "https://your-project-ref.supabase.co",
  "your-public-anon-key",
);

The URL and the anon (public) key are safe to ship in browser code, as long as Row Level Security is on. The service_role key bypasses security and must never leave your server; the setup lesson covered this.

The chainable builder

Pick a table, then chain

from Choose the table.
Action select, insert, update, delete or upsert.
Filters eq, gt, in, ilike and friends.
Modifiers order, range, limit, single.

The request is sent when you await the chain.

1 / 2

A query is built in this order: table, action, filters, modifiers. Nothing is sent until you await it.

JavaScript
const { data, error } = await supabase
  .from("todos")
  .select("id, title, done")
  .eq("done", false)
  .order("created_at", { ascending: false })
  .range(0, 9);

Reading rows

JavaScript
// All columns
const { data } = await supabase.from("todos").select("*");

// Chosen columns only
await supabase.from("todos").select("id, title");

// Filters
await supabase.from("todos").select().eq("done", false);               // =
await supabase.from("todos").select().neq("user_id", currentUserId);   // <>
await supabase.from("todos").select().gt("priority", 2);               // >
await supabase.from("todos").select().lte("due_date", "2026-12-31");   // <=
await supabase.from("todos").select().in("id", [1, 2, 3]);             // IN (...)
await supabase.from("todos").select().ilike("title", "%milk%");        // case-insensitive LIKE
await supabase.from("todos").select().is("due_date", null);            // IS NULL

Several filters are combined with AND. Use .or("done.eq.true,priority.gt.3") for OR conditions.

Pagination uses .range(from, to), which is inclusive on both ends and zero-based, so .range(0, 9) returns ten rows. Use .limit(n) for "first n". When you expect exactly one row, add .single(); you get an object instead of an array, and an error if zero or several rows match. .maybeSingle() allows zero rows without an error.

Writing rows

JavaScript
// insert: pass an object or an array of objects
await supabase.from("todos").insert({ title: "Buy milk", user_id: currentUserId });

// to get the inserted row back, chain select()
const { data } = await supabase
  .from("todos")
  .insert({ title: "Buy milk", user_id: currentUserId })
  .select()
  .single();

// update: ALWAYS add a filter
await supabase.from("todos").update({ done: true }).eq("id", 5);

// delete: ALWAYS add a filter
await supabase.from("todos").delete().eq("id", 5);

// upsert: insert, or update when the key already exists
await supabase.from("profiles").upsert({ id: currentUserId, username: "ada" });

Without a filter, update and delete would target every row the policies allow you to touch. Supabase's hosted databases add a safety net that refuses unfiltered updates and deletes, but do not rely on it; always filter. By default, insert, update and delete return no rows (data is null). Add .select() when you need them back.

upsert uses the primary key by default. Choose another unique column with { onConflict: "username" }.

Try it: a stand-in query builder

The stand-in below holds two tables in arrays and implements select, insert, update, delete, upsert, filters, order, range, single, and an embedded select. It returns { data, error } like supabase-js does.

JS A chainable query builder over arrays

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The stand-in's await works because Query has a then method. That is how real builders delay the request until you await them. Note the shape of the failures: nothing throws, you get error instead.

Joins through foreign keys

Because of the foreign key from todos.user_id to profiles.id, supabase-js can fetch related rows in one request. You list the related table and its columns inside the select string:

JavaScript
const { data } = await supabase
  .from("todos")
  .select("id, title, profiles(username)");
// [{ id: 1, title: "Write notes", profiles: { username: "ada" } }, ...]

For a many-to-one link (many todos belong to one profile) the nested value is an object. In the other direction, profiles with todos(title) returns an array of todos per profile. You can filter on the related table (for example .eq("profiles.username", "ada"), combined with profiles!inner(username) to drop non-matching parents) and rename relationships when several foreign keys point to the same table. This replaces the N+1 pattern that Firestore needs, as you saw in the queries lesson.

Calling SQL functions with rpc

Some work does not fit the builder: multi-step logic, aggregates, or anything that must be atomic. Write a Postgres function and call it by name:

SQL
create function public.count_open_todos(uid uuid)
returns integer
language sql
stable
as $$
  select count(*)::integer from public.todos where user_id = uid and done = false;
$$;
JavaScript
const { data, error } = await supabase.rpc("count_open_todos", { uid: currentUserId });
console.log(data); // 3

Arguments are passed as an object whose keys match the function's parameter names. The function runs in the database, which makes it a good place for transactions such as "create an order and reduce stock". Functions run with the caller's permissions by default (security invoker), so Row Level Security still applies.

Handling errors

supabase-js does not throw for database or API errors. It returns them:

JavaScript
const { data, error } = await supabase.from("todos").insert({ user_id: currentUserId });

if (error) {
  console.error(error.code, error.message);   // e.g. "23502" for a NOT NULL violation
  return;
}
console.log(data);

The code is often a Postgres SQLSTATE code (23505 unique violation, 23503 foreign key violation, 23502 not null violation, 42501 permission denied), or a PostgREST code such as PGRST116 when .single() does not find exactly one row. Check error on every call. A very common bug is to use data without looking at error, then crash on null.

A related trap: when a Row Level Security policy hides rows, a select simply returns fewer rows (or none), and an update that matches no visible row changes nothing, with no error. If a query "works but returns nothing", suspect policies first.

Try it: a safe wrapper around { data, error }

Many teams write one small helper that turns the { data, error } pair into a thrown error or a value, so screens can use try/catch. This stand-in shows the pattern with a fake client that fails on demand, and a fake rpc.

JS Unwrapping results and calling rpc

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A supabase-js call fails because of a database error. What happens?

    supabase-js returns the error in the result object. You must check error yourself.
  2. 2. What does .range(0, 9) return?

    range is zero-based and inclusive at both ends, so 0 through 9 is ten rows.
  3. 3. Which line is dangerous if you forget to add a filter?

    An update without a filter targets every row you are allowed to touch. Always add .eq(...) or similar.
  4. 4. How do you fetch each todo together with its owner's username in one request?

    supabase-js follows foreign keys: name the related table inside the select string.
  5. 5. A select returns an empty array although rows exist in the table. What is a likely cause?

    Policies filter silently. The query succeeds but only returns rows the user may see.

Summary

  • supabase.from(table) starts a chain: action, filters, then modifiers like order, range and single.
  • Every call returns { data, error }; check error before using data.
  • Always filter update and delete; add .select() to get changed rows back.
  • range(from, to) is inclusive; upsert inserts or updates by key.
  • Foreign keys let you embed related rows with select("title, profiles(username)").
  • Use rpc() to call Postgres functions for logic that needs SQL or atomicity.

Next: Supabase Realtime and Postgres Changes.