Thursday, November 16, 2017

SKIP and TAKE in sql query (simple work around)


Sometimes we might need not just to filter the records but also to skip and/or take specific rows from it. Using LINQ in c#, it can be easy for developers to skip and take records but they might be scratching their head if they need to do the same in SQL query and hence we get stuck.

Below are some query examples which I have been using to perform these actions.We can customize our query to skip and/or take records.

To get exact records, you can sort the records by any field like I did below.

Note: Replace Your_SkipCount and  Your_TakeCount by numbers your numbers

To skip only


SELECT * FROM
(
         SELECT
ROW_NUMBER() OVER(ORDER BY id) AS rowid,
Column1, ..
         FROM dbo.YourTable
        ) AS tbl
WHERE rowid > Your_skipCount

To Skip and Take


SELECT FROM
(
           SELECT
ROW_NUMBER() OVER(ORDER BY id) AS rowid,
Column1, ..
           FROM dbo.YourTable
         ) AS tbl
WHERE rowid BETWEEN (Your_SkipCount +1) AND (Your_Skipcount + Your_TakeCount)

To Take Only


SELECT TOP Your_TakeCount
id,
Name
FROM dbo.YourTable
ORDER BY id


No comments:

Post a Comment