Skip to content
Advertisement

SQL Case Statement: Set the default value for an Case

this time I need an explanation for SQL. I have seen on the internet now nothing special and maybe I have a thinking error.

I have a case statement and now I want to ” filter ” it in different ways. Specifically I have a question, whether it is possible to provide rows directly with the “ELSE Value” of the case, without writing this itself?

The example is with the word “Pflaume”, this contains the letter ‘e’ and is therefore recognized by the ‘e’ case. But I want to assign the DEFAULT value ‘default’ to this case.

Thank you and have a nice day

SELECT 
  ID_NR AS Names
, CASE 

   WHEN ROB_ARTIKEL.ID_NR = 'Pflaumen' THEN  'Bitte nicht'
   WHEN ROB_ARTIKEL.ID_NR LIKE '%Z%'   THEN  'Hat ein Z'
   WHEN ROB_ARTIKEL.ID_NR LIKE '%e%'   THEN  'Hat ein e'
   WHEN ROB_ARTIKEL.ID_NR LIKE '%n%'   THEN  'Hat ein n'   
   WHEN ROB_ARTIKEL.ID_NR LIKE '%w%'OR ROB_ARTIKEL.ID_NR LIKE '%K%'  THEN 'Ist ne Kiwi'
  
   ELSE 'default'

  END AS BUCHSTABEN_CASE
  
FROM ROB_ARTIKEL

    NAMES      BUCHSTABEN_CASE
--------------------------------
1   Zitronen   Hat ein Z
2   Gurken     Hat ein e
3   Äpfel      Hat ein e
4   Bananen    Hat ein e
5   Birnen     Hat ein e
6   Pflaumen   Bitte nicht
7   Kirschen   Hat ein e
8   Erdbeeren  Hat ein e
9   Kiwi       Ist ne Kiwi

Advertisement

Answer

Since cases are tested in order, you can check for this case before the LIKE '%e%' case.

CASE 

   WHEN ROB_ARTIKEL.ID_NR = 'Pflaumen' THEN  'Bitte nicht'
   WHEN ROB_ARTIKEL.ID_NR LIKE '%Z%'   THEN  'Hat ein Z'
   WHEN ROB_ARTIKEL.ID_NR = 'Pflaume' THEN 'default'
   WHEN ROB_ARTIKEL.ID_NR LIKE '%e%'   THEN  'Hat ein e'
   WHEN ROB_ARTIKEL.ID_NR LIKE '%n%'   THEN  'Hat ein n'   
   WHEN ROB_ARTIKEL.ID_NR LIKE '%w%'OR ROB_ARTIKEL.ID_NR LIKE '%K%'  THEN 'Ist ne Kiwi'
  
   ELSE 'default'

In general, order your cases in order of specificity — put the exceptions first, then the general cases.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement