How to use Paging in SQL Queries?

Paging is one of the most important tasks when developers developed applications. 
how to use paging in SQL queries or How to select 5-10 records?.
 In SQL queries we can select first 1-10  records, 10-20 records, 20-30 records etc.
  • SQL ROW_NUMBER() Function
  • Paging using Sub Queries
  • Paging using Common Table Expression (CTE)
SQL ROW_NUMBER() Function
SQL ROW_NUMBER() function is a built-in function of SQL Server. 
For SQL paging we need to use this.
We can implement paging in SQL in two ways
Paging using Sub Queries
Here is an example of SQL Sub Queries for paging.
SELECT * 
FROM (
       SELECT *,ROW_NUMBER() OVER(ORDER BY + @sortExpression ) as RowNum  
       FROM [Inquiry] where USERID=CAST(@USERID AS NVARCHAR(10)) 
 
) T
WHERE RowID between 1 and 10
Paging using Common Table Expression (CTE)
Here is an example of SQL Common Table Expression (CTE) for paging.
;WITH CTE as
(
      SELECT *,ROW_NUMBER() OVER(ORDER BY + @sortExpression ) as RowNum  
    FROM [Inquiry] where USERID=CAST(@USERID AS NVARCHAR(10)) 
) SELECT * from CTE WHERE RowID between 1 and 10

Comments

Post a Comment

Popular posts from this blog

Validate Mobile Number with 10 Digits in ASP.Net