Home » SQL & PL/SQL » SQL & PL/SQL » ORDER BY
ORDER BY [message #2514] Mon, 22 July 2002 21:42 Go to next message
mary
Messages: 19
Registered: November 1999
Junior Member
Why do I receive error in the following SQL statement?
SELECT ename
FROM emp
WHERE job = 'SALESMAN'
UNION
SELECT ename
FROM emp
WHERE job = 'CLERK'
ORDER BY empno desc

After I include the column name in which I'll sort the result the SQL below worked:
SELECT empname, empno
FROM emp
WHERE job = 'SALESMAN'
UNION
SELECT empname, empno
FROM emp
WHERE job = 'CLERK'
ORDER BY empno desc

But why does the following SQL also works:
SELECT ename
FROM emp
WHERE job = 'SALESMAN'
ORDER BY empno desc
Re: ORDER BY [message #2515 is a reply to message #2514] Mon, 22 July 2002 22:08 Go to previous messageGo to next message
Maaher
Messages: 7065
Registered: December 2001
Senior Member
In fact, the ORDER BY clause in your first and second select refers to the entire select (including the UNION).
I'll try to explain:
Oracle first creates internally a sort of "temporary view" using the select with the union. Then, after getting the result of this select, Oracle will sort it, according to you ORDER BY clause. But, in the first case, Oracle won't find the EMPNO column in it's result set. In the second SELECT, you've included the column so it won't pose anymore problem. The third case is a single select, which doesn't cause such a "temporary view" (in fact, it is more like a subset in the memory) to be created. Oracle is well aware of the description of the table.

You might wonder why this mechanism works like that. Well, with a UNION you can perform a select over different tables. Look at the example below:
SQL> select empno
  2    from emp
  3   union
  4  select deptno
  5    from dept;

     EMPNO
----------
         1
        10
        12
....
....
      7902
      7934

22 rows selected.



The description of the two tables is different, yet Oracle manages to perform the requested task. As long as the number and datatype of both select match, there's no problem. But the drawback is that you won't be able to use the sort of a column that isn't in the select list.

HTH,
MHE
Re: ORDER BY [message #2569 is a reply to message #2514] Sun, 28 July 2002 18:05 Go to previous message
mary
Messages: 19
Registered: November 1999
Junior Member
Thanks a lot Maaher.
Previous Topic: A strange problem
Next Topic: Re: Creating a user in a stored procedure - compile error
Goto Forum:
  


Current Time: Tue Apr 23 05:15:04 CDT 2024