SQL ROW_NUMBER and sorting issue

vk_muse picture vk_muse · Jun 11, 2012 · Viewed 9.7k times · Source

In SQL 2005/2008 database we have table BatchMaster. Columns: RecordId bigint - autoincremental id, BatchNumber bigint - unique non-clustered index, BatchDate). We have sproc that returns paginated data from this table. That sproc works fine for most of the clients, but at one SQL server instance we have problem with records order. In general, at sproc we do

select * from
(
    select row_number() over (order by bm.BatchDate desc, bm.BatchNumber desc) as Row,
    *
    from dbo.BatchMaster bm with (nolock)
)
where Row between @StartingRow and @EndgingRow

So, as you can notice from the script above we want return records sorted by BatchDate and BatchNumber. That's not gonna happen for one of our client: enter image description here

Records are in wrong order. Also, notice first column (Row), it is not in ascending order.

Can someone explain why so?

Answer

aF. picture aF. · Jun 11, 2012

Assuming you want the lowest BatchNumber for a given BatchDate with the smallest Row number and that you want orderer by the Row, try this:

select * from
(
    select row_number() over (order by bm.BatchDate desc, bm.BatchNumber asc) as Row,
    *
    from dbo.BatchMaster bm with (nolock)
)
where Row between @StartingRow and @EndgingRow
order by Row