Monetary Type (PostgreSQL)
The PostgreSQL extension provides the same monetary type with identical semantics.
Installation
Section titled “Installation”CREATE EXTENSION pg_monetary;Basic Usage
Section titled “Basic Usage”SELECT '100 EUR'::monetary AS value;Arithmetic
Section titled “Arithmetic”SELECT '100 EUR'::monetary + '50 EUR'::monetary AS sum;Currency mismatch raises an error:
SELECT '100 EUR'::monetary + '50 USD'::monetary;-- ERROR: Cannot add monetary values with different currenciesCurrency Functions
Section titled “Currency Functions”SELECT currency_for_country('US'); -- USDSELECT currency_for_country('DE'); -- EURSELECT countries_for_currency('EUR');Aggregates
Section titled “Aggregates”Sum monetary values:
SELECT SUM(amount::monetary)FROM transactionsWHERE currency = 'EUR';Comparison
Section titled “Comparison”SELECT '100 EUR'::monetary > '50 EUR'::monetary; -- trueComparing different currencies errors:
SELECT '100 EUR'::monetary > '50 USD'::monetary;-- ERROR: Cannot compare monetary values with different currenciesIndexing
Section titled “Indexing”Create indexes on monetary columns:
CREATE INDEX idx_amount ON transactions (amount);Migration from MONEY type
Section titled “Migration from MONEY type”PostgreSQL’s built-in MONEY type is locale-dependent and problematic. Migrate:
ALTER TABLE orders ADD COLUMN amount_new monetary;
UPDATE ordersSET amount_new = (amount::numeric || ' ' || currency)::monetary;
ALTER TABLE orders DROP COLUMN amount, DROP COLUMN currency;
ALTER TABLE orders RENAME COLUMN amount_new TO amount;