Skip to content
Aurabase Logo
aurabase

Aggregate rows

Get totals and per-group figures from your data, with the method that works today for each need, and know which aggregate doors are closed.

How-to guide8 min readLevel intermediate

The SDK and the REST API count rows, but they do not compute sums, averages or groups on a PostgreSQL project: write the aggregate in SQL, in a view you read like a table or a function you call with rpc(). The policies of the tables still apply when the view or function runs with the caller's rights.

Prerequisites#

  • A linked project: aura link <project-id>.

  • The example schema, installed with the service role key of the project:

    export AURABASE_SERVICE_ROLE_KEY=aura_sk_…
    aura db seed --example docs

    It creates profiles, orgs, org_members, posts, todos, the view open_todos and the function todo_count(p_user uuid). See Example schema.

  • AURABASE_URL and AURABASE_ANON_KEY in the environment, for the SDK and curl examples.

The examples create the table qd_agg_orders, the view qd_agg_by_status and the function qd_agg_totals, read them with the service_role key, then remove them.

What works today#

NeedUseAvailable
Number of rows matching a filterselect('*', { count: 'exact', head: true })Yes
Number of related rows per rowselect('name, child_table(count)')Yes
sum, avg, min, max, group byA view, or a function called with rpc()Yes
Aggregates in select() (amount.sum(), count())No: refused with Use of aggregate functions is not allowed
POST /v1/db/{table}/aggregateMongoDB projects only
Ad hoc SQL from a serveraura db raw, db.sql()Yes, service_role key

Example data#

create table qd_agg_orders (
  id int primary key,
  customer text not null,
  status text not null,
  amount numeric(10,2) not null,
  ordered_on date not null
);
insert into qd_agg_orders values
  (1, 'ada', 'paid', 120.00, '2026-11-01'),
  (2, 'ada', 'paid', 35.50, '2026-11-03'),
  (3, 'bob', 'refunded', 80.00, '2026-11-03'),
  (4, 'cy', 'paid', 15.25, '2026-11-10'),
  (5, 'bob', 'pending', 60.00, '2026-11-12');
  ℹ No results (0 rows).

Count rows#

count counts the rows that match the filters; head: true skips the rows themselves:

import { createClient } from '@aurabase/aurabase-js'

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)

const all = await admin.from('qd_agg_orders').select('*', { count: 'exact', head: true })
const paid = await admin.from('qd_agg_orders').select('*', { count: 'exact', head: true }).eq('status', 'paid')
console.log('orders:', all.count, 'paid:', paid.count)

const members = await admin.from('orgs').select('slug, org_members(count)')
console.log('members per org:', JSON.stringify(members.data))
orders: 5 paid: 3
members per org: [{"slug":"acme","org_members":[{"count":2}]}]

table(count) inside select() counts the related rows of each row through a foreign key (Join tables and nest rows). To count per value of a column (orders per status), group in SQL.

Group in a view#

A view saves the group by query; you read it with from() and filter or sort it like a table:

create view qd_agg_by_status as
  select status,
         count(*)::int as orders,
         sum(amount) as total,
         round(avg(amount), 2) as average
  from qd_agg_orders
  group by status;
  ℹ No results (0 rows).
import { createClient } from '@aurabase/aurabase-js'

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)

const { data, error } = await admin.from('qd_agg_by_status').select('status, orders, total, average').order('total', { ascending: false })
console.log(data, error)

const paid = await admin.from('qd_agg_by_status').select('total').eq('status', 'paid').single()
console.log('paid total:', paid.data)
[
  { status: 'paid', orders: 3, total: 170.75, average: 56.92 },
  { status: 'refunded', orders: 1, total: 80, average: 80 },
  { status: 'pending', orders: 1, total: 60, average: 60 }
] null
paid total: { total: 170.75 }

Aurabase creates views with security_invoker = true unless you set the option explicitly (Views and materialized views): a signed-in user who reads the view gets figures computed on the rows its policies let it see, such as its own orders only. A filter on the view (eq('status', 'paid')) applies to the grouped rows, like having.

Aggregate in a function#

When the aggregate takes parameters (a date range, a customer), write a function that returns a table, and call it with rpc():

create function qd_agg_totals(p_since date)
returns table (customer text, orders int, total numeric)
language sql stable as $$
  select customer, count(*)::int, sum(amount)
  from qd_agg_orders
  where ordered_on >= p_since and status = 'paid'
  group by customer
  order by sum(amount) desc
$$;
  ℹ No results (0 rows).
import { createClient } from '@aurabase/aurabase-js'

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)

const { data, error } = await admin.rpc('qd_agg_totals', { p_since: '2026-11-02' })
console.log(data, error)
[
  { customer: 'ada', orders: 1, total: 35.5 },
  { customer: 'cy', orders: 1, total: 15.25 }
] null

To let signed-in users call it, grant execute on function qd_agg_totals(date) to aura_authenticated; the function runs with their rights, so their policies filter the rows it aggregates. See Call functions with rpc().

Refused requests#

Aggregate functions in select() are turned off on the REST API of every project:

import { createClient } from '@aurabase/aurabase-js'

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)

const r = await admin.from('qd_agg_orders').select('status, amount.sum()')
console.log(r.error?.status, r.error?.code, r.error?.message)
400 POSTGREST_ERROR Use of aggregate functions is not allowed

POST /v1/db/{table}/aggregate takes a MongoDB aggregation pipeline. It requires the service_role key on every project, and a PostgreSQL project refuses it:

for key in "$AURABASE_ANON_KEY" "$AURABASE_SERVICE_ROLE_KEY"; do
  curl -s -X POST "$AURABASE_URL/v1/db/qd_agg_orders/aggregate" \
    -H "apikey: $key" -H 'content-type: application/json' -d '[{"$match": {}}]' \
    | node -e 'const e = JSON.parse(require("fs").readFileSync(0, "utf8")).error; console.log(e.code, "-", e.message)'
done
FORBIDDEN - Forbidden: Aggregation is reserved to the service_role role
BAD_REQUEST - Invalid request: Pipeline aggregation is specific to MongoDB: it is not available on a 'postgres' project. Use `?select=` with aggregate functions (count/sum/avg/min/max) or `POST /v1/db/{project_id}/raw` for SQL.

The second message suggests ?select= aggregates, which are turned off as shown above: use a view, a function, or SQL from a server.

Large tables#

An aggregate reads every row it groups. On a large table:

  • index the columns of where and group by (Indexes);
  • for figures that may be a few minutes old (dashboards), store them in a materialized view and refresh it from your code (Views and materialized views); revoke it from the anon key, since a materialized view has no row level security;
  • for a total shown next to a list, count: 'planned' avoids a full count (Paginate and count rows).

Result#

select status, orders, total from qd_agg_by_status order by status
  orders │ status   │ total
  ───────┼──────────┼───────
  3      │ paid     │ 170.75
  1      │ pending  │ 60.0
  1      │ refunded │ 80.0

  ℹ 3 row(s).

Common errors#

MessageCauseFix
400 POSTGREST_ERROR Use of aggregate functions is not allowedsum(), avg(), count()… in select().Use a view or a function.
403 FORBIDDEN Forbidden: Aggregation is reserved to the service_role role/aggregate with the anon key or a user token.Not available for apps; use a view or a function.
400 BAD_REQUEST … Pipeline aggregation is specific to MongoDB …/aggregate on a PostgreSQL project.Use a view, a function or SQL.
column "…" must appear in the GROUP BY clause or be used in an aggregate functionA selected column is neither grouped nor aggregated.Add it to group by, or aggregate it.

Clean up#

aura db raw "drop function if exists qd_agg_totals(date); drop view if exists qd_agg_by_status"
aura db raw "drop table qd_agg_orders"
  ℹ No results (0 rows).
  ℹ No results (0 rows).

See also#

@aurabase/aurabase-js@0.7.5 · aura@0.3.4↗ Report a problem