SQL loop by shell

While PL/pgSQL has LOOP flow for recursive operations, SQL or psql doesn’t have one.
If you want to loop without PL/pgSQL, utilize bash:

for id in $(psql -U<user> <database> -t -c "SELECT id FROM <table>"); do
  # any recursive query
  psql -U<user> <database> -t -c "CALL some_procedure($id)"
done

psql -t in the outer query excludes extra outputs like column header, so variable id gets each id from table.
Inside for loop, you can issue any query with bash variable substitution.

For example, CALL stored procedure requires external loop for multiple operations.

中馬崇尋
Chuma Takahiro