Theodore
Theodore

Reputation: 67

How multiple CASE WHEN scenario works in SQL?

If in a query we have 2 case scenario satisfying the condition, which one will be picked by the SQL to show the output ?

sample Query :

    SELECT 
         CASE 
             WHEN field1 = 'a' THEN 1
             WHEN field2 = 'a' THEN 2
             ELSE 3
         END
    from table ;

Upvotes: 0

Views: 892

Answers (2)

As soon as a condition is true within your case conditions it will ignore all the later conditions.

If field1='a' then it will return 1 even if field2='a'. But if field1<>'a' and field2='a' then it will return 2 and only if field1 and field2 are both not 'a' then it will return 3.

I am assuming that field1 and field2 are column names.

Upvotes: 0

Ad Fortia
Ad Fortia

Reputation: 333

In SQL they will be evaluated in the order they are written so the first match wins.

Upvotes: 2

Related Questions