Skip to content

Instantly share code, notes, and snippets.

@AayushSameerShah
Last active December 8, 2021 11:16
Show Gist options
  • Select an option

  • Save AayushSameerShah/2a0217196e4eaca11357f157ea61e47b to your computer and use it in GitHub Desktop.

Select an option

Save AayushSameerShah/2a0217196e4eaca11357f157ea61e47b to your computer and use it in GitHub Desktop.
This file is dedicated to the case statement only

There are 2 types of CASE:

  1. General CASE
  2. CASE expression

General Syntax

-- General Syntax
CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    ELSE result3 AS abc
END

-- Example
SELECT col_1, col_2,
CASE 
    WHEN col_2 = 33 THEN 'Yes!'
    ELSE 'No!'
END
FROM table;

Returns:

col_1 col_2 case
12 33 Yes!
22 211 No!
32 33 Yes!

Expression Syntax

-- General Syntax
CASE column
    WHEN value1 THEN result1
    WHEN value2 THEN result2
    ELSE result3 AS abc
END

-- Example
SELECT col_1, col_2,
CASE col_2
    WHEN 33 THEN 'Yes!'
    ELSE 'No!'
END
FROM table;

Returns:

col_1 col_2 case
12 33 Yes!
22 211 No!
32 33 Yes!

So the difference

General Case Expression Case
So much flexible allows any condition Only allows the "equals to" condition
Need to write condition again and again for each case No repeated condition writing saves time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment