Sub topic 12
Unique indexes and constraints with INCLUDE
This chapter assumes you know how CREATE INDEX and UNIQUE constraints work, and that you have met the INCLUDE clause in the previous chapters. You should also be comfortable with the idea that an index-only scan needs both the right columns in the index and mostly all-visible heap pages. Here you will see how INCLUDE interacts with uniqueness, and when it is the right tool.
What uniqueness covers
A unique index rejects a new entry when an existing entry has the same values in all of its key columns. Columns listed in INCLUDE are not key columns. They are stored as payload in the leaf pages and take no part in the uniqueness check.
This is the main reason to use INCLUDE on a unique index. Suppose you want lookups by id to return status and total from the index alone. The obvious attempt is this:
-- Wrong for this goal: uniqueness now applies to the combination
CREATE UNIQUE INDEX orders_id_status_total_idx
ON orders (id, status, total);This index would allow two rows with the same id as long as status or total differ. It enforces a weaker rule than you intended, and it also sorts by all three columns. The correct form keeps the rule on id alone:
CREATE UNIQUE INDEX orders_id_covering_idx
ON orders (id) INCLUDE (status, total);Uniqueness is enforced only on id. status and total ride along so that a query like SELECT status, total FROM orders WHERE id = 123 can be answered from the index.
Unique constraints and primary keys
INCLUDE works in constraint syntax as well as in CREATE INDEX. Both UNIQUE and PRIMARY KEY constraints accept it, and PostgreSQL builds a unique B-tree index behind the constraint.
Here is a small table you can run as shown:
CREATE TABLE accounts (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
display_name text,
CONSTRAINT accounts_email_key UNIQUE (email) INCLUDE (display_name)
);
INSERT INTO accounts (email, display_name) VALUES ('[email protected]', 'Ann');
-- Fails: same email, different payload
INSERT INTO accounts (email, display_name) VALUES ('[email protected]', 'Bob');The second insert fails with duplicate key value violates unique constraint "accounts_email_key". The detail line names only the key: Key (email)=([email protected]) already exists. The different display_name did not make the row distinct.
In psql, \d accounts shows the index as UNIQUE CONSTRAINT, btree (email) INCLUDE (display_name).
You can also put INCLUDE on a primary key:
CREATE TABLE products (
sku text,
name text NOT NULL,
price numeric(10,2) NOT NULL,
PRIMARY KEY (sku) INCLUDE (name, price)
);Now SELECT name, price FROM products WHERE sku = 'A-100' can use an index-only scan on the primary key index. No second index is needed.
How the insert path works
The uniqueness check searches the key columns only. If no equal key exists, the new entry goes into the leaf page with its payload attached.
Two details follow from this design:
- Included columns are stored in leaf entries only. The upper levels of the B-tree keep just the key columns, so a wide payload does not make the navigation levels taller.
- Because included columns are never compared or sorted, they do not need a B-tree operator class. You can include a column whose type has no B-tree ordering, which you could not do as a key column.
What references and conflict clauses can use
Only key columns count for features that depend on uniqueness.
| Feature | Uses included columns? | Notes |
|---|---|---|
| Duplicate detection | No | Only key columns are compared |
| `ON CONFLICT (cols)` | No | The conflict target must match the key columns |
| Foreign key `REFERENCES t (cols)` | No | References the key columns, for example `accounts (email)` |
| Index-only scan output | Yes | Included columns can be returned from the index |
| `ORDER BY` from index order | No | Payload is not sorted |
| `WHERE` conditions as index search conditions | No | A filter on a payload column cannot narrow the index search |
For example, this works against the accounts table:
INSERT INTO accounts (email, display_name)
VALUES ('[email protected]', 'Ann B.')
ON CONFLICT (email) DO UPDATE SET display_name = EXCLUDED.display_name;The conflict target is (email), which matches the key column of accounts_email_key. Naming display_name in the target would not match any unique index.
A foreign key can reference the constraint in the same way. REFERENCES accounts (email) is valid because email is the unique key. The included display_name plays no part.
Choosing between designs
You have three common ways to serve a lookup that needs extra columns:
| Design | Uniqueness rule | Extra columns | Cost |
|---|---|---|---|
| `UNIQUE (id)` plus a separate covering index | On `id` | Second index holds them | Two indexes to maintain |
| `UNIQUE (id, status, total)` | On the whole combination, usually wrong | In the key | Wide keys at every tree level |
| `UNIQUE (id) INCLUDE (status, total)` | On `id` | Leaf payload only | One index, wider leaf entries |
The third design is usually best when you need both the constraint and a covered lookup. Weigh the costs from the earlier chapter on write overhead:
- Each leaf entry is larger, so the index takes more disk space and cache.
- An update to an included column changes the index entry. That prevents a HOT update, as it would for any indexed column, even though the column plays no part in uniqueness.
- The whole index tuple, payload included, must still fit within the B-tree's per-entry size limit of roughly one third of a page. Wide
textpayloads can hit this limit, and the insert then fails with an index row size error.
If the payload columns change often, covering them in the unique index may cost more in writes than it saves in reads. A narrow payload of rarely changing columns is the best case.
Index-only scans on a unique covering index
A unique covering index behaves like any other covering index when you query it. A lookup by the key returns at most one row, so the plan is typically a single probe:
EXPLAIN (ANALYZE, BUFFERS)
SELECT email, display_name FROM accounts WHERE email = '[email protected]';On a small table the planner may prefer a sequential scan, because reading one page is cheaper than probing an index. Try this on a table with many thousands of rows. After a VACUUM, you should see Index Only Scan using accounts_email_key with Heap Fetches near zero. As before, recently modified pages that are not marked all-visible force heap visits, and the unique constraint does not change that.
Edge cases to remember
- NULLs. A normal unique index treats NULLs as distinct, so many rows may have a NULL key. PostgreSQL 15 added
NULLS NOT DISTINCTfor unique indexes and constraints if you need at most one NULL. This option concerns key columns only. Included columns can hold NULLs freely. - Expression and partial indexes. Uniqueness can be combined with a
WHEREclause. A partial unique index enforces the rule only on matching rows. A query must repeat that condition for the planner to use the index. The next chapter covers this. - Index types. Only B-tree supports
UNIQUEamong the built-in methods, so a unique covering index is always a B-tree here. - Redundant indexes. Check for an existing unique index on the same key before adding another. Query
pg_indexesor use\d tablenameto list them.
Exercise
A table users has PRIMARY KEY (id). You want SELECT id, email FROM users WHERE id = $1 to use an index-only scan, and you also want to guarantee that no two rows share an id. A colleague proposes CREATE UNIQUE INDEX users_id_email_idx ON users (id, email). Explain what is wrong with this, and give a better design.
Show answer
The proposed index enforces uniqueness on the pair (id, email), not on id alone, so it adds no real guarantee, and it duplicates the primary key's index while making every entry wider at all tree levels. The primary key on id already enforces uniqueness. A better design is to recreate the primary key as PRIMARY KEY (id) INCLUDE (email), which keeps one index, enforces uniqueness on id only, and stores email as leaf payload so the query can be answered by an index-only scan (given an up-to-date visibility map). If rebuilding the primary key is too disruptive, use a non-unique CREATE INDEX ... ON users (id) INCLUDE (email) instead, accepting the extra index.
Exercise
Given CONSTRAINT accounts_email_key UNIQUE (email) INCLUDE (display_name), which of these statements is accepted: (a) a second row with the same email and a different displayname, (b) a second row with a different email and the same displayname, (c) ON CONFLICT (display_name) DO NOTHING?
Show answer
Only (b) is accepted. Statement (a) fails with a duplicate key error because the key column email matches. Statement (c) is rejected because no unique index has display_name as a key column, so there is no arbiter index for the conflict target.