Any difference between “current row” and “0 preceding/following” in windowing clause of Oracle analytic functions?

StackOverflow https://stackoverflow.com/questions/379643

  •  22-08-2019
  •  | 
  •  

Question

Some of Oracle's analytic functions allow for a windowing clause to specify a subset of the current partition, using keywords like "unbounded preceding/following", "current row", or "value_expr preceding/following" where value_expr is a physical or logical offset from the current row or value (depending on whether you have specified ROW or RANGE, respectively).

Here is an example using scott/tiger that displays employees in dept 30, and a count of the number of employees in their dept hired before them (including themselves):

select deptno, 
       empno,
       hiredate,
       count(*) over (partition by deptno 
                          order by hiredate
                          range between unbounded preceding and current row) cnt_hired_before1,
       count(*) over (partition by deptno 
                          order by hiredate
                          range between unbounded preceding and 0 preceding) cnt_hired_before2
  from emp
 where deptno = 30
 order by deptno, hiredate;

...can anyone provide an example or documentation where "current row" is different than "0 preceding/following"? It just seems like syntactic sugar to me...

Was it helpful?

Solution

It doesn't really matter which you use. They are two different ways of expressing the windowing, but the optimizer will perform the query the same way. The term "current row" is one that is common to multiple databases with analytic functions, not just Oracle. It's more of a stylistic difference, in the same way that some people prefer count(*) over count(1).

OTHER TIPS

The Oracle documentation that I have to hand (Oracle 9.2) says:

If you specified RANGE:

  • value_expr is a logical offset. It must be a constant or expression that evaluates to a positive numeric value or an interval literal.

This implies that you shouldn't really be using 0 since it isn't a positive numeric value. But, obviously it is possible to use 0 preceding/following since you are.

It is all about what you're trying to accomplish. You may want to use RANGE BETWEEN/ROWS BETWEEN use it to find LAST_VALUE within the sub-set or compare things within a sub-set. But most certainly you don't need for the example you provided.

    select deptno, 
       empno,
       hiredate,
       count(*) over (partition by deptno, trunc(hiredate,'mm')) cnt_same_month
  from emp
 where deptno = 30
 order by deptno, hiredate
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top