PostgreSQL Partial Index Soft Delete

Index only live rows with a partial index over soft-deleted tables, keeping hot queries small and vacuum friendly.

SqlData Integrity

Code

sqlsnippet
33 lines
-- 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

FAQ

Which tables or CTEs does it reference?
`documents`.