tags:

views:

81

answers:

8

Now I am working on a project, which has to select top 25 records from a table according to one column, let's call it Num.

The case is 1) the table is not sorted by Num;

I know this part can be done by using "GROUP ORDER BY"

2) the number of the records in the table might be less than 25.

For this question, is there any way to make it in just one single SQL statement?

Thanks so much!

A: 
SELECT ...
  LIMIT 25
Ignacio Vazquez-Abrams
LIMIT is a construct in MySQL.
Ardman
The OP didn't specify his RDBMS
Tom H.
http://stackoverflow.com/questions/595123/is-there-an-ansi-sql-alternative-to-the-mysql-limit-keyword
Ignacio Vazquez-Abrams
+1  A: 
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".

Valentino Vranken
+1  A: 

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 ...
codykrieger
A: 

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.

Adam
A: 

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

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

AllenG
+4  A: 

For SQL Server:

select top 25 * from table order by Num asc

For mySQL:

select * from table order by Num asc limit 25
Sarfraz
Like this because you give alternative solutions.
mslot
+1  A: 

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.

James Black
+1  A: 

Oracle:

Select *
FROM Table
WHERE rownum <= 25

MSSQL:

SELECT TOP 25 * 
from Table

Mysql:

SELECT * FROM table
LIMIT 25
Michael Pakhantsov