Occasionally in psql we need a function that returns the first and last day of the month for a given date. This seems simple, after all we know that the beginning of the month will always be '01', very different from the last day of the month which can vary depending on the month and year. In the function below we create a function that will return the first day of the month for a given date and return it in timestamp format. This function will work in conjunction with the function also explained in another article called... GET_LAST_DAY_OF_MONTH.
If you've ever had a need like this, the psql function below will solve your problem:
create or alter function GET_FIRST_DAY_OF_MONTH ( P_DATE_REF timestamp) returns timestamp as declare variable LCALC_DATE timestamp; begin -- Calculates the beginning of the month of the given date lcalc_date=:P_DATE_REF; select cast(:P_DATE_REF as date) - extract(day from cast(:P_DATE_REF as date)) + 1 from RDB$DATABASE into :lcalc_date; return :lcalc_date; end
How to use
select GET_FIRST_DAY_OF_MONTH(current_timestamp) as first_day_of_month from RDB$DATABASE
Imagine searching for the closing period of the current month:
select * from table a where a.dt_lancamento between GET_FIRST_DAY_OF_MONTH(current_timestamp) and GET_LAST_DAY_OF_MONTH(current_timestamp)
Conclusion
Functions to retrieve the start and end of the month may seem trivial at first, but trust me, when programming with psql you will have times when you need these dates to process something important that must be counted from the beginning of the month to its end, or both. For example, consider querying entries for a monthly period, from the 1st to the end of the month, including the time suffix 23:59:59 to avoid missing transactions from the last day. The fact that the function returns a timestamp will also help you with the index, which will not require a timestamp cast to date.