Search code examples
sqlcaseteradataexistssql-tuning

teradata SQL tuning pundits - SELECT Failed. 3771: Illegal expression in WHEN clause of CASE expression


I am using a statement as below and get this error:

SELECT Failed. 3771: Illegal expression in WHEN clause of CASE expression.

I had better hopes from Teradata. SQL Server can do it but Teradata can't. How can I work around this? Any solution?

sel ( CASE
    WHEN  EXISTS   ( sel '1' from VolatileTable Dtb1 where Dtb1.c1=FACT_Table_5MillionRows.C1)
    THEN "FACTTablew5MillionRows"."CustomColumName" 
ELSE 'ALL OTHER'
END  ) (NAMED "CustomColumName" )

from
"Db"."FACTTablew5MillionRows" 

Solution

  • Teradata doesn't like EXISTS in Correlated Scalar Subqueries within a CASE, but you can rewrite it like this:

    select
      ( CASE
           WHEN C1 = ( select MIN(C1) from VolatileTable Dtb1 
                       where Dtb1.c1=ft.C1)
           THEN ft."CustomColumName" 
           ELSE 'ALL OTHER'
        END  ) (NAMED "CustomColumName" )
    from
    "Db"."FACTTablew5MillionRows" as ft
    

    If VolatileTable.C1 is unique you can remove the MIN.

    But in 95% logic like this can be replaced by a LEFT JOIN:

    select
       ft.*,
       CASE WHEN Dtb1.c1 IS NOT NULL 
            THEN ft."CustomColumName" 
            ELSE  'ALL OTHER' 
       end as "CustomColumName" 
    from "Db"."FACTTablew5MillionRows" as ft
    left join VolatileTable Dtb1 
    on Dtb1.c1=ft.C1
    

    This will return duplicated rows if VolatileTable.C1 is not unique, then you need to change it to:

    from "Db"."FACTTablew5MillionRows" as ft
    left join (select distinct C1 from VolatileTable) Dtb1 
    on Dtb1.c1=ft.C1