-2

The OPs request for an explanation of how the following works threw up a point which I'm uncertain of.

select sysdate + (interval_difference * 1440) - sysdate
  from (select systimestamp - (systimestamp - 1) as interval_difference
          from dual )

Namely, does a plus or a minus have operator precedence? The documentation1 lists the operator order as follows

+----------------------------+-------------------------------------------+
| Operator                   |Operation                                  |
+------------------------------------------------------------------------+
| +, - (as unary operators)  | Identity, negation, location in hierarchy |
| , PRIOR, CONNECT_BY_ROOT   |                                           |
+----------------------------+-------------------------------------------+ 
| *, /                       | Multiplication, division                  |
+----------------------------+-------------------------------------------+
| +, - (as binary operators) | Addition, subtraction, concatenation      |
| , ||                       |                                           |
+----------------------------+-------------------------------------------+

The query, once reduced, becomes date + interval - date. However, the interval - date part is invalid.

Does the operation work because the operator order of precedence places a binary plus above a binary minus or because Oracle's clever enough to know that one operation is invalid and the other isn't (i.e. it's been hacked for datetime/interval arithmetic)?

In other words, why is date + interval - date executed as (date + interval) - date and not as date + (interval - date)?

The documentation placing + before - might be construed to imply that a + does have precedence but this doesn't prove anything and the fact that this operation is successful might also prove something, save that it couldn't be if executed in any other way.

The information to hand points to + having precedence but it's all circumstantial. Is this provable one way or the other?

1. For 11.2 but the 10g and 9i documentation is, unsurprisingly, identical

4

1 回答 1

6

It is because + and - are both left-associative.

  • a + b + c means (a + b) + c.
  • a + b - c means (a + b) - c.
  • a - b + c means (a - b) + c. (And (3 - 2) + 1 != 3 - (2 + 1).)
  • a - b - c means (a - b) - c. (And (3 - 2) - 1 != 3 - (2 - 1).)

(The page that you link to actually mentions this:

Oracle evaluates operators with equal precedence from left to right within an expression.

though it's easy to miss if you don't know what to look for.)

于 2013-07-03T20:53:51.887 回答