Skip to content
Advertisement

Filter a case in a where clause

I want to filter on a case statement in my where clause for example:

Select
    name,
    address,
    case when code in (50000-8113, 512388-8114) then ‘M345’ else ‘N/A’ end as Mucode
Where mucode = ‘M345’

The above does not work.

Advertisement

Answer

I assume you have a from clause

Select
    name,
    address,
    case when code in (50000-8113, 512388-8114) then ‘M345’ else ‘N/A’ end as Mucode
From someTable
Where mucode = ‘M345’

If you can’t change the columns, then you have to repeat the code:

Select
    name,
    address,
    case when code in (50000-8113, 512388-8114) then ‘M345’ else ‘N/A’ end as Mucode
From someTable
Where case when code in (50000-8113, 512388-8114) then ‘M345’ else ‘N/A’ end = ‘M345’

But whenever I see duplicated code like that, I like to move it to a cross apply:

select       name, address, mucode
from         someTable
cross apply (select mucode = 
                case 
                when code in (50000-8113, 512388-8114) then ‘M345’ 
                else ‘N/A’ 
                end
            ) ap
where       mucode = ‘M345’
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement