Skip to content
Advertisement

How to Select Records from large table batch wise in SQL

I have a table that contains billions of records. I want to select records in a batch using the c# while loop. I used Offset and Fetch Next, but it is taking too long to get results. If the table contains below 100k records, it works fine. What is the best way to batch select records?

Sample Code

Advertisement

Answer

If your Id is a number and your network Bandwidth is good enough:

  1. First, find the maximum and minimum value of Id.
  2. Second, create a range of numbers to be used in your where clause (Sorting on many records is a high-cost operation. Using Where Id > @A and Id<@B is way faster than fetch next).
  3. Use TPL to extract data from the database.
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement