Lossy Bitmap Recheck With Small Work Mem

With work_mem tiny, a bitmap heap scan spills to lossy whole-page bits and EXPLAIN ANALYZE reports rows removed by the index recheck.

SqlData Integrity

Code

snippet
CREATE TABLE readings (
    id      bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    sensor  integer NOT NULL,
    payload text NOT NULL
);

-- insert clustered by sensor so each value owns a contiguous page block
INSERT INTO readings (sensor, payload)
SELECT g / 1000, repeat('x', 800)
FROM generate_series(0, 49999) AS g;
CREATE INDEX readings_sensor_idx ON readings (sensor);
ANALYZE readings;

-- 64kB is far below what the exact page bitmap needs: pages the scan cannot
-- remember exactly become lossy whole-page bits, and the heap scan must then
-- recheck each row on a lossy page against the index condition
SET work_mem = '64kB';
EXPLAIN (ANALYZE, COSTS OFF)
SELECT count(*) FROM readings WHERE sensor BETWEEN 10 AND 30;
RESET work_mem;

What to notice first — Lossy Bitmap Recheck With Small Work Mem

SELECT / INSERT / CREATE / EXPLAIN statements share the script, touching readings and generate_series.

Breaking the statements into their working parts: a WHERE clause filtering the rows one statement applies to; COUNT aggregation; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Using it

Point it at the readings table.

Key statements

INSERT INTO readings (sensor, payload)
SELECT g / 1000, repeat('x', 800)
FROM generate_series(0, 49999) AS g;
EXPLAIN (ANALYZE, COSTS OFF)
SELECT count(*) FROM readings WHERE sensor BETWEEN 10 AND 30;
CREATE TABLE readings (
    id      bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    sensor  integer NOT NULL,
    payload text NOT NULL
);

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`readings`, `generate_series`.