Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select top N from a table

Tags:

sql

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?

like image 829
skydoor Avatar asked Jul 28 '10 13:07

skydoor


People also ask

How do I select the top 10 rows in a column in SQL?

For example, TOP(10) would return the top 10 rows from the full result set. Optional. If PERCENT is specified, then the top rows are based on a percentage of the total result set (as specfied by the top_value). For example, TOP(10) PERCENT would return the top 10% of the full result set.

How do you select nth record in a table?

To verify the contents of the table use the below statement: SELECT * FROM Employee; Now let's display the Nth record of the table. Syntax : SELECT * FROM <table_name> LIMIT N-1,1; Here N refers to the row which is to be retrieved.


2 Answers

For SQL Server:

select top 25 * from table order by Num asc

For mySQL:

select * from table order by Num asc limit 25
like image 65
Sarfraz Avatar answered Sep 17 '22 21:09

Sarfraz


Oracle:

Select *
FROM Table
WHERE rownum <= 25

MSSQL:

SELECT TOP 25 * 
from Table

Mysql:

SELECT * FROM table
LIMIT 25
like image 25
Michael Pakhantsov Avatar answered Sep 18 '22 21:09

Michael Pakhantsov