PostgreSQL: Basic Cursor Handling


I summarized about cursor operation in PostgreSQL PL/pgSQL.

Environment

  • psql 9.6
  • PostgreSQL 9.3

Cursor

Speaking simply, cursor is used when we operate to each record we got by SELECT query, one by one.

Use Cursor with Declaration

There are several ways to use cursor. First, I write about basic usage. In Oracle, this patter is called explicit cursor. PostgreSQL document says it, Bound Cursor.

Declare cursor with CURSOR statement, and declare variable of RECORD type. LOOP about all rows of SELECT result.

FOR after CURSOR statement can be replaced to IS. Public document only says about FOR, but IS is also OK.

There, カーソルを開き、クエリ結果の行を変数(ここではCR)に入れて全行の処理を行います。 When the cursor processed all rows, exit the loop with EXIT statement. Close opened cursor at last.

EXIT is in IF conditional branch, but you can make it simpler for executing EXIT. Insert EXIT WHEN NOT FOUND;.

This pattern, FETCH timing is not complicated, so it can be shortening.

In this case, CR can be used only in the loop.

Use Parameter for Cursor

Cursor can take parameter like function in programming languages.

Use Cursor without Declaration

This is more technical cursor usage. In Oracle, it is called implicit cursor.

There, I didn’t declare cursor variable. Record variable has to be declared.(In Oracle PL/SQL, record variable doesn’t have to be declared.)