Back to The Four Attributes

Attributes · The Four Attributes · Practice Question

When Would You Use Each Attribute?

Sign in to track your progress

Question

When would you choose each of the four kdb+ attributes — sorted, unique, parted, and grouped?

Solution

/ Use `s# when: data is sorted and you need fast range lookups
quote: ([] time:09:30:00 09:30:01 09:30:05; sym:`AAPL`MSFT`AAPL; bid:185.1 410.0 185.3)
update `s#time from `quote
select from quote where time within 09:30:00 09:30:02

/ Use `u# when: each value appears exactly once and you need fast lookup
instRef: `u# distinct quote`sym

/ Use `p# when: data is sorted by value into contiguous blocks (after xasc)
`sym xasc `:/hdb/2025.01.01/trade/
@[`:/hdb/2025.01.01/trade/; `sym; `p#]

/ Use `g# when: data arrives in unsorted order but fast symbol lookup is needed
@[`trade; `sym; `g#]    / apply to RDB sym column at startup

Explanation

Use sorted `s# when:

  • The data is already in ascending order (or you can sort it cheaply once)
  • You need fast range queries (where time within 09:30 10:00) or step-function lookups
  • You can guarantee that future appends will only add values ≥ the current maximum

Sorted is the least flexible — it breaks the moment an out-of-order value is appended. Reserve it for columns that are naturally monotonically increasing (time columns, sequence numbers) or are fully sorted once and never appended to.

Use unique `u# when:

  • Each value must appear exactly once (instrument masters, user IDs, configuration keys)
  • You want fast lookup by value (note that u# does not enforce uniqueness — appending a duplicate just removes the attribute)
  • The data is a reference table that changes rarely and in controlled ways

Use parted `p# when:

  • The data has been explicitly sorted by value into contiguous groups (via xasc)
  • You need fast block reads on the HDB (the primary use case)
  • You will not append to the data after applying the attribute (or will re-sort if you do)

Parted is the right choice for on-disk HDB data because the EOD sort produces exactly the contiguous grouping that p# requires.

Use grouped `g# when:

  • Values appear multiple times in no particular order (live market data, RDB tables)
  • Data is continuously appended and the sort order cannot be maintained
  • You need fast symbol-filtered queries on in-memory tables throughout the day

Grouped is the most flexible — it works on any data regardless of order and survives appends. It uses more memory than the others (the inverted index stores all row positions for every distinct value) and is not suitable for on-disk storage at scale.