Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting returned record from SQL query in Oracle

Tags:

sql

oracle

One of apps I take care of in checking a Oracle DB table every x seconds to see if there are new data to process (other real-time app is populating it).

Our new client business process forces our real-time up to populate this table with lots of records in a same time (say 10 000), but just few times a day. Next time my app checks if there is anything to process it encounters 10 000 records and tries to process that.

It's not very well engineered and it just not scale good enough. Quick fix would be limit the number of record the app gets from Oracle, next time it will pick another 50 (or whatever) etc.

How can I limit in Oracle SQL the number of returned records? Order matters!

  select * 
    from cool_table where date >= to_date('200901010000', 'YYYYMMDDhh24mi') 
order by seq_nr, entry_dts;
like image 713
Nazgob Avatar asked Jan 28 '09 04:01

Nazgob


People also ask

How do I limit the number of results returned in SQL?

The SQL LIMIT clause constrains the number of rows returned by a SELECT statement. For Microsoft databases like SQL Server or MSAccess, you can use the SELECT TOP statement to limit your results, which is Microsoft's proprietary equivalent to the SELECT LIMIT statement.

How do we limit which rows are returned by a query?

The SQL LIMIT clause restricts how many rows are returned from a query. The syntax for the LIMIT clause is: SELECT * FROM table LIMIT X;. X represents how many records you want to retrieve. For example, you can use the LIMIT clause to retrieve the top five players on a leaderboard.

How do I limit rows in Oracle query?

SELECT * FROM yourtable ORDER BY name LIMIT 50, 10; This query would get rows 51 to 60, ordered by the name column. This works in MySQL because the ORDER BY happens before the LIMIT. So, you can get the rows from 51-60 using this LIMIT clause.


2 Answers

select * from
(select c.* from cool_table c
   where date >= to_date('200901010000', 'YYYYMMDDhh24mi') 
   order by seq_nr, entry_dts)
where rownum < 50

You need to ensure the ordering is done before the rownum filtering (otherwise it will take the first 50 rows it finds, then order them)

like image 143
Gary Myers Avatar answered Oct 16 '22 14:10

Gary Myers


Starting with Oracle 12c it finally supports the standard ANSI fetch first n rows option:

select * 
from cool_table where date >= to_date('200901010000', 'YYYYMMDDhh24mi') 
order by seq_nr, entry_dts
fetch first 50 rows only;

This can be combined with an offset for paging:

select * 
from cool_table where date >= to_date('200901010000', 'YYYYMMDDhh24mi') 
order by seq_nr, entry_dts
offset 50 rows 
fetch first 50 rows only;
like image 45
a_horse_with_no_name Avatar answered Oct 16 '22 13:10

a_horse_with_no_name