Unique Index Include Non-Key Columns

INCLUDE columns travel in a unique index leaf without joining the key: uniqueness checks skip them while covering reads still qualify for an index-only scan.

SqlData Integrity

Code

snippet
-- UNIQUE 索引加 INCLUDE (non-key columns):非键列只进叶子层,不参与唯一判断
CREATE TABLE shipments (
    shipment_id   int PRIMARY KEY,
    customer_id   int NOT NULL,
    tracking_code text NOT NULL,
    created_at    timestamptz NOT NULL DEFAULT now()
);

INSERT INTO shipments (shipment_id, customer_id, tracking_code, created_at) VALUES
    (1, 10, 'TRK-1', '2026-11-20 09:00+00'),
    (2, 10, 'TRK-2', '2026-11-20 09:00+00');

CREATE UNIQUE INDEX shipments_by_customer
    ON shipments (customer_id, tracking_code) INCLUDE (created_at);

-- created_at 是 INCLUDE 列:两行时间相同仍然插入成功
INSERT INTO shipments (shipment_id, customer_id, tracking_code, created_at) VALUES
    (3, 10, 'TRK-3', '2026-11-20 09:00+00');

-- 只有键列组合冲突才被拒绝:
-- INSERT INTO shipments (shipment_id, customer_id, tracking_code) VALUES
--     (4, 10, 'TRK-1');   -- ERROR: duplicate key value violates unique constraint

-- 键列 + INCLUDE 列的查询可命中 Index-Only Scan,不必回表
EXPLAIN (COSTS OFF)
SELECT customer_id, tracking_code, created_at
FROM shipments
WHERE customer_id = 10;

DROP TABLE shipments;

How the snippet works

What runs here is SELECT / INSERT / CREATE / EXPLAIN — shipments are the objects involved.

In terms of clauses, the statements use: a WHERE clause filtering the rows one statement applies to; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out; DEFAULT values filling omitted columns.

Using it

Run the statement against the shipments table.

Key statements

EXPLAIN (COSTS OFF)
SELECT customer_id, tracking_code, created_at
FROM shipments
WHERE customer_id = 10;
CREATE TABLE shipments (
    shipment_id   int PRIMARY KEY,
    customer_id   int NOT NULL,
    tracking_code text NOT NULL,
    created_at    timestamptz NOT NULL DEFAULT now()
);
INSERT INTO shipments (shipment_id, customer_id, tracking_code, created_at) VALUES
    (1, 10, 'TRK-1', '2026-11-20 09:00+00'),
    (2, 10, 'TRK-2', '2026-11-20 09:00+00');

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`shipments`.