Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting specific row number in sql [duplicate]

Tags:

sql

sql-server

Is any way that I could select specified number of rows in SQL Server? Like on my first query, I wanted to get rows 1-5, then next is rows 6-10, then onwards? Thank you in advance for your answers :)

like image 310
Brenelyn Avatar asked Jun 23 '13 10:06

Brenelyn


People also ask

How do I SELECT repeated rows in SQL?

To select duplicate values, you need to create groups of rows with the same values and then select the groups with counts greater than one. You can achieve that by using GROUP BY and a HAVING clause.

How do I SELECT a specific row number in SQL?

For SQL Server, a generic way to go by row number is as such: SET ROWCOUNT @row --@row = the row number you wish to work on.


1 Answers

For SQL Server 2012, try this (simply set the offset)

SELECT  *
FROM     MyTable 
ORDER BY OrderingColumn ASC 
OFFSET  0 ROWS 
FETCH NEXT 5 ROWS ONLY 

OFFSET:
Specifies the number of rows to skip before it starts to return rows from the query expression.

FETCH NEXT:
Specifies the number of rows to return after the OFFSET clause has been processed.

Definitions of OFFSET and FETCH NEXT are from here.

Query 1:
Offset 0 => 1-5

Query 2:
Offset 5 => 6-10, etc.

SQL fiddle example: http://sqlfiddle.com/#!6/b4b8c/2

like image 184
Fabian Bigler Avatar answered Oct 27 '22 05:10

Fabian Bigler