Calling aggregate functions with supabase-js #626
-
I'm new to Supabase, so apologies if I'm missing something here. I'm coming from Object/Knex, just having trouble translating what should be a simple query. Simplified schema as follows:
const { data, error, count } = await db
.from("payment_intents")
.select(`
*,
articles(*)
`, { count: "exact" })
.filter("articles.author_id", "eq", id) I'm trying to answer:
When running the count above, all Appreciate any help here! Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
You can resort to SQL functions if your query cannot be expressed purely in Right now, calling the Answering your questions:
create or replace function "TotalPaymentIntents"(author_id int)
returns bigint as $$
select
count(pi)
from articles a
join payment_intents pi on pi.article_id = a.id
where a.author_id = $1;
$$ language sql stable; // Then you can call it through supabase-js like:
const { data, error } = await db
.rpc("TotalPaymentIntents", { author_id: 1} )
create or replace function "TotalAmountCents"(author_id int)
returns float as $$
select
sum(pi.amount_cents)
from articles a
join payment_intents pi on pi.article_id = a.id
where a.author_id = $1;
$$ language sql stable; // Then you can call it through supabase-js like:
const { data, error } = await db
.rpc("TotalAmountCents", { author_id: 1} ) |
Beta Was this translation helpful? Give feedback.
-
Aggregation functions and inner joins in the Supabase JS SDK are currently supported! To run a query that counts the const { data, error } = await supabase
.from('payment_intents')
.select('count, amount_cents.sum()', {
count: 'exact'
})
.eq('articles.author_id', authorId) To use an inner join so payment intents without an article aren't included you would use the const { data, error, count } = await db
.from("payment_intents")
.select(`
*,
articles!inner(*)
`, { count: "exact" })
.filter("articles.author_id", "eq", id) |
Beta Was this translation helpful? Give feedback.
You can resort to SQL functions if your query cannot be expressed purely in
supabase-js
.Right now, calling the
sum
aggregate function and doing aninner join
(embedding is done through aleft join
) is not possible withsupabase-js
directly. These capabilities are being worked on though.Answering your questions: