71 lines
1.8 KiB
SQL
71 lines
1.8 KiB
SQL
\set ON_ERROR_STOP on
|
|
\timing on
|
|
|
|
\echo '=== Grade 5: index comparison ==='
|
|
|
|
DROP TABLE IF EXISTS bench_index_a;
|
|
DROP TABLE IF EXISTS bench_index_b;
|
|
|
|
CREATE TABLE bench_index_a AS
|
|
SELECT * FROM messages;
|
|
|
|
CREATE TABLE bench_index_b AS
|
|
SELECT * FROM messages;
|
|
|
|
CREATE INDEX bench_a_history_idx
|
|
ON bench_index_a (chat_id, created_at, id);
|
|
|
|
CREATE INDEX bench_b_history_idx
|
|
ON bench_index_b (chat_id, created_at, id)
|
|
INCLUDE (sender_id, text);
|
|
|
|
VACUUM (ANALYZE) bench_index_a;
|
|
VACUUM (ANALYZE) bench_index_b;
|
|
|
|
\echo '=== Table and index sizes ==='
|
|
|
|
SELECT
|
|
'A: regular index' AS variant,
|
|
pg_size_pretty(pg_relation_size('bench_a_history_idx')) AS index_size
|
|
UNION ALL
|
|
SELECT
|
|
'B: covering index',
|
|
pg_size_pretty(pg_relation_size('bench_b_history_idx'));
|
|
|
|
\echo '=== Index A: large chat, deep page ==='
|
|
|
|
EXPLAIN (ANALYZE, BUFFERS)
|
|
SELECT id, chat_id, sender_id, text, created_at
|
|
FROM bench_index_a
|
|
WHERE chat_id = '66666666-6666-4666-8666-666666666661'
|
|
AND created_at > '2026-01-01 00:01:00+00'
|
|
ORDER BY created_at, id
|
|
LIMIT 100;
|
|
|
|
\echo '=== Index B: large chat, deep page ==='
|
|
|
|
EXPLAIN (ANALYZE, BUFFERS)
|
|
SELECT id, chat_id, sender_id, text, created_at
|
|
FROM bench_index_b
|
|
WHERE chat_id = '66666666-6666-4666-8666-666666666661'
|
|
AND created_at > '2026-01-01 00:01:00+00'
|
|
ORDER BY created_at, id
|
|
LIMIT 100;
|
|
|
|
\echo '=== Index A: small chat ==='
|
|
|
|
EXPLAIN (ANALYZE, BUFFERS)
|
|
SELECT id, chat_id, sender_id, text, created_at
|
|
FROM bench_index_a
|
|
WHERE chat_id = '66666666-6666-4666-8666-666666666663'
|
|
ORDER BY created_at, id
|
|
LIMIT 100;
|
|
|
|
\echo '=== Index B: small chat ==='
|
|
|
|
EXPLAIN (ANALYZE, BUFFERS)
|
|
SELECT id, chat_id, sender_id, text, created_at
|
|
FROM bench_index_b
|
|
WHERE chat_id = '66666666-6666-4666-8666-666666666663'
|
|
ORDER BY created_at, id
|
|
LIMIT 100; |