Secondary indexes
How a KDBS secondary index stays complete for every value, why it only appends, and how the engine chooses it.
In this article
A secondary index in KDBS is an ordered map from one or more non-key columns to the row’s primary key. It covers every row and is updated on every write, so it can answer any value of its key, including an authoritative “no rows”. An ordinary index is a read accelerator only: it never makes a write fail for a reason of its own. A unique index (CREATE UNIQUE INDEX) is the one exception: it also refuses a write that would give two live rows the same key value.
The idea
An index is “a Cabin that observed everything”. A Cabin is complete only for the values queries have asked for. An index is complete for every value, because every write maintains it. Both keep a superset of the matching rows and remove the surplus when a query reads them.
CREATE INDEX ix_passenger_name ON passengers(name) COVERING (member);
How it works
What an entry holds
Each entry holds the key columns, any COVERING columns, and the row’s primary key. It holds no page address, so moving a row never invalidates an index. Entries are sorted by the whole entry, covered columns included, so no two entries share a sort key.
A string key column stores only a fixed prefix of its value (32 bytes in this release, a proposed value). An equality on a prefix can match extra rows but never miss one. Every read re-checks the predicate against the real row, so the prefix costs precision, never correctness.
Maintenance only appends
| Write | What happens to the index |
|---|---|
INSERT | One entry is appended per index on the table. |
UPDATE that changes a key or covered column | A new entry is appended. The old entry stays. |
UPDATE that touches no key or covered column | Nothing. |
DELETE | Nothing. |
Old entries stay because an older snapshot may still need them to find its version of the row. A reader resolves each entry to the row version its snapshot sees, checks visibility, and re-checks the key. An entry that no longer matches is skipped.
If appending an index entry fails, the statement fails. An index that is missing an entry gives wrong answers, not slow ones. On disk, the index record is written to the log before the row record it describes, so a crash can leave an extra entry, which reads skip, but never a row without its entry.
Reading
WHERE name = 'Park Jiho' AND member = 1
|
IndexProbe on ix_passenger_name: walk entries for 'Park Jiho'
|
member is covered -> test "member = 1" on the entry
| fails -> drop it, no table read (index_filtered)
| passes or cannot tell -> keep
sort the kept primary keys into primary-key order
|
read each row: check visibility, re-check every predicate, emit
- Two access kinds.
IndexProbeis an equality on a prefix of the key columns.IndexRangeis an equality prefix plus a range on the next key column, or a range on the first one. - Rows come back in primary-key order, the same order a scan returns. Creating an index never reorders a query’s reply.
- Covering columns save table reads for rows that will be filtered out. A predicate on a covered column is tested on the entry, and a row that fails it is never read from the table. A row that is returned is always read from the table, because visibility is decided only from the row itself. There is no index-only scan, and even
COUNT(*)reads the rows. - Joins can use an index. When the leading key column is bound by equality to a column of an earlier step, such as
ON t.passenger_id = p.idwithpassengers AS pread first, the index is probed once per outer row. Both columns must have exactly the same type.
Which structure the engine picks
For a WHERE column = value on a non-key column, the engine uses an index first, then a Cabin, then a filtered scan, in that fixed order. Among indexes it takes the one matching the longest usable prefix of the statement’s equalities, and on a tie the oldest one. The choice depends on the statement and the catalog, never on data statistics. A statement’s plan therefore never changes as the table grows (see Statements and execution plans).
The price is that KDBS cannot skip its own index on a small table. Measured on an earlier engine (the bench/ tree at commit 1769487), a range over 200 rows ran 11% slower with an index than without one, while a selective equality over 10,000 rows ran 9.7 times faster.
Unique indexes
CREATE UNIQUE INDEX makes the index a constraint as well as a read path:
- What holds a key. A row holds a key value when its latest version is live, visible and carries the value. A deleted, rolled-back or purged row holds nothing. A row whose latest writer has not committed yet is busy.
- Full values are compared. The check walks every entry of the key, resolves each row and compares the full values, never the stored 32-byte prefix alone.
- Two writers of one key are ordered by a lock on that key value of that index, taken before the check and released once the row’s entry is appended.
- The check runs before the row is placed, so a refused write wrote nothing. Only a write that changes a key column is checked; changing a covered column is not.
- A busy holder makes a statement that has written nothing wait for the holder to commit or roll back, then run again. Row 2 onward of a multi-row
INSERTis refused with the retryableTXN_CONFLICTinstead. - Checked per row, immediately.
UPDATE t SET k = k + 1over consecutive keys is refused, although the SQL standard allows it.
kdbs> CREATE UNIQUE INDEX ux_passenger_name ON passengers(name)
CREATED INDEX name=ux_passenger_name on=passengers index_oid=3 root_page=158 key_width=33 entry_width=41 entries=0
kdbs> INSERT INTO passengers VALUES ('Park Jiho', 1, NULL)
ERR unique index 'ux_passenger_name' on (name): (Park Jiho) is already held by tuple key 3 (byte 31)
CREATE UNIQUE INDEX checks the existing rows while it builds. A duplicate refuses the statement, naming both rows, and the partly built tree is freed. Reads do not change: a unique index is probed exactly like an ordinary one.
Building over existing rows
CREATE INDEX on a populated table walks every row and adds an entry for each distinct key value across the row’s older versions too, so a reader with an older snapshot finds its version. The catalog row is published only after the build ends, and a failed build frees the tree it filled. An index is therefore complete or absent, never partial.
Example
Run against the sample tables. The sample already has the index ix_tickets_passenger; the example adds a second one:
kdbs> CREATE INDEX ix_passenger_name ON passengers(name) COVERING (member)
CREATED INDEX name=ix_passenger_name on=passengers index_oid=2 root_page=157 key_width=33 entry_width=42 entries=0
kdbs> SHOW INDEXES
index_oid,name,rel_oid,rel_name,keys,covering,root_page,key_width,entry_width,height,entries,unique
1,ix_tickets_passenger,4039,tickets,passenger_id,flight_id,baggage_kg,154,9,33,1,9,0
2,ix_passenger_name,4025,passengers,name,member,157,33,42,1,8,0
kdbs> ANALYZE SELECT * FROM passengers WHERE name = 'Park Jiho' AND member = 1
analyze rows=0 class=JoinSelect steps=1 examined=0 pages=1 opens=1 pattern_id=0x33bf2b0d86d56353 fetch_id=0xf78f0ea975a4a9ba
class=JoinSelect steps=1 hoisted=0
step 0 IndexProbe passengers
filter 0:0.1 = 'Park Jiho'
filter 0:0.2 = 1
project * (4 column(s) of step 0)
step 0 IndexProbe passengers opens=1 examined=0 matched=0 pages=1 index_scanned=1 index_filtered=1
Park Jiho is not a member (member is 0), so the covered member column ruled the row out on the entry (index_filtered=1) and the table was not read (examined=0).
What it guarantees
On the trust ladder, a secondary index is authoritative with full coverage, one rung below the primary-key tree:
| Structure | Authoritative for | Maintained on |
|---|---|---|
| Primary-key B+ tree | every key | every write |
| Secondary index | every key value | every write |
| Cabin | values queries have observed | every write, for observed values |
| Waystone trail | nothing (advisory) | nothing |
An index that finds no entries is an authoritative “no rows” without opening the table. A trail may never replace an index step, because an index returns a set and a trail cannot prove a set is complete.
What it costs
- One appended entry per index for every
INSERT, and for everyUPDATEthat changes a key or covered column.COVERINGcolumns widen every entry, and since entries sort by the whole entry, they also widen the tree’s internal nodes. - A unique index adds a check and a key lock to every write that changes its key. Measured at commit
9bf559e2on one core withrelaxeddurability (bench/v3.2.0/results-bx-close-v3.2.0-62-g9bf559e2.md): about 5 µs more perINSERTand 7 µs more perUPDATEof its column, flat from 200 to 10,000 rows. An ordinary index cost about 0.3 µs per statement. - Superseded entries are never reclaimed. Each costs space and a skipped read.
CREATE INDEXandDROP INDEXtake an exclusive lock on the table. They wait for open writes and running reads of it, and block new writes until they finish. A wait that reaches the lock fault net (lock_wait_fault_net_ms, default 1 s) is refused with the retryableTXN_CONFLICT. Both are transactional:ROLLBACKundoes them.
How to observe it
SHOW INDEXES: one row per index from thesys.indexesview, with key and covered columns in declared order,heightandentrieswalked from the tree, andunique(1for a unique index).ANALYZE <select>: the step kind (IndexProbeorIndexRange) and per-step counters such asindex_scanned,index_resolvedandindex_filtered. Ifindex_filteredstays at zero, aCOVERINGclause has bought only its write cost.SHOW ACCESS:IndexProbeandIndexRangeshapes per table and column.
Configuration
| Key | Default | Effect |
|---|---|---|
indexes | on | A read-path switch. off makes an index step take the walk it would take without the index. The compiled plan stays the same, so ANALYZE still shows IndexProbe. |
There is no switch for index maintenance, because an unmaintained index gives wrong answers. To remove the write cost, use DROP INDEX.
Limitations
UNIQUEis spelled only asCREATE UNIQUE INDEX. There is noUNIQUEcolumn or table constraint inCREATE TABLE.- A unique index’s key columns cannot be nullable, like every index’s.
CREATE UNIQUE INDEXover string keys that share their first 32 bytes costs time quadratic in the number of such rows, because each row’s check walks every entry of the shared prefix.- A unique check can wait on a transaction that only touched a row with a stale entry for the key. That is an unneeded wait, never an admitted duplicate.
- At most 4 key columns and 8 covered columns. Over the cap is refused, never truncated.
- Key and covered columns cannot be nullable.
IS NULLis answered by a scan. - No index on the primary key; the clustered tree already is one.
- No expression, partial or descending indexes.
ORDER BYis never served from an index; a sort step stays.- Only
BTREEtables can carry an index. Every new table is one. - An index name is unique across the instance.
- An index beats a Cabin on the same column.
CREATE INDEXdoes not drop the Cabin; it is no longer probed, andDROP CABINfrees its memory.