I have a simple table odd_nums
with columns num
and odd
:
create table odd_nums
(
num numeric,
odd numeric
);
INSERT INTO odd_nums VALUES (0, 0);
INSERT INTO odd_nums VALUES (1, 1);
INSERT INTO odd_nums VALUES (2, 0);
INSERT INTO odd_nums VALUES (3, 1);
I am playing around with window functions. This query produces the expected results:
SELECT num,
FIRST_VALUE(num) OVER (PARTITION BY odd) a,
FIRST_VALUE(num) OVER (PARTITION BY odd) b
FROM odd_nums;
num | a | b |
---|---|---|
0 | 0 | 0 |
2 | 0 | 0 |
1 | 1 | 1 |
3 | 1 | 1 |
When I order the partition in column b
the results change like this:
SELECT NUM,
FIRST_VALUE(num) OVER (PARTITION BY odd) a,
FIRST_VALUE(num) OVER (PARTITION BY odd ORDER BY num DESC) b
FROM odd_nums;
num | a | b |
---|---|---|
2 | 2 | 2 |
0 | 2 | 2 |
3 | 3 | 3 |
1 | 3 | 3 |
Column b
is what I would expect, but why is column a
changing as well?
Can someone help me understand why adding the ORDER BY num DESC
clause in the second window function causes a change in the first window function? Is there some specific database implementation detail or optimization that might be affecting the result?
I have looked through the PostgreSQL documentation but without success.