tags:

views:

751

answers:

5

Oracle is giving me an error (ORA-00907: missing right parenthesis) when I run this query:

select * 
from reason_for_appointment 
where reason_for_appointment_id in 
(
    select reason_for_appointment_id 
    from appointment_reason 
    where appointment_id = 11 
    order by appointment_reason_id
)

However, when I run just the subquery, there's no error.

Can anyone explain what the problem is?

+10  A: 

The inner query results will never be displayed, so theres no point in doing the order by in the nested select. Apply it to the outer query instead.

StingyJack
+2  A: 

The problem is that ORDER BY is not permiited inside a subquery like this one. Why did you want to have one?

Tony Andrews
I'm guessing he wants the output ordered by the ID field. See my answer for how to do that.
Dave Costa
+1  A: 

It looks like you're wanting to display the results from one table using an ordering defined in another table. An inner join should suffice.

select reason_for_appointment.*
from reason_for_appointment rfa, appointment_reason ar
where rfa.reason_for_appointment_id = ar.reason_for_appointment_id
and ar.appointment_id = 11
order by ar.appointment_reason_id;
darreljnz
No, that's not always true. IN can be recast as a join IF AND ONLY IF the column in the IN clause has a unique constraint. If there are 27 rows with reason_for_appointment_id of "1" in appointment_reason You'll get 27 rows in the result with a join but only 1 with an IN. You people scare me.
A: 

select * from reason_for_appointment where reason_for_appointment_id in (select reason_for_appointment_id from appointment_reason where appointment_id = 11 order by appointment_reason_id)

try something like: with auxiliar as (select reason_for_appointment_id from appointment_reason where appointment_id = 11 order by appointment_reason_id) select reason_for_appointment_id from appointment_reason where reason_for_appointment_id in (select reason_for_appointment_id from auxiliar)

A: 

If your goal is to have the output ordered, you simply want to move the ORDER BY outside of the subquery:

select * from reason_for_appointment where reason_for_appointment_id in
 (select reason_for_appointment_id from appointment_reason where appointment_id = 11)
 order by reason_for_appointment_id

( I'm assuming that where you wrote "appointment_reason_id" you meant "reason_for_appointment_id". If there really are two different columns with these names ... ouch.)

Dave Costa