Why are CASE-expressions in the list documenting operator precedence?
سؤال
In the list here:
https://mariadb.com/kb/en/operator-precedence/
case-expressions are put at the same precedence level as BETWEEN
, between the NOT
operator and the comparison operators.
However, case-expressions always begin with CASE
and end with END
, and all subexpressions are also delimited by the CASE
keywords. They're like parenthetical expressions, so I don't understand why case-expressions are on this list.
Is there an SQL expression that would be parsed differently if the case-expression precedence was set higher or lower?
To give an example, with 2 + 3 * 4
, we get different results when parentheses are used in these 2 ways: 2 + (3 * 4)
and (2 + 3) * 4
. This question is about how it's impossible to do the same with CASE
. One can't substitute the use of +
for CASE
and show 2 different uses of parentheses such that the result differs between them.
To compare with other RDBMSes, neither SQLite nor PostgreSQL include CASE
in their operator precedence lists.
المحلول
The documentation is like that because it's an accurate reflection of this part of the source code:
%left OR_SYM OR2_SYM
%left XOR
%left AND_SYM AND_AND_SYM
%left PREC_BELOW_NOT
%left NOT_SYM
%left BETWEEN_SYM CASE_SYM WHEN_SYM THEN_SYM ELSE
%left '=' EQUAL_SYM GE '>' LE '<' NE IS LIKE SOUNDS_SYM REGEXP IN_SYM
%left '|'
%left '&'
%left SHIFT_LEFT SHIFT_RIGHT
%left '-' '+' ORACLE_CONCAT_SYM
%left '*' '/' '%' DIV_SYM MOD_SYM
%left '^'
%left MYSQL_CONCAT_SYM
%left NEG '~' NOT2_SYM BINARY
That's despite how the parser behaves. Despite how, for example, 1 + NOT 0
raises a syntax error for following an operator of high precedence with one of lower precedence, 1 + CASE WHEN 1 THEN 1 END
doesn't raise a similar syntax error for the same reason. Any expression involving CASE
treats it as an operator of the highest precedence.
I'm left wondering now why the source code is expressed like that despite it not behaving like that. Unfortunately, I lack knowledge of bison to make sense of this discrepancy without investing more time in this curiosity.