In ORACLE DB I dont understand why ORDER BY sometimes work and sometimes does not.
As well as I understand - the columns are always derived from the first subquery in the compound operator. In the case below we have last column amd
that we sort by:
SELECT 'Ala' col1, 123123 sal, 0.33 amd FROM DUAL
UNION
SELECT 'Ola' kol1, 12444 usd, 0.22 FROM DUAL
ORDER BY amd;
But adding extra union breaks everything:
SELECT 'Ala' col1, 123123 sal, 0.33 amd FROM DUAL
UNION
SELECT 'Ola' kol1, 12444 usd, 0.22 FROM DUAL
UNION
SELECT 'Ula' coll1, 12444 eur, NULL FROM DUAL
ORDER BY amd;
ORDER BY amd
*
ERROR at line 6:
ORA-00904: "AMD": invalid identifier
Even though amd is still the last column (SELECT without ORDER BY
):
SELECT 'Ala' col1, 123123 sal, 0.33 amd FROM DUAL
UNION
SELECT 'Ola' kol1, 12444 usd, 0.22 FROM DUAL
UNION
SELECT 'Ula' coll1, 12444 eur, NULL FROM DUAL;
COL SAL AMD
--- ---------- ----------
Ala 123123 .33
Ola 12444 .22
Ula 12444
Why is it so?
I know I should be using aliases for all columns or numeric positions, but I am prepping for an exam and would like to understand the inconsistency.
Note that parentheses do not solve the issue.