Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select subset of rows using Row_Number()

Select id, name, ROW_NUMBER() OVER (ORDER BY id asc) as 'RowNo'
from customers
where RowNo between 50 AND 60

I am trying to select a subset of rows between 50 and 60 . The problem is 'RowNo' is an invalid column name.

Thank you

Using SQL SERVER 2008 R2

like image 533
test Avatar asked Feb 17 '12 13:02

test


People also ask

How do I select a subset of a row in SQL?

To fetch a subset of selected rows we use TOP clause fallowed by integer value. We can also use PERCENT clause to fetch n percent rows in result set. Notice that statement must have ORDER BY clause.

What is ROW_NUMBER () function in SQL?

ROW_NUMBER function is a SQL ranking function that assigns a sequential rank number to each new record in a partition. When the SQL Server ROW NUMBER function detects two identical values in the same partition, it assigns different rank numbers to both.

What does ROW_NUMBER () over partition by do?

The Row_Number function is used to provide consecutive numbering of the rows in the result by the order selected in the OVER clause for each partition specified in the OVER clause. It will assign the value 1 for the first row and increase the number of the subsequent rows.

How do you select Rownum?

You can use ROWNUM to limit the number of rows returned by a query, as in this example: SELECT * FROM employees WHERE ROWNUM < 10; If an ORDER BY clause follows ROWNUM in the same query, then the rows will be reordered by the ORDER BY clause. The results can vary depending on the way the rows are accessed.


1 Answers

Use your query as subquery like bellow:

select * from (
    Select id, name, ROW_NUMBER() OVER (ORDER BY id asc) as [RowNo]
    from customers
) t
where RowNo between 50 AND 60

You can use CTE as well but whether to choose one over another read Difference between CTE and SubQuery? and check execution plan.

like image 85
Michał Powaga Avatar answered Nov 15 '22 06:11

Michał Powaga