Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CURSOR vs select statement in loop

I just saw a simple example in another StackOverflow question that used a cursor to loop through a table. I would have just looped through the results of a select query instead of wrapping the select query in a cursor. What is the advantage of using a cursor?

(I couldn't include the example here because StackOverflow thought my question was mostly code, and demanded more details. I've run into that annoying restriction before. If I can ask my question clearly in just a few words, I should be able to. I'll see if I can find a link to that question, and if I can, I'll add the link here.)

Here is the original question where I saw CURSOR used.

like image 422
ROBERT RICHARDSON Avatar asked Sep 07 '25 01:09

ROBERT RICHARDSON


1 Answers

What is the advantage of using a cursor?

The only advantage is that you have to write more code (if they pay you for each line of code).

do $$
declare
    rec record;
    cur cursor for select i from generate_series(1, 3) i;
begin
    open cur;
    loop
        fetch cur into rec;
        exit when rec is null;
        raise notice '%', rec.i;
    end loop;
    close cur;
end
$$;

A loop through query results just opens a (virtual) cursor, fetches rows, checks range, exits when needed and closes the cursor for you.

do $$
declare
    rec record;
begin
    for rec in select i from generate_series(1, 3) i
    loop
        raise notice '%', rec.i;
    end loop;
end
$$;
like image 63
klin Avatar answered Sep 09 '25 15:09

klin