Kdb+ supports keyed tables, these tables have one or more columns designated as primary keys, allowing the use of their unique values to lookup entries.

Create a Keyed Table

A keyed table is a dictionary from one table of keys to another table of values with an equal number of rows. We can define it as such or we can use the shorter table syntax. Where we place the key columns inside square braces.

Common Keyed Table Functions

The functions xkey and 0!,1!,2!.. allow setting and removing key columns:

Upserting Data into a Table

Whereas insert always appended data to unkeyed tables for keyed tables we use upsert. Upsert has two different behaviours, if there is an existing key -> update the values else if it's a new key -> insert.

You do not need to upsert all value columns.

  • If the keys do not already exist, any specified columns will be inserted
    unspecified columns will be filled with appropriate nulls.
  • If the keys already exist, specified columns will be overwritten with the new value
    other unspecified columns will remain unchanged.

Multiple Key Columns

Tables with more than one key column use compound keys for access and upserts. New Data must contain values for all key columns to allow upserts to succeed.

Selecting Data

Keyed tables can be accessed in many ways including:

  1. qSQL - it provides a universal wrapper for accessing keyed and unkeyed tables.
  2. Id Lookup
    1. Single - kt `a
    2. Multiple - kt[flip enlist `c`d]
  3. Table Lookup - kt ([] id:`a`b )
  4. Table #Take - ([] id:`a`b )#kt

Compound keys work similar to single keys, the table format retrieving values is recommended as being more clear in it's intent and easier for other developers to read.

Non-Unique Keys

One feature to be aware of is that key uniqueness is not enforced on table creation or when using xkey. Below we demonstrate how we can create a table with repeated keys and the behaviour of accessing such a table.