Postgres: Find previous and next row or existing value created by SERIAL colum for separate query
Seeing the loop in pseudo-code, it seems like you want a SQL cursor.
it's instantiated with DECLARE associated to a query with an ORDER BY if needed, and you can use MOVE to move forward or backward, and FETCH to fetch the current row, or several rows, and finally CLOSE when you're done.
All these are SQL statements and independent from any client-side language.