PostgreSQL Partial Index Soft Delete
Index only live rows with a partial index over soft-deleted tables, keeping hot queries small and vacuum friendly.
Code
-- PostgreSQL 软删除表:业务查询永远附加 deleted_at IS NULL
CREATE TABLE documents (
id bigserial PRIMARY KEY,
owner_id bigint NOT NULL,
title text NOT NULL,
deleted_at timestamptz
);
-- 部分索引只覆盖活行:体积与热数据成正比
CREATE INDEX idx_documents_owner_live
ON documents (owner_id, created_at DESC)
WHERE deleted_at IS NULL;
-- 命中部分索引:条件必须与索引谓词精确匹配
SELECT id, title
FROM documents
WHERE owner_id = 42
AND deleted_at IS NULL
ORDER BY created_at DESC
LIMIT 10;
-- 归档查询走另一条路:不占热索引的空间
SELECT id, deleted_at
FROM documents
WHERE owner_id = 42
AND deleted_at IS NOT NULL
ORDER BY deleted_at DESC
LIMIT 100;
-- 唯一性也按活行生效:同 owner 的活文档标题唯一
CREATE UNIQUE INDEX idx_documents_title_live
ON documents (owner_id, title)
WHERE deleted_at IS NULL;How the snippet works
The file runs SELECT / CREATE statements, touching documents.
The pieces that do the work: a WHERE clause narrowing which rows one statement affects; 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; UNIQUE constraints that keep duplicate values out.
Applying it
Run the statement against the documents table; the LIMIT keeps the probe cheap while you tune the predicates.
Statements that matter
SELECT id, deleted_at
FROM documents
WHERE owner_id = 42
AND deleted_at IS NOT NULL
ORDER BY deleted_at DESC
LIMIT 100;
SELECT id, title
FROM documents
WHERE owner_id = 42
AND deleted_at IS NULL
ORDER BY created_at DESC
LIMIT 10;
CREATE INDEX idx_documents_owner_live
ON documents (owner_id, created_at DESC)
WHERE deleted_at IS NULL;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Which tables or CTEs does it reference?
- `documents`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.