28

Can't we use CASE condition outside SQL SELECT statements?

E.g.:

CASE 
  WHEN old.applies_to = 'admin' THEN _applies_to = 'My Self'
  ELSE _applies_to = initcap(old.applies_to)
END
 _summary = _summary || '<li>Apply To: ' || _applies_to || '</li>';

I get the following error:

ERROR:  syntax error at or near "_summary"
LINE 86: _summary = _summary || '<li>Apply To: ' || _applies ...

1 Answer 1

45

This concerns the conditional control structure CASE of the procedural language PL/pgSQL, to be used in PL/pgSQL functions, procedures, or DO statements.
Not to be confused with the CASE expression of SQL. Different language! Subtly different syntax rules.

While SQL CASE can be embedded in SQL expressions inside PL/pgSQL code, you cannot have stand-alone SQL CASE expressions (would be nonsense).

-- inside a plpgsql code block:
CASE 
   WHEN old.applies_to = 'admin' THEN
      _applies_to := 'My Self';
   ELSE
      _applies_to := initcap(old.applies_to);
END CASE;

You must use PL/pgSQL statements, terminated with a semicolon (;) and END CASE; to close it.

Is ELSE required?

PL/pgSQL CASE expects an ELSE branch and raises an error if it's missing when reached. The manual:

If no match is found, the ELSE statements are executed; but if ELSE is not present, then a CASE_NOT_FOUND exception is raised.

You can use an empty ELSE:

CASE 
   WHEN old.applies_to = 'admin' THEN
      _applies_to := 'My Self';
   ELSE
      --  do nothing
END CASE;

This is different for SQL CASE where ELSE is optional. If the ELSE keyword is present an expression must be given. Without ELSE, it defaults to NULL. Like:

CASE WHEN old.applies_to = 'admin' THEN 'My Self'
  -- ELSE null  -- optional
END;
Sign up to request clarification or add additional context in comments.

9 Comments

Thank you very much for your quick support Erwin. Very much appreciate it.
Another small question Erwin. Accroding to documentation ELSE condition of CASE statement is optional. But when I try to run series of WHEN conditions with statements without ELSE, Query browser giving me errors. ERROR: case not found. HINT: CASE statement is missing ELSE part. If you need I'll post relevant script part.
@Yohan: Please see additional answer.
@Yohan: It would be unwise to skip the ELSE clause. Always include it. Raise an exception with an informative msg. in the ELSE clause if it should not occur.
@Brandstetter: Thanks for the advice. I have change the logic as you suggest.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.