Let’s consider the database table for currency conversion looks as below:
fromCurrency | toCurrency | effective date | conversion rate |
---|---|---|---|
USD | INR | 1-Mar-2024 | 80 |
USD | INR | 1-Jan-2024 | 85 |
USD | GBP | 1-Oct-2023 | .80 |
USD | GBP | 1-Mar-2024 | .85 |
USD | AUD | 1-Mar-2023 | 1.55 |
USD | AUD | 1-Mar-2024 | 1.60 |
If database is queried on 1-Feb-2024, to get the conversion rate where fromCurrency=’USD’, it should return
fromCurrency | toCurrency | effective date | conversion rate |
---|---|---|---|
USD | INR | 1-Jan-2024 | 85 |
USD | GBP | 1-Oct-2023 | .80 |
USD | AUD | 1-Mar-2023 | 1.55 |
The same query on 15-April-2024 should return
fromCurrency | toCurrency | effective date | conversion rate |
---|---|---|---|
USD | INR | 1-Mar-2024 | 80 |
USD | GBP | 1-Mar-2024 | .85 |
USD | AUD | 1-Mar-2024 | 1.60 |
Basically for all possible combinations of (fromCurrency, toCurrency) there many many records in the database and on a particular date when the database is queried only one of those many records is applicable based on the effective date. I am trying to figure out the best possible postgres query to get the records.
3
Answers
Try the following PostgreSQL query to get the applicable conversion rates based on the query date (or pickup system date):
I have kept effective_date and from_currency configurable, which you might want to change (ie. pickup system date) as needed.
My Fiddle for this to play around.
Both in jOOQ and native PostgreSQL, you can use
DISTINCT ON
, which is a clause where you can request only the first record perDISTINCT ON
expression, given theORDER BY
clause:With SQL:
With jOOQ:
See this db-fiddle
Here is a query that can get you the conversion rate on a specific system date. If you don’t want to use the system date, you are going to need to replace current_date, with a parameter.