Skip to content

Aggregate Functions

The extension provides aggregate functions that preserve currency type safety.

These functions require all values to have the same currency:

Sums monetary values:


          

Calculates the average:


          

Finds minimum and maximum values:


          

Aggregating different currencies throws an error:


          

To aggregate mixed currencies, use monetary_sum_converted.

Sums values after converting to a target currency:

monetary_sum_converted(value, target_currency, rate) → monetary

          

For dynamic rates from an exchange table:

-- Load rates
CREATE TABLE rates AS SELECT * FROM ecb_exchange_rates();
-- Join to get rates for conversion
WITH prices AS (
SELECT '100 EUR'::monetary AS price, 'EUR' AS curr UNION ALL
SELECT '100 USD'::monetary, 'USD' UNION ALL
SELECT '100 GBP'::monetary, 'GBP'
)
SELECT monetary_sum_converted(
price,
'EUR',
COALESCE(r.rate, 1.0)
) AS total_eur
FROM prices p
LEFT JOIN rates r ON r.currency_to = p.curr;
FunctionSame CurrencyDescription
monetary_sum(m)RequiredSum values
monetary_avg(m)RequiredAverage values
monetary_min(m)RequiredFind minimum
monetary_max(m)RequiredFind maximum
monetary_sum_converted(m, target, rate)NoSum with conversion

Aggregate functions work with GROUP BY: