tom
tom

Reputation: 215

Using rownum in sub query on oracle 11

I have query like this.It is working properly on oracle 12.

select * from customers where customerId IN (select custId from Orders where 
   orderStatus = 'S' and orderCity = 'Amsterdam' and ORDER BY custId DESC FETCH FIRST 10 ROWS ONLY)

But I am using oracle 11.That query is not working on oracle 11.Therefore I changed my query like that

select * from customers where customerId IN (select custId from Orders where 
  orderStatus = 'S' and orderCity = 'Amsterdam' and ORDER BY custId DESC rownum <= 10)

It gives missing right paranthesis

How can I solve this problem.Do you have any idea?Actually I use a variable instead on 10 number.

Upvotes: 1

Views: 646

Answers (2)

GMB
GMB

Reputation: 222392

I would phrase this with exists and row_number():

select c.* 
from customers 
where exists (
    select 1
    from (
        select custId, row_number() over(order by custid desc) rn
        from orders 
        where orderStatus = 'S' and orderCity = 'Amsterdam'
    ) o
    where o.rn <= 10 and o.cusid = c.customerid
)

row_number() ranks orders by descending customer id in the subquery. Then, we filter on the first 10 rows, and use exists to filter the corresponding rows in the outer query.

Upvotes: 0

Chris
Chris

Reputation: 1804

Syntax is a bit different - you need an extra subquery so it would need to be more like ... where customerId IN (select * from (select custId from Orders where orderStatus = 'S' and orderCity = 'Amsterdam' and ORDER BY custId DESC) where rownum <=10)

You wouldn't need the extra subquery if you didn't have the order by clause

For ref see https://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns009.htm#:~:text=For%20each%20row%20returned%20by,has%202%2C%20and%20so%20on.

Upvotes: 2

Related Questions