Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display order of a SQL Query without order by clause

I am writing a simple query in SQL Server:

Select 
    EmpId, EmpName, Sal 
from 
    Emp 
where  
    EmpId in (10,9,5,7,3,8);

I want to get the output in a same order which is given i.e; 10,9,5,7,3,8

Actually whatever I'll give the result will display with given order without order by ascending or descending.

How can I do that? Please help.

like image 355
Shubhadeep Chattopadhyay Avatar asked Aug 13 '15 05:08

Shubhadeep Chattopadhyay


People also ask

Can we use ORDER BY without WHERE clause?

ORDER BY Characteristics: The ORDER BY clause is used to get the sorted records on one or more columns in ascending or descending order. The ORDER BY clause must come after the WHERE, GROUP BY, and HAVING clause if present in the query.

In what order do records appear when executing a SQL query without ORDER BY clause?

without an ORDER BY clause, you will have not asked exactly for a particular order, and so the RDBMS will give you those rows in some order that (maybe) corresponds with some coincidental aspect of the query, based on whichever algorithm the RDBMS expects to produce the data the fastest.

What can we use instead of ORDER BY in SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.


2 Answers

No way to do this natively. Try:

SELECT EmpId,EmpName,Sal
FROM Emp
WHERE EmpId IN (10,9,5,7,3,8)
ORDER BY CASE EmpId
    WHEN 10 THEN 1
    WHEN 9 THEN 2
    WHEN 5 THEN 3
    WHEN 7 THEN 4
    WHEN 3 THEN 5
    WHEN 8 THEN 6
    ELSE 7
END;
like image 64
rabudde Avatar answered Oct 19 '22 19:10

rabudde


You can use a table variable to pass the inputs. You must insert the records into this table variable in the desired order.

Declare @empids table(id int identity(1,1),empid int)
insert into @empids values(10),(9),(5),(7),(3),(8)

Select e.EmpId,e.empname,e.sal from Emp e
join @empids t on  e.EmpId = t.empid 
order by t.id

Try this.

like image 32
Jasqlg Avatar answered Oct 19 '22 17:10

Jasqlg