\set ON_ERROR_STOP on SELECT chat_id FROM messages GROUP BY chat_id ORDER BY count(*) DESC LIMIT 1 \gset SELECT created_at AS cursor_time, id AS cursor_id FROM messages WHERE chat_id = :'chat_id' ORDER BY created_at, id OFFSET 80000 LIMIT 1 \gset BEGIN; SET LOCAL plan_cache_mode = force_generic_plan; PREPARE history(uuid, timestamptz, uuid, int) AS SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT $4; EXPLAIN (ANALYZE, BUFFERS) EXECUTE history(:'chat_id', :'cursor_time', :'cursor_id', 51); ROLLBACK;