Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort query result without selecting that column but sort by that column?

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?

like image 233
Mr.Chowdary Avatar asked Jul 19 '12 05:07

Mr.Chowdary


People also ask

How do I sort by column not in SELECT?

Yes, you can order by a field(s)even if it is not your in your select statement but exists in your table. For a group by clause though you'd need it to be in your select statement. There's another exception, when you're using SELECT DISTINCT you must include the fields used in the GROUP BY clause in the select list.

Does ORDER BY column need to be in SELECT?

The column-Name that you specify in the ORDER BY clause does not need to be the SELECT list. An integer that identifies the number of the column in the SelectItems in the underlying query of the SELECT statement.

Can you sort a column using a column alias?

Sort Items Based on Host Variable Values You must specify fields in a CASE expression by column name. Column aliases and column numbers are not permitted in this context.


2 Answers

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
like image 193
jaychapani Avatar answered Oct 23 '22 11:10

jaychapani


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;
like image 22
archit agarwal Avatar answered Oct 23 '22 12:10

archit agarwal