I have 3 tables. "Portfolios", "Balances" and "Positions". My users can save multiple portfolios, for each portfolio multiple balances and for each balance multiple positions.
Now I want to query for one portfolio with its balances and for each balances two sums (amount and fees).
My system will automatically filter for the current user.
I have following query:
CREATE OR REPLACE FUNCTION public.getBalancesWithStats(portfolioid bigint)
RETURNS TABLE(
id bigint,
name text,
portfolio_id bigint,
overall_amount double precision,
overall_fees double precision) AS $$
BEGIN
RETURN QUERY
SELECT balances.id
,balances.name
,balances.portfolio_id
,SUM(positions.amount) AS overall_amount
,SUM(positions.fee) AS overall_fees
FROM balances
LEFT JOIN positions ON positions.crypto_balance_id = balances.id
WHERE balances.portfolio_id = portfolioid
GROUP BY balances.id
,balances.name
,balances.portfolio_id;
END;
$$ LANGUAGE plpgsql;
I'm not sure if this would be a performance issue. A user has like 3 portfolios, 10-100 balances and 10 - 100k transactions, this is for sure the largest table.
The result should look like
id, name, overall_amount, overall_fees
Distinct/Grouped by id
Update
After I created two indexes:
create index balance_portfolio_id on balances(portfolio_id, id)
create index positions_balance_id on positions(crypto_balance_id, id)
and filled one portfolio with 1k balances and a balance with 1k positions and query the other portfolio with one balance and one position the balance switched to indexed scan but positions still seq scan. Before I created an index for positions there was a nested loop as well.
After I put another 10k balances and positions in one portfolio/balance it switched both to bitmap heap scan and Bitmap Index Scan.
I'm not sure what this means but it should be both index scan in the first step and the second bitmap does not say anything to me.
Can I improve my query even more? Thanks a lot guys!