Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if the row is the last one when looping through result set in PL/pgSQL

Is something like this possible?

FOR row_var IN SELECT * FROM my_table LOOP
    -- ...
    IF is_last_row THEN
        -- do something...
    END IF;
END LOOP

The only thing that goes into my mind now is to select a count of the rows and compare it with row_number() in the loop.

like image 562
Przemek Avatar asked Oct 18 '25 16:10

Przemek


1 Answers

There is a very cheap and simple way. Your row variable row_var still holds the last row after the loop ends. Just use it then:

FOR row_var IN
   SELECT * FROM my_table ORDER BY ???
LOOP
    -- do something for every row here
END LOOP;

-- do something with row_var for the last row here

Aside from that, there is often a more efficient solution with plain SQL, depending on the undisclosed details of your use case ...

like image 102
Erwin Brandstetter Avatar answered Oct 20 '25 08:10

Erwin Brandstetter