\set ON_ERROR_STOP on SELECT version() AS postgres_version; SELECT count(*) AS messages_total, count(DISTINCT chat_id) AS chats_with_messages, pg_size_pretty(pg_table_size('messages')) AS table_size, pg_size_pretty(pg_indexes_size('messages')) AS indexes_size FROM messages; \echo '--- распределение истории по чатам: 5 самых больших и 5 самых маленьких ---' SELECT chat_id, count(*) AS rows FROM messages GROUP BY chat_id ORDER BY count(*) DESC LIMIT 5; SELECT chat_id, count(*) AS rows FROM messages GROUP BY chat_id ORDER BY count(*) ASC LIMIT 5; SELECT chat_id AS big_chat, count(*) AS big_rows FROM messages GROUP BY chat_id ORDER BY count(*) DESC LIMIT 1 \gset SELECT created_at AS cur_ts, id AS cur_id FROM messages WHERE chat_id = :'big_chat' ORDER BY created_at, id OFFSET (:'big_rows'::bigint * 9 / 10) LIMIT 1 \gset \echo '--- A. keyset, первая страница самого большого чата ---' EXPLAIN (ANALYZE, BUFFERS) SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = :'big_chat' ORDER BY created_at, id LIMIT 50; \echo '--- B. keyset, страница на глубине 90% истории (так работает cursor API) ---' EXPLAIN (ANALYZE, BUFFERS) SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = :'big_chat' AND (created_at, id) > (:'cur_ts'::timestamptz, :'cur_id'::uuid) ORDER BY created_at, id LIMIT 50; \echo '--- C. OFFSET на той же глубине (так API не делает: цена растёт со страницей) ---' EXPLAIN (ANALYZE, BUFFERS) SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = :'big_chat' ORDER BY created_at, id OFFSET (:'big_rows'::bigint * 9 / 10) LIMIT 50; \echo '--- индексы таблицы messages ---' SELECT indexrelname AS index, pg_size_pretty(pg_relation_size(indexrelid)) AS size, idx_scan AS scans FROM pg_stat_user_indexes WHERE relname = 'messages' ORDER BY indexrelname;