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
.
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 ).
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With