14

I have a query, I have to sort the result from the DB2 database. The query will select the columns empname,salary,status. But I have to sort the result using order by empno
But the query is not working.. This is the query.

select empname, salary, status from emp where salary>5000 order by empno  

Can you update the query to sort by empno without using it in selecting columns?

Fabian Pijcke
  • 2,920
  • 25
  • 29
Mr.Chowdary
  • 3,389
  • 9
  • 42
  • 66

5 Answers5

12

Your syntax seems correct to me except dot(.) at the end. After removing dot if doesn't work...

Try something like

SELECT empname, salary, status
  FROM (SELECT   *
            FROM emp
        ORDER BY empno)
 WHERE salary > 5000
jaychapani
  • 1,501
  • 1
  • 13
  • 31
2

Another syntax that may be easier, depending on how you think about it is using the with keyword. This explicitly creates a named temporary table with the desired ordering, then queries from that. The order of the new query will be the same as the temporary tables ordering.

WITH temp_table AS (SELECT   *
            FROM emp
        ORDER BY empno)

SELECT empname, salary, status
  FROM temp_table
 WHERE salary > 5000;

The answer by @jaychapani is more concise and functionally does the same thing, but the with syntax is powerful for quite a few other use cases and visually separates the two, which can be helpful especially if you have a long subquery that does other things.

Halcyon
  • 1,376
  • 1
  • 15
  • 22
1

I used below query to solve this problem. In this case we can sort query result without displaying the column:

WITH temp_table
     AS (select distinct(s1.Name),s1.id
         from students s1
         where marks>75
         order by right(s1.Name ,3) asc,s1.id asc
        )

SELECT Name
  FROM temp_table;
fcdt
  • 2,371
  • 5
  • 14
  • 26
0

I'm not sure, but the fastest way on DB is something like this:

SELECT empname, salary, status
FROM (
    select empname, salary, status, empno 
    from emp 
    where salary > 5000 
    order by empno ASC
) 
Krzysiek
  • 615
  • 8
  • 19
-3

try this

select empname, salary, status from emp where salary>5000 order by empno asc

make sure that columns and table name really exist.

have a look at: ORDER BY clause

Best Regards

BizApps
  • 6,048
  • 9
  • 40
  • 62