Unique and covering indexes
Overview
Uniqueness is a data rule; covering is a property of an index relative to a query. An index can enforce uniqueness, cover a query, both, or neither.
First example
EXPLAIN QUERY PLAN SELECT note FROM ix_order WHERE customer=2 AND day BETWEEN 40 AND 70 ORDER BY day;Observed SQLite result (rows in JSON):
[ [ 4, 0, 0, "SEARCH ix_order USING INDEX ix_customer_day (customer=? AND day>? AND day<?)" ]]How it works
The unique reference index rejects duplicate non-NULL references. SQLite unique indexes allow multiple NULL values; PostgreSQL 17 defaults to distinct NULLs but offers NULLS NOT DISTINCT. The customer/day/amount index covers the previous query, but selecting note requires accessing the table in the first example. PostgreSQL INCLUDE adds non-key payload columns without extending uniqueness; SQLite has no INCLUDE clause. Even a PostgreSQL index-only plan may fetch heap tuples when visibility checks require it. The second example verifies two NULL aliases in a unique index.
Practical example
SELECT count(*) FROM ix_alias WHERE alias IS NULL;Observed SQLite result (rows in JSON):
[ [ 2 ]]Practice and mistakes
Practice: compare selecting amount versus note for the same customer/day filter. Hint 1: inspect COVERING INDEX. Hint 2: note is absent from the index. Try inserting a duplicate reference inside a transaction, then rollback after the expected error.
PostgreSQL 17 example — NOT RUN
BEGIN;CREATE TEMP TABLE ix_demo(id integer, customer integer, day integer, amount integer, ref text, status text);INSERT INTO ix_demo VALUES (42,2,42,420,'Ref0042','open'),(52,2,52,520,'Ref0052','closed');CREATE UNIQUE INDEX ix_demo_cover ON ix_demo(ref) INCLUDE (amount);SELECT amount FROM ix_demo WHERE ref='Ref0042';ROLLBACK;Expected result, not executed: [[420]]