skydoor
skydoor

Reputation: 25868

How to select top N from a table

I have to select the top 25 records from a table according to the column Num.

There are two issues. First, the table is not sorted by Num. I know this can be resolved by using GROUP ORDER BY. Second, the number of the records in the table might be less than 25.

Is there any way to perform this selection in just one SQL statement?

Upvotes: 7

Views: 37976

Answers (9)

No'am Newman
No'am Newman

Reputation: 6477

In Firebird,

select first 25 
from your_table
order by whatever

Upvotes: 0

Michael Pakhantsov
Michael Pakhantsov

Reputation: 25370

Oracle:

Select *
FROM Table
WHERE rownum <= 25

MSSQL:

SELECT TOP 25 * 
from Table

Mysql:

SELECT * FROM table
LIMIT 25

Upvotes: 4

James Black
James Black

Reputation: 41858

It depends heavily on your database, as there is no standard way to do this.

In SQL Server, for example, I have used Row_Number (http://msdn.microsoft.com/en-us/library/ms186734.aspx) to do this, so I can select which group I was interested in (for paging, for example), but Top also works.

For Oracle you can look at rownum (http://www.adp-gmbh.ch/ora/sql/examples/first_rows.html).

And MySQL has been mentioned already.

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382696

For SQL Server:

select top 25 * from table order by Num asc

For mySQL:

select * from table order by Num asc limit 25

Upvotes: 15

AllenG
AllenG

Reputation: 8190

Select Top 25 [Column] From [Table] Order By [Column]

If you have fewer than 25 records, this will just pull however many there are.

Upvotes: 0

Adam Houldsworth
Adam Houldsworth

Reputation: 64487

Not sure I understand the requirement, but you can do:

SELECT TOP 25 Num FROM Blah WHERE Num = 'MyCondition'

If there aren't 25 records, you won't get 25. You can perform an ORDER BY and the TOP will listen to that.

Upvotes: 0

codykrieger
codykrieger

Reputation: 1780

Depending on the database implementation you're using, it could be using the limit statement (as one other answer suggests) or it could be like this:

SELECT TOP 25 Num, blah, blah ...

Upvotes: 1

Valentino Vranken
Valentino Vranken

Reputation: 5815

select top 25 *
from your_table
order by Num asc

On SQL Server that would select the 25 first records starting from the lowest value of Num. If you need the highest, use "desc" instead of "asc".

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798646

SELECT ...
  LIMIT 25

Upvotes: 0

Related Questions