Advertisement
Intermediate SQL Server, Cursors

What is the performance impact of using a cursor compared to a set based operation on a large table, and why does this difference occur?

Short answer

A cursor processes one row at a time, incurring the overhead of fetching and processing each individual row separately, while a set based operation lets SQL Server's query optimizer work on the entire result set at once, taking advantage of indexes, parallel processing, and…

Save SQL Server mock interview
Advertisement
AModel answer
A cursor processes one row at a time, incurring the overhead of fetching and processing each individual row separately, while a set based operation lets SQL Server's query optimizer work on the entire result set at once, taking advantage of indexes, parallel processing, and efficient execution plans that a row by row loop cannot benefit from.
-- Cursor: processes 100,000 rows one at a time, each with its own overhead
-- Set based: processes all 100,000 rows in a single optimized operation
UPDATE Orders SET Status = 'Archived' WHERE OrderDate < '2020-01-01';
Real-world example
A reporting team notices a cursor based nightly job taking over an hour to process a large orders table, and after converting it to a set based approach, the same task completes in just a few seconds.
Likely follow-ups
  • Can a cursor ever take advantage of parallel query execution?
  • How much slower is a typical cursor compared to an equivalent set based statement on a large table?
Related topics