Back to Gotchas & Edge Cases

Attributes · Gotchas & Edge Cases · Practice Question

What Does Applying `s#` to a Table Do?

Sign in to track your progress

Question

What is the effect of applying the sorted attribute directly to a table (rather than to an individual column)?

Solution

/ Simple (unkeyed) table — `s# applies `p# to the FIRST column
t: ([] col1: til 5; col2: `a`b`c`d`e)
meta t           / col1: no attribute, col2: no attribute

meta `s#t        / col1: `p, col2: no attribute
/ Assign the result (t: `s#t) to keep it

/ Single-keyed table — `s# applies `s# to the KEY column
kt: ([col1: til 5] col2: `a`b`c`d`e)
meta `s#kt       / col1 (key): `s

/ Multi-keyed table — `s# applies `p# to the FIRST key column only
mkt: ([k1: til 5; k2: `a`b`c`d`e] col3: 1 2 3 4 5)
meta `s#mkt      / k1: `p, k2: no attribute, col3: no attribute

Explanation

Applying s# to a table is a shorthand that differs from applying it to a column list. The behaviour depends on the table type:

Simple (unkeyed) table: s# applies the parted attribute (p#) to the first column of the table. This may seem counterintuitive — the name says "sorted" but the result is "parted". The rationale is that kdb+ interprets a sorted simple table as one where the first column has contiguous groups (since a sorted list of non-unique values forms contiguous blocks of equal values).

Single-keyed table: s# applies the sorted attribute to the key column. This is the semantically consistent case — a sorted keyed table is one where the key is in ascending order, which is the exact structural guarantee s# represents.

Multi-keyed table: s# applies the parted attribute to the first key column only. The remaining key columns and value columns are unaffected.

Practical use:

The most common use of s# on a table is for step-function lookup on a keyed table — looking up "the most recent value as of a given key":

rates: ([time: 09:00 09:30 10:00 10:30] rate: 1.25 1.27 1.26 1.28)
rates: `s#rates
rates 09:45      / rate| 1.27 — the row for 09:30, the most recent key ≤ 09:45

For applying attributes to individual columns in production code, the explicit @[table; column; attribute] form or update `attr#col from `t is clearer and less ambiguous than applying s# to the whole table.