# `keys`, `xkey`

_Get or set key columns of a table_

## `keys`

_Key columns of a table_
```syntax
keys x    keys[x]
```

Where `x` is a table (by value or reference), returns the primary key columns of `x` as a symbol vector, which is empty if there are none.
```q
q)trade:([]time:09:30:00.000 09:31:00.000;sym:`a`b;price:10.75 11.5;size:100 200)
q)keys trade         / no keys
`symbol$()
q)keys`trade
`symbol$()
q)`sym xkey`trade    / define a key
`trade
q)keys`trade
,`sym
```

## `xkey`

_Set specified columns as primary keys of a table_
```syntax
x xkey y    xkey[x;y]
```

Where symbol atom or vector `x` lists columns in table `y`, which is passed by

- value, returns
- [reference](glossary.md#reference-pass-by), updates

`y` with `x` set as the primary keys.
The key columns move to the front of the table. If `y` is already keyed, its existing key is replaced, and `()` as `x` removes the key.
Key values do not need to be unique.
```q
q)trade:([]time:09:30:00.000 09:31:00.000;sym:`a`b;price:10.75 11.5;size:100 200)
q)keys trade
`symbol$()
q)`sym xkey trade     / return table with primary key sym
sym| time         price size
---| -----------------------
a  | 09:30:00.000 10.75 100
b  | 09:31:00.000 11.5  200
q)keys trade          / trade has not changed
`symbol$()
q)`sym xkey `trade    / pass trade by reference updates the table in place
`trade
q)keys trade          / sym is now primary key of trade
,`sym
q)`time xkey trade    / replace the key
time        | sym price size
------------| --------------
09:30:00.000| a   10.75 100
09:31:00.000| b   11.5  200
q)() xkey trade       / remove the key
sym time         price size
---------------------------
a   09:30:00.000 10.75 100
b   09:31:00.000 11.5  200
```

---

[Enkey, Unkey](enkey.md)


[`.Q.ff`](dotq.md#ff-append-columns) (append columns)


[Dictionaries](dictsandtables.md),
[Tables](table.md),
[Metadata](metadata.md)
