Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server select rows between two values

Tags:

sql

sql-server

Hopefully the title explains it enough, but I want to be able to select rows in an SQL Server table between two values

example

SELECT * FROM table WHERE rows between 20 and 60

I have tried the ROW_NUMBER() and then use a WHERE clause....

Thanks,

Jason

like image 452
neolaser Avatar asked Mar 30 '11 01:03

neolaser


4 Answers

SELECT TOP 40 * FROM (SELECT TOP 60 * FROM table ORDER BY xx ASC) t ORDER BY xx DESC

Since the output of a select statement can return records in any order (without an order by clause) you need to decide which order to apply to the records... use the primary key if you don't know or care (substitute for xx)

like image 126
Martin Booth Avatar answered Oct 17 '22 15:10

Martin Booth


WITH mytable AS
(
   SELECT *,
    ROW_NUMBER() OVER (order by colname) AS 'RowNumber'
    FROM table
) 
SELECT * 
FROM myTable 
WHERE RowNumber BETWEEN 20 AND 60;
like image 37
Hogan Avatar answered Oct 17 '22 14:10

Hogan


If you have SQL Server 2012 (or higher) you may use Offset-Fetch for this.
See this Microsoft Technet Article on the Offset-Fetch Clause.
You will need to specify an Order-By (which I think is obvious).

If you want Rows Between 20 and 60, then what you're really saying is you want to start at 20 (your Offset) and then select (or Fetch) the next 40.

SELECT *
  FROM TableName
 ORDER BY SomeColumnName
 OFFSET 20 ROWS
 FETCH NEXT 40 ROWS ONLY

You can even use Variables and Calculations for your Fetch and Offset values.
Here's an example for exactly what the question asks for: Rows between 20 and 60

DECLARE @RowStart Int = 20
DECLARE @RowEnd   Int = 60
SELECT *
  FROM TableName
 ORDER BY SomeColumnName
 OFFSET @RowStart ROWS
 FETCH NEXT (@RowEnd - @RowStart) ROWS ONLY
like image 3
MikeTeeVee Avatar answered Oct 17 '22 14:10

MikeTeeVee


In previous versions of SQL, an option is to use a temporary table:

SELECT  IDENTITY(int,1,1) RowNumber,* 
into    #Temp
FROM    Table1

SELECT  *
FROM    #Temp
WHERE   RowNumber between 20 and 60 
like image 2
pcofre Avatar answered Oct 17 '22 14:10

pcofre