Reputation: 303
Output of
Query 1:
select id from users
order by case when DEVIATION_LEVEL=2863 then 1 else 2 end
is
800019
800030
800040
800003
800007
800015
800025
800026....etc
Output of Query 2:
select id from
(select id from users
order by case when DEVIATION_LEVEL=2863 then 1 else 2 end)
where rownum<=16;
is
800019
800030
800028
800020
800021
800018
800012
800161...etc
Why the order changes in 2nd query? Please suggest correct solution to just limit the size of the first query result.
Upvotes: 1
Views: 2627
Reputation: 61
ORDER BY
in a subquery does not guarantee the results; SELECT * FROM table ORDER BY 1;
is not same as SELECT * FROM (SELECT * FROM table ORDER BY 1);
Upvotes: 0
Reputation: 49082
The reason is that ORDER BY cannot guarantee the ordering on duplicate values.
In your query, put the DEVIATION_LEVEL
in the column list of the select and then you will understand that the order is just not same when they are duplicate values.
For example,
Query 1
SQL> SELECT empno, deptno FROM emp ORDER BY CASE WHEN deptno=10 THEN 1 ELSE 2 END;
EMPNO DEPTNO
---------- ----------
7782 10
7839 10
7934 10
7566 20
7654 30
7698 30
7900 30
7788 20
7369 20
7844 30
7876 20
7521 30
7499 30
7902 20
14 rows selected.
Query 2
SQL> SELECT empno, deptno
2 FROM
3 (SELECT empno, deptno FROM emp ORDER BY CASE WHEN deptno=10 THEN 1 ELSE 2 END
4 )
5 WHERE rownum<=5;
EMPNO DEPTNO
---------- ----------
7782 10
7934 10
7839 10
7369 20
7654 30
SQL>
So, the ordering in the second case when ROWNUM is applied, it is picked randomly among the similar values.
Look at the first three ordered rows:
Output 1
EMPNO DEPTNO
---------- ----------
7782 10
7839 10
7934 10
Output 2
EMPNO DEPTNO
---------- ----------
7782 10
7934 10
7839 10
ORDER BY deptno will not guarantee same order every time. In above query, if you want a particular order, then make an ORDER BY on another column too, i.e. empno.
ORDER BY empno, deptno
If you compare both the outputs, there is no guarantee that ordering will be same always since the deptno is same as 10 in all three rows. When you have similar values, and if you order them, it is just like picking them in random.
Upvotes: 2
Reputation: 1629
When you perform a SELECT query without an ORDER BY clause the order of the result is undetermined. If you want or need to have a consistent ordering behavior then use the ORDER BY clause at the top level SELECT.
There is however the exception in oracle when you are limiting the rows with the ROWNUM field. In that case the ROWNUM filter would reduce the result set before applying the order by clause, thus removing rows that should have come first.
select id from users
order by case when DEVIATION_LEVEL=2863 then 1 else 2, id;
and
select id from
(select id from users
order by case when DEVIATION_LEVEL=2863 then 1 else 2 end, id)
where rownum<=16;
Upvotes: 2