0
select 
    * 
from emp 
where id 
    (select order
    from department
    where name = 'testing'
    order by order asc)

I am getting ordered data from the inner query and with the id's I get I should get the result from the emp table to be in the same order as the inner query.

philipxy
  • 14,867
  • 6
  • 39
  • 83
Vijay
  • 71
  • 1
  • 2
  • 11
  • 2
    I think you've dropped an `in` between `id` and `(`. This would be better done as an inner join rather than a subquery - would that be a reasonable change? The only way to deterministically determine the order of the results from a query is to have an `ORDER BY` on the outermost `SELECT` statement. – Damien_The_Unbeliever Sep 30 '13 at 08:45
  • Does this answer your question? [Is order by clause allowed in a subquery](https://stackoverflow.com/questions/2101908/is-order-by-clause-allowed-in-a-subquery) – philipxy Apr 06 '23 at 06:09

5 Answers5

2

If it's reasonable to re-write your query as a join:

select e.*
from emp e
inner join department d
    on e.id = d.order
where d.name = 'testing'
order by d.order asc

Where this would change your results is if there are multiple rows in department with the same order value matching one or more rows in emp - in which case this query will return multiple rows, whereas the original would not. But if such a condition doesn't apply, then this is the query I'd recommend.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
1

Damien's answer is quite cool and perfect. but if you still want to go with subquery then try this

select * 
from emp 
where id in (select order from department where name = 'testing' order by order asc) 
order by id asc

May this help you

Vikash Singh
  • 804
  • 1
  • 10
  • 11
1

This will give the right number of rows in case there more than 1 match between emp.id and department.order

select * from emp e
where exists
(select 1 from department d where d.name = 'testing' 
and e.id = d.order1) -- order is a reserved word in several sql languages
order by id

It seems there is something funny going on between your tables. Would would department contain any information about emp(I assume it is employee table) ?

t-clausen.dk
  • 43,517
  • 12
  • 59
  • 92
0

There is no guarantee that there is an actual temporary table with the inner query and that it is sorted and processed in a certain way. However, you can sort the outer query by emp.id.

select * from emp where id in 
     (select order from department where name = 'testing')
order by id asc
Lorenzo Gatti
  • 1,260
  • 1
  • 10
  • 15
0
select e.* from emp as e, department d where e.id=d.order and d.name='testing' order by d.order 
senthilkumar2185
  • 2,536
  • 3
  • 22
  • 36