0

How to perform the switch CASE statement on the PostgreSQL, PL/pgSQL?

Currently we may right a IF block like this:

IF boolean THEN
    statements;
ELSE 
IF boolean THEN
    statements;
ELSE 
   statements;
END IF;
END IF;

However it is not desired for several cases. Then a better approach would be use something close to the usual switch statements.

Related threads:

  1. PostgreSQL IF statement
Community
  • 1
  • 1
Evandro Coan
  • 8,560
  • 11
  • 83
  • 144
  • 2
    Note that you can use an ELSIF statment instead of two seperate IF/ELSE/END IF statements for your example. – danjuggler Nov 28 '16 at 23:34

2 Answers2

2

In order to mimic a switch statement, put the switch value directly after "CASE" before the "WHEN". Every when statement will check to see if it's value equals the CASE value.

Example using the specialized case statement to return hex color values for color words:

DO $$ 
DECLARE
  test_color varchar;
  hex_color varchar;
BEGIN
  test_color := 'blue';
  hex_color :=
    CASE test_color
      WHEN 'red' THEN
        '#FF0000'
      WHEN 'blue' THEN
        '#0000FF'
      WHEN 'yellow' THEN
        '#FFFF00'
      ELSE --we do not use that color, replace with white
        '#FFFFFF'
    END;
END $$

I'm not able to test the anonymous block on my computer so here's a straight SQL statement I've tested to work which can be used in an anonymous block:

SELECT
    CASE 'blue'
      WHEN 'red' THEN
        '#FF0000'
      WHEN 'blue' THEN
        '#0000FF'
      WHEN 'yellow' THEN
        '#FFFF00'
      ELSE --we do not use that color, replace with white
        '#FFFFFF'
    END;
danjuggler
  • 1,261
  • 2
  • 21
  • 38
0

The basic/base structure for the PL/pgSQL CASE with anonymous code block procedure block is:

DO $$ BEGIN
    CASE
        WHEN boolean-expression THEN
          statements;
        WHEN boolean-expression THEN
          statements;
        ...
        ELSE
          statements;
    END CASE;
END $$;

References:

  1. http://www.postgresql.org/docs/current/static/sql-do.html
  2. https://www.postgresql.org/docs/current/static/plpgsql-control-structures.html
Evandro Coan
  • 8,560
  • 11
  • 83
  • 144