Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show only the first N lines of output of a SQL query

Tags:

Is there a way to only show the first N lines of output from an SQL query?
Bonus points, if the query stops running once the N lines are outputted.

I am most interested in finding something which works in Oracle.

like image 229
pacman Avatar asked May 17 '09 07:05

pacman


People also ask

How do I select the first row from multiple records in SQL?

To do that, you can use the ROW_NUMBER() function. In OVER() , you specify the groups into which the rows should be divided ( PARTITION BY ) and the order in which the numbers should be assigned to the rows ( ORDER BY ).

How do I select the last 3 rows in SQL?

I want to select the last 3 rows of an sql table. I know I should use SELECT * FROM table ORDER BY DESC LIMIT 3 , but the problem with this code is that it selects the rows from the end. For example, it selects 30, then 29, then 28. But, I need them in this format: 28, 29, 30 .


2 Answers

It would be helpful if you specify what database you are targetting. Different databases have different syntax and techniques to achieve this:

For example in Oracle you can ahieve this by putting condition on RowNum (select ... from ... where ... rownum < 11 -> would result in outputting first 10 records)

In MySQL you can use you can use limit clause.

Microsoft SQL Server => SELECT TOP 10 column FROM table

PostgreSQL and MySQL => SELECT column FROM table LIMIT 10

Oracle => select * from (SELECT column FROM table ) WHERE ROWNUM <= 10 (thanks to stili)

Sybase => SET rowcount 10 SELECT column FROM table

Firebird => SELECT FIRST 10 column FROM table

NOTE: Modern ORM tools such as Hibernate give high level API (Query, Restriction, Condition interfaces) that abstract the logic of top n rows based on the dialect you choose.

like image 123
Rutesh Makhijani Avatar answered Sep 29 '22 06:09

Rutesh Makhijani


For Oracle the suggested and accepted solution is wrong. Try using an order clause, and the results will be unpredictable. The SQL will need to be nested to accomplish this in Oracle.

select name, price   from (     select name, price, row_number() over (order by price) r       from items   ) where r between 1 and 5;  

The example above was borrowed from http://www.adp-gmbh.ch/ora/sql/examples/first_rows.html which has a good discussion on this topic.

like image 27
stili Avatar answered Sep 29 '22 07:09

stili