Reputation: 175964
There is simple table:
CREATE TABLE tab AS
SELECT 1 AS t, 'G' AS company, 40 AS quote
UNION SELECT 2 , 'G', 60
UNION SELECT 3 , 'S', 60
UNION SELECT 4, 'S', 20;
And query:
SELECT DISTINCT company, quote ,LAG(quote) OVER(PARTITION BY company ORDER BY t)
FROM tab;
Output - result is consistent across RDBMSes.
+---------+-------+------+
| company | quote | lag |
+---------+-------+------+
| G | 40 | null |
| S | 60 | null |
| G | 60 | 40 |
| S | 20 | 60 |
+---------+-------+------+
But when I try to make some calculations I get different results:
SELECT DISTINCT company, quote - LAG(quote) OVER(PARTITION BY company ORDER BY t)
FROM tab;
PostgreSQL/SQL Server/Oracle (as I expected):
+---------+--------+
| company | result |
+---------+--------+
| G | null |
| G | 20 |
| S | null |
| S | -40 |
+---------+--------+
MariaDB/MySQL:
+----------+--------+
| company | result |
+----------+--------+
| G | null |
| S | null |
+----------+--------+
Now as far as I know Logical Query Processing
:
- FROM
- ON
- JOIN
- WHERE
- GROUP BY
- WITH CUBE/ROLLUP
- HAVING
- SELECT
- DISTINCT
...
DISTINCT
is after SELECT
so the correct way should be like PostgreSQL/SQL Server/Oracle.(Yes I know that I could use subquery/remove DISTINCT
but it is not the point of the question).
Is this behaviour a bug or is it working correctly(documentation)?
Upvotes: 9
Views: 2792
Reputation: 221106
Definitely a bug in both MySQL and MariaDB. I've reported the issue to the two databases, linking back to this Stack Overflow question:
Upvotes: 2