title: How to Select Records from large table batch wise in SQL
body: <p>I have a table that contains billions of records. I want to select records in a batch using the c# <code>while</code> loop. I used <code>Offset</code> and <code>Fetch Next</code>, 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?</p>
  <p>Sample Code</p>
  <pre class="lang-cs prettyprint-override"><code>int Count  = 500000 // Select Count(id) from table
  int OffSet = 1; //Next Time 100000
  int FetchNext = 100000; //Next Time 200000
  
   while (OffSet &lt; Count)
  {
     _strsqlcommand = &quot;Select id from table ORDER BY id  OFFSET &quot; + OffSet + &quot; ROWS  FETCH NEXT &quot; + FetchNext + &quot; ROWS ONLY&quot;
  
  _sqlCommand = new SqlCommand(_strsqlcommand, _sqlConnection);
  _sqlDataReader = _sqlCommand.ExecuteReader();
  
  
   OffSet += FetchNext;
  }
  </code></pre>