postgresqlpaginationin-memory

pagination on snapshot of data in postgres


Is there any pre-existing mechanism in postgresql to save a query result in some cache and do pagination on it (in case the data being queried keeps changing and it is not required to show updated data for different pages and pagination can be done on snapshot of that data at the time of first query)?

I know we can always save the data in another table and apply pagination on that but if there's any other better approach available for this, then please let me know.


Solution

  • Yes, that mechanism is a "with hold" cursor. Such cursors are materialized at the end of the transaction that creates them and don't reflect any changes in the underlying data:

    -- don't start a transaction
    
    -- this will compute the complete result set and store it on the server
    DECLARE c CURSOR WITH HOLD FOR SELECT ...;
    
    -- get the first page of 50 rows
    FETCH NEXT 50 FROM c;
    
    -- skip to page 100 (starts at row 4951)
    MOVE ABSOLUTE 4951 IN c;
    
    -- get page 100
    FETCH NEXT 50 FROM c;
    
    -- close the cursor when you are done!
    CLOSE c;
    

    It is very important to close with hold cursors, otherwise the result set remains cached on the server until the end of the database session.

    See this article for more information.