Partial Index With INCLUDE For Sparse Errors

Index only failed jobs with CREATE INDEX ... INCLUDE (...) WHERE so error queue queries run index-only scans while healthy rows stay unindexed.

SqlResilience

Code

snippet
CREATE TEMP TABLE job_runs (
    job_id     bigint PRIMARY KEY,
    priority   smallint NOT NULL,
    created_at timestamptz NOT NULL,
    failed_at  timestamptz,
    error_code text
);

INSERT INTO job_runs
SELECT g, (g % 5)::smallint, now() - (g || ' minutes')::interval,
       CASE WHEN g % 50 = 0 THEN now() ELSE NULL END,
       CASE WHEN g % 50 = 0 THEN 'TIMEOUT' ELSE NULL END
FROM generate_series(1, 500) AS g;

-- Only failed rows enter the B-tree; INCLUDE carries payload for index-only scans
CREATE INDEX idx_job_runs_failed_queue
    ON job_runs (priority, created_at)
    INCLUDE (job_id, error_code)
    WHERE failed_at IS NOT NULL;

ANALYZE job_runs;

EXPLAIN (COSTS OFF)
SELECT job_id, priority, error_code
FROM job_runs
WHERE failed_at IS NOT NULL
  AND priority <= 1
ORDER BY priority, created_at
LIMIT 10;

Code mechanics — Partial Index With INCLUDE For Sparse Errors

What runs here is SELECT / INSERT / CREATE / EXPLAIN — job_runs and generate_series are the objects involved.

job_runs allocates temporary session-only schema fixtures inline right above the queries without external setup and tears them down automatically on exit.

Concretely, the SQL combines: a WHERE clause that keeps only the rows a statement is meant to touch; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Using it

Setup is internal: the session-local tables it queries (job_runs) are made by the file, so a single complete run against a scratch database suffices.

Key statements

INSERT INTO job_runs
SELECT g, (g % 5)::smallint, now() - (g || ' minutes')::interval,
       CASE WHEN g % 50 = 0 THEN now() ELSE NULL END,
       CASE WHEN g % 50 = 0 THEN 'TIMEOUT' ELSE NULL END
FROM generate_series(1, 500) AS g;
EXPLAIN (COSTS OFF)
SELECT job_id, priority, error_code
FROM job_runs
WHERE failed_at IS NOT NULL
  AND priority <= 1
ORDER BY priority, created_at
LIMIT 10;
CREATE INDEX idx_job_runs_failed_queue
    ON job_runs (priority, created_at)
    INCLUDE (job_id, error_code)
    WHERE failed_at IS NOT NULL;

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
The references are `job_runs`, `generate_series`.