Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return rows between a specific range, with one select statement

I'm looking to some expresion like this (using SQL Server 2008)

SELECT TOP 10 columName FROM tableName

But instead of that I need the values between 10 and 20. And I wonder if there is a way of doing it using only one SELECT statement.

For example this is useless:

SELECT columName FROM
(SELECT ROW_NUMBER() OVER(ORDER BY someId) AS RowNum, * FROM tableName) AS alias
WHERE RowNum BETWEEN 10 AND 20

Because the select inside brackets is already returning all the results, and I'm looking to avoid that, due to performance.

like image 203
user1823901 Avatar asked Nov 16 '12 18:11

user1823901


People also ask

How do I SELECT a range in a table in SQL?

The SQL BETWEEN Operator The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are included.

How do you indicate ranges between numbers in a query?

The BETWEEN operator is inclusive. To specify an exclusive range, you use the less than (<) and greater than (>) operators instead. If you pass the NULL values to the BETWEEN operator e.g., expr , lower_value or upper_value , the BETWEEN operator returns NULL .

How do I SELECT a row in range?

Or click on any cell in the column and then press Ctrl + Space. Select the row number to select the entire row.


2 Answers

There is a trick with row_number that does not involve sorting all the rows.

Try this:

SELECT columName
FROM (SELECT ROW_NUMBER() OVER(ORDER BY (select NULL as noorder)) AS RowNum, *
      FROM tableName
     ) as alias
WHERE RowNum BETWEEN 10 AND 20

You cannot use a constant in the order by. However, you can use an expression that evaluates to a constant. SQL Server recognizes this and just returns the rows as encountered, properly enumerated.

like image 192
Gordon Linoff Avatar answered Oct 23 '22 05:10

Gordon Linoff


Use SQL Server 2012 to fetch/skip!

SELECT SalesOrderID, SalesOrderDetailID, ProductID, OrderQty, UnitPrice, LineTotal
FROM AdventureWorks2012.Sales.SalesOrderDetail
OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY;

There's nothing better than you're describing for older versions of sql server. Maybe use CTE, but unlikely to make a difference.

WITH NumberedMyTable AS
(
    SELECT
        Id,
        Value,
        ROW_NUMBER() OVER (ORDER BY Id) AS RowNumber
    FROM
        MyTable
)
SELECT
    Id,
    Value
FROM
    NumberedMyTable
WHERE 
    RowNumber BETWEEN @From AND @To  

or, you can remove top 10 rows and then get next 10 rows, but I double anyone would want to do that.

like image 25
RAS Avatar answered Oct 23 '22 05:10

RAS