0

I receive an error which I don't understand. This is the part of the query in the WHERE clause which results in an error.

WHERE 
CASE so.console_role
WHEN 'NONE' THEN so.orderid = '512' 
ELSE so.console_id IN (select console_id from service_order where so.orderid 
= '512')

Error:

ERROR: syntax error at end of input LINE 118:

Have someone an idea? Thanks in advance.

5
  • 1
    A case expression is exactly that an expression that returns a value, it doesn't work like if. Commented Apr 12, 2018 at 12:37
  • 1
    It's generally better to use AND/OR constructions instead of case expressions in the WHERE clause. Commented Apr 12, 2018 at 12:38
  • 2
    BTW, your case has no end. Commented Apr 12, 2018 at 12:39
  • 2
    You need an end statement with this notation. Just a typo... Commented Apr 12, 2018 at 12:39
  • Argh stupid! I forgot the END. Thanks for the quick reply guys. I will look at the and/or construction, thanks for the tip. Commented Apr 12, 2018 at 12:47

1 Answer 1

2

Don't use case expressions in the where clause. Use boolean logic:

WHERE (so.console_role = 'NONE' AND so.orderid = '512'
      ) OR
      (so.console_role <> 'NONE' AND so.console_id IN (select console_id from service_order where so.orderid = '512')
      )

Note that this does not take NULL values into account for so_console_role, although that is trivial to add.

Also, I suspect the logic in the second part is not correct, and you intend:

WHERE (so.console_role = 'NONE' AND so.orderid = '512'
      ) OR
      (so.console_role <> 'NONE' AND so.console_id IN (select so2.console_id from service_order so2 where so2.orderid = '512')
      )

The where clause in your version of the subquery is referring to so in the outer query.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Gordon! Why is a 'case' expression not recommended?
@MauriceJansen . . . A case expression pretty much blocks efforts by the optimizer. In addition, boolean logic is sufficient to express the logic. In some rare cases, you want a case expression to control the order of evaluation, but that is unusual.
Clearly! Thanks again for the help and explanation.

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.