sqloracle-databaseplsqlto-date

how to get the year from the max date in oracle sql


I am trying to get yyyy from the below query it is throwing error if i try to use the

Query

WITH last_startdate
     AS (SELECT owner,
                package_name,
                Max(start_date) MAX_START_DATE,
                to_date(max(start_date),'YYYY') as max_start_date_yr
         FROM   (SELECT DISTINCT owner,
                                 object_name AS PACKAGE_NAME
                 FROM   dba_procedures

                ) P
                JOIN SCHEMA.table_name A /*AUDITING TABLE*/
                  ON P.package_name = A.task_name
         GROUP  BY P.owner,
                   P.package_name)
SELECT *
FROM   last_startdate
ORDER  BY 3 DESC 

Error

ORA-01830: date format picture ends before converting entire input string
01830. 00000 -  "date format picture ends before converting entire input string"
*Cause:    
*Action:

Expected Result

OWNER PACKAGE_NAME MAX_START_DATE MAX_START_DATE_YR
STAGE PA_AB_CDS    19.02.2021     2021
EDW   PA_BX_BCS    09.12.2020     2020
MART  PA_WQ_AFD    12.08.2019     2019
CODE  PA_WQ_IOD    23.05.2016     2016

any suggestion to get the expected results ?


Solution

  • start_date is a DATE I suppose. So max(start_date) is a date, too.

    Why then do you apply to_date on it? Convert the date into a date? That makes no sense. You my want want to_char instead

    to_char(max(start_date),'YYYY') as max_start_date_yr
    

    which would give you the year in a string. Or just use EXTRACT to get the numeric year:

    extract(year from max(start_date)) as max_start_date_yr