Search code examples
sqloracleoracle-sqldeveloper

Between operator not working properly in sql


ERROR: ORA-01861: literal does not match format string 01861. 00000 - "literal does not match format string" *Cause: Literals in the input must be the same length as literals in the format string (with the exception of leading whitespace). If the "FX" modifier has been toggled on, the literal must match exactly, with no extra whitespace. *Action: Correct the format string to match the literal.

 SELECT
    
        SUM("ASSET")
    
    FROM  component WHERE "Extraction Date" = '20201231' AND  "Account Start Date"
    
         BETWEEN '20151221' AND ADD_MONTHS(to_date('20151221', 'YYYYMMDD'),3) ;

Solution

  • You're mixing strings and dates; that won't work. I presume that those "date" columns are, actually, strings - at least, that's how you treat them.

    This: ADD_MONTHS(to_date('20151221', 'YYYYMMDD'),3) returns a date value, so you'll have to convert it to a string with appropriate format mask. Therefore:

    select sum ("ASSET")
      from component
     where     "Extraction Date" = '20201231'
           and "Account Start Date" 
               between '20151221'
                   and to_char (add_months (to_date ('20151221', 'YYYYMMDD'), 3), 'yyyymmdd');
    

    If those columns are dates, then everything should be a date:

    select sum ("ASSET")
      from component
     where     "Extraction Date" =  date '2020-12-31'
           and "Account Start Date" 
               between date '2015-12-12' and add_months(date '2015-12-21', 3);  
    

    Also, note that we, working with Oracle, don't particularly like column names enclosed into double quotes, having spaces within. You, obviously, can have such a column names, but that's just too painful (from my point of view). You have to match letter case every time you work with them. So, I'd suggest (for the future)

    select sum (asset)
      from component
     where     extraction_date =  date '2020-12-31'
           and account_start_date
               between date '2015-12-12' and add_months(date '2015-12-21', 3);