Pregunta

I need some information about processing order of the Searched CASE WHEN statement in SQL.

For example:

(CASE
     WHEN Cells.Type <> 'UOM' THEN 0
     WHEN Template_Colors.Uom_Case = 'ONE' THEN 1
     WHEN Template_Colors.Uom_Case = 'MUL' THEN 2
 END) AS CELL_WHAT_UOM

I need the result to be always 0, unless Cells.Type <> 'UOM'.

I know that SQL parsers usually proceed from the bottom to the top, but in Oracle the query seems to work correctly, so I suppose that WHEN clauses are processed in the order they are.

It is 100% guaranteed that the 0 case is processed before the others?

Or I have compulsorily to write:

(CASE
     WHEN Cells.Type <> 'UOM' THEN 0
     WHEN Cells.Type = 'UOM' AND Template_Colors.Uom_Case = 'ONE' THEN 1
     WHEN Cells.Type = 'UOM' AND Template_Colors.Uom_Case = 'MUL' THEN 2
 END) AS CELL_WHAT_UOM

...?

I need this information about Oracle 10g + SQL server 2008 r2 + Postgre.

¿Fue útil?

Solución

If Cells.Type is not equal to UOM, you're guaranteed that the result will be 0.

What you are not guaranteed (certainly in SQL Server) is that any expressions in the other branches will not be computed.

So, if you did the following:

CASE WHEN a = 0 THEN 0 ELSE 10/a END

You might get a division by zero error.


And, even in your example:

WHEN Cells.Type = 'UOM' AND Template_Colors.Uom_Case = 'ONE' THEN ...

There is no guarantee on the order in which predicates are evaluated, so Template_Colors.Uom_Case may still be accessed. Not sure what your concern is around whether this column is accessed or not, so no further advice to offer at the present moment.


SQL Server documentation:

  • Evaluates, in the order specified, Boolean_expression for each WHEN clause.

  • Returns result_expression of the first Boolean_expression that evaluates to TRUE.

  • If no Boolean_expression evaluates to TRUE, the Database Engine returns the else_result_expression if an ELSE clause is specified, or a NULL value if no ELSE clause is specified.

Oracle:

In a searched CASE expression, Oracle searches from left to right until it finds an occurrence of condition that is true, and then returns return_expr. If no condition is found to be true, and an ELSE clause exists, Oracle returns else_expr. Otherwise, Oracle returns null.

PostGre:

If the result is true then the value of the CASE expression is the result that follows the condition. If the result is false any subsequent WHEN clauses are searched in the same manner.

Ansi 92 (draft):

If the <search condition> of some <searched when clause> in a <case specification> is true, then the value of the <case specification> is the value of the <result> of the first (leftmost) <searched when clause> whose <search condition> is true, cast as the data type of the <case specification>.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top