Ask Your Question
4

What are the optimal methods to retrieve the initial and final date of the preceding month in Oracle?

asked 2021-05-02 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-09-12 15:00:00 +0000

david gravatar image

There are several methods to retrieve the initial and final date of the preceding month in Oracle:

  1. Using the SYSDATE function, subtracting the number of days in the current month and adding one day to get the initial date of the preceding month. Then, subtracting one day from the initial date of the current month to get the final date of the preceding month.

    SELECT TRUNC(SYSDATE, 'MM') - 1 AS LastDayOfPrecedingMonth, TRUNC(SYSDATE, 'MM') - EXTRACT(DAY FROM SYSDATE) + 1 AS FirstDayOfPrecedingMonth FROM DUAL;

  2. Using the ADDMONTHS function, subtracting one month and using the LASTDAY function to get the final date of the preceding month. Then, subtracting the number of days in the preceding month minus one from the final date to get the initial date of the preceding month.

    SELECT LASTDAY(ADDMONTHS(SYSDATE, -1)) AS LastDayOfPrecedingMonth, LASTDAY(ADDMONTHS(SYSDATE, -1)) - (TONUMBER(TOCHAR(LASTDAY(ADDMONTHS(SYSDATE, -1)), 'DD')) - 1) AS FirstDayOfPrecedingMonth FROM DUAL;

Both methods will return the same results.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-05-02 11:00:00 +0000

Seen: 13 times

Last updated: Sep 12 '21