I want to know how CURSOR and FETCH work internally in PostgreSQL.
At the first, I assumed that
When
CURSORis declared with aselectstatement, DB will execute theselectstatement and then have the result stored in DB memory.When
FETCHis called on theCURSOR, DB will just read the result moving on theCURSOR.When the
CURSORis closed, results stored is removed from memory.
If my assumption is correct, FETCH should have short response time regardless of how the select statement is complex.
However, When I test, FETCH show more poor response time than I expected like It has done something I haven't expected.
How do they work?
--------- EDIT ---------
The below is what I get when I test with my actual database table.
(select statement contains join clause for 3 tables and one of the tables has 3 million rows)
( 8sec) DECLARE “123" NO SCROLL CURSOR WITH HOLD FOR SELECT .....
(0.04sec) FETCH FORWARD 2 FROM "123";
( 4sec) FETCH FORWARD 10000 FROM "123";
--------- EDIT ---------
The 4sec response time in FETCH FORWARD 10000 FROM "123" seems because of pgcli(PostgreSQL client tool) I used.
I don't know why but It has clearly came to be fast up to 0.04sec after changing client tool.
SELECTis not executed when you declare the cursor but when you use it for the first time (the firstFETCH). See also this answer.DECLAREseems to do something. Please check my edited question.