Using a variable period in an interval in Postgres

Use this line:

startDate TIMESTAMP := endDate - ($3 || ' MONTH')::INTERVAL;

and note the space before MONTH.
Basically: You construct a string with like 4 MONTH and cast it with ::type into a proper interval.

Edit: I’ have found another solution: You can calculate with interval like this:

startDate TIMESTAMP := endDate - $3 * INTERVAL '1 MONTH';

This looks a little bit nicer to me.

Leave a Comment