60 lines
995 B
PL/PgSQL
60 lines
995 B
PL/PgSQL
\set ON_ERROR_STOP on
|
|
BEGIN;
|
|
\timing on
|
|
|
|
ANALYZE messages;
|
|
|
|
SELECT
|
|
chat_id,
|
|
COUNT(*) AS messages_count
|
|
FROM messages
|
|
GROUP BY chat_id
|
|
ORDER BY messages_count DESC
|
|
LIMIT 5;
|
|
|
|
SELECT id AS benchmark_chat_id
|
|
FROM chats
|
|
WHERE id IN (
|
|
SELECT chat_id
|
|
FROM messages
|
|
GROUP BY chat_id
|
|
ORDER BY COUNT(*) DESC
|
|
LIMIT 1
|
|
)
|
|
LIMIT 1
|
|
\gset
|
|
|
|
\echo 'TEST A: existing composite index'
|
|
|
|
EXPLAIN (ANALYZE, BUFFERS)
|
|
SELECT id, text, created_at
|
|
FROM messages
|
|
WHERE chat_id = :'benchmark_chat_id'
|
|
ORDER BY created_at, id
|
|
LIMIT 50;
|
|
|
|
\echo 'TEST B: additional index'
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_messages_chat_id_only
|
|
ON messages (chat_id);
|
|
|
|
ANALYZE messages;
|
|
|
|
EXPLAIN (ANALYZE, BUFFERS)
|
|
SELECT id, text, created_at
|
|
FROM messages
|
|
WHERE chat_id = :'benchmark_chat_id'
|
|
ORDER BY created_at, id
|
|
LIMIT 50;
|
|
|
|
\echo 'Index sizes'
|
|
|
|
SELECT
|
|
indexrelname,
|
|
pg_size_pretty(pg_relation_size(indexrelid)) AS size
|
|
FROM pg_stat_user_indexes
|
|
WHERE relname = 'messages'
|
|
ORDER BY indexrelname;
|
|
|
|
ROLLBACK;
|