Q:

get the previous last date of the month in oracle sql

I have below query which is taking the last date of the month when this query is running on the current month. But as i am going to use this query in stored procedure and this procedure will run may be on the 1st or 2nd or 3rd of the current month then in this case i want to take the previous last month date everytime. For example if the query runs on 2nd or 3rd february then it will return the date with 31st January which is previous month last date.
The C_DATE column is date datatype
Select * from C_LOG
WHERE C_DATE = LAST_DAY(to_date(sysdate,'YYYYMMDD'))-1

A:

You can use EXTRACT( DAY FROM SYSDATE ) to get the current day of the month. If this is below your threshold then you can get the last day of the previous month otherwise use the last day of the current month:
SELECT *
FROM   C_LOG
WHERE  C_DATE = CASE
                WHEN EXTRACT( DAY FROM SYSDATE ) <= 3
                THEN TRUNC( SYSDATE, 'MM' ) - INTERVAL '1' DAY
                ELSE LAST_DAY( TRUNC( SYSDATE ) )
                END

Note:
Do not use to_date(sysdate,'YYYYMMDD') since TO_DATE( date_string, format_model ) takes a string as its first argument so Oracle will implicitly cast the date to a string; effectively doing:
TO_DATE(
  TO_CHAR(
    SYSDATE,
    ( SELECT value FROM NLS_SESSION_PARAMETERS WHERE parameter = 'NLS_DATE_FORMAT' )
  ),
  'YYYYMMDD'
)

If the NLS_DATE_FORMAT is not YYYYMMDD then the query will fail. Since this is a session parameter, each user can change it at any time and your query will fail for any user who changes that parameter without ever changing sql of the query.
Instead, if you want to remove the time component of a DATE data type, use the TRUNC function.

