Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Select Top 100 rows in Oracle?

Tags:

sql

oracle

My requirement is to get each client's latest order, and then get top 100 records.

I wrote one query as below to get latest orders for each client. Internal query works fine. But I don't know how to get first 100 based on the results.

    SELECT * FROM (       SELECT id, client_id, ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn        FROM order     ) WHERE rn=1 

Any ideas? Thanks.

like image 919
user2321728 Avatar asked Nov 20 '14 08:11

user2321728


People also ask

How do you do top 100 in Oracle?

As Moneer Kamal said, you can do that simply: SELECT id, client_id FROM order WHERE rownum <= 100 ORDER BY create_time DESC; Notice that the ordering is done after getting the 100 row.

How do I select the top 10 rows in a table?

For example, TOP(10) would return the top 10 rows from the full result set. Optional. If PERCENT is specified, then the top rows are based on a percentage of the total result set (as specfied by the top_value).

How do I select top 10 rows in MySQL?

To select first 10 elements from a database using SQL ORDER BY clause with LIMIT 10. Insert some records in the table using insert command. Display all records from the table using select statement. Here is the alternate query to select first 10 elements.


2 Answers

Assuming that create_time contains the time the order was created, and you want the 100 clients with the latest orders, you can:

  • add the create_time in your innermost query
  • order the results of your outer query by the create_time desc
  • add an outermost query that filters the first 100 rows using ROWNUM

Query:

  SELECT * FROM (      SELECT * FROM (         SELECT            id,            client_id,            create_time,           ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn          FROM order       )        WHERE rn=1       ORDER BY create_time desc   ) WHERE rownum <= 100 

UPDATE for Oracle 12c

With release 12.1, Oracle introduced "real" Top-N queries. Using the new FETCH FIRST... syntax, you can also use:

  SELECT * FROM (     SELECT        id,        client_id,        create_time,       ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn      FROM order   )    WHERE rn = 1   ORDER BY create_time desc   FETCH FIRST 100 ROWS ONLY) 
like image 182
Frank Schmitt Avatar answered Sep 25 '22 06:09

Frank Schmitt


you should use rownum in oracle to do what you seek

where rownum <= 100 

see also those answers to help you

limit in oracle

select top in oracle

select top in oracle 2

like image 21
Moneer Kamal Avatar answered Sep 22 '22 06:09

Moneer Kamal