I am beginner in sql and this is the mysql code I was testing.
CREATE TABLE test (
id INT,
nm VARCHAR(16),
occ VARCHAR(16)
);
INSERT INTO test (id, nm, occ)
VALUES (1, "E", "X"), (2, "B", "X"), (3, "C", "Y"), (4, "D", "Z"), (5, "A", "Z");
SET @r1 = 0, @r2 = 0, @r3 = 0;
SELECT *,
CASE WHEN occ = 'X' THEN (@r1 := @r1 + 1)
WHEN occ = 'Y' THEN (@r2 := @r2 + 1)
WHEN occ = 'Z' THEN (@r3 := @r3 + 1) END AS rownumber,
CASE WHEN occ = 'X' THEN nm END AS X,
CASE WHEN occ = 'Y' THEN nm END AS Y,
CASE WHEN occ = 'Z' THEN nm END AS Z
FROM test
ORDER BY nm;
My question is as follows. If I remove the ORDER BY nm
clause what I get is this table below:
But if I add the clause I get the following table:
Why is the rownumber 1 in the row with nm = 'A'
in the second table after applying ORDER BY nm
? I would think it is 2 because I thought SELECT
takes precedence over ORDER BY
.