New York kdb Training 2019
Spaces still available. Register now to learn Kdb+.

Kdb+ Keyword Function Reference List

This page is intended as a one page quick lookup of kdb keywords, functions, variables grouped by their area of functionality. Those of you on our kdb+ training course will find a similar function listing printed at the back of your reference booklet.

A printable kdb+ cheat sheet is also available.

io 0:0:Prepare. The dyadic prepare text function takes a separator character as its first argument and a table or a list of columns as its second. The result is a list of character strings containing text representations of the rows of the second argument separated by the first.
Example: show csv 0: ([]a:1 2 3;b:`x`y`z)

Save. The dyadic save text function takes a file handle as its first argument and a list of character strings as its second. The strings are saved as lines in the file. The result of the prepare text function can be used as the second argument.

Load. The dyadic load text function takes file format description as its first argument and a file handle or a list of character strings as its second.
Example: t:("SS";enlist" ")0:`:/tmp/txt /load 2 columns from space delimited file

The format description takes the form of a list of types and either a list of widths for each field if the data to be loaded is fixed width, or the delimiter if delimited, if the delimiter is enlisted the first row of the input data will be used as column names and the data is loaded as a table, otherwise the data is loaded as an list of values for each column.
Example: t:("IFC D";4 8 10 6 4) 0: `:/q/Fixed.txt /reads a text file containing fixed length records

note that when loading text you should specify the identifier as an uppercase letter, to load a field as a nested character column or list rather than symbol use '*' as the identifier and to skip a field from the load use ' '.

Optionally, load text can take a three-item list as its second argument, containing the file handle, an offset at which to begin reading, and a length to read.
Example: ("SS";csv)0:(`:/tmp/data.csv;x;x+100000)

Also works for key/value pairs.
Example: show "S=;"0:"one=1;two=2;three=3"
11Write to standard output
Example: 1 "String vector here "
1:1:The 1: dyadic function is used to read fixed length data from a file or byte sequence. The left argument is a list of types and their widths to read, and the right argument is the file handle or byte sequence.
Example: ("ich";4 1 2)1:0x00000000410000FF00000042FFFF

Optionally, it can also take a three-item list as its second argument, containing the file handle, an offset at which to begin reading, and a length to read.
Example: ("ii";4 4)1:(`:/tmp/data;x;x+100000)
22write to standard error
Example: 2 "String vector here "
2:2:The 2: function is a dyadic function used to dynamically load C functions into Kdb+. Its left argument is a symbol representing the name of the dynamic library from which to load the function. Its right argument is a list of a symbol which is the function name and an integer which is the number of arguments the function to be loaded takes. getenvgetenvReturns the value of the given environment variable.
Example: getenv `PATH
hcounthcountGets the size in bytes of a file as a long integer.
Example: hcount`:c:/q/test.txt

Gets the size in bytes of a file as a long integer.
Syntax: hcount fh
Example: hcount `:readme.txt
hdelhdelDelete a file.
Syntax: hdel fh
Example: hdel `:readme.txt
hsymhsymConverts its symbol argument into a file name, or valid hostname, ipaddress
Example: hsym`10.43.23.197
read0read0The read0 function reads a text file, returning a list of lines.Lines are assumed delimited by either LF or CRLF, and the delimiters are removed.
Example: read0`:test.txt

Optionally, read0 can take a three-item list as its argument, containing the file handle, an offset at which to begin reading, and a length to read.
Example: read0(`:/tmp/data;0;0+100000)
read1read1The read1 function reads a file as a list of bytes.
Example: read1`:test.txt

Optionally, read1 can take a three-item list as its argument, containing the file handle, an offset at which to begin reading, and a length to read.
Example: read1(`:/tmp/data;0;0+100000)
rloadrloadThe rload function loads a splayed table. This can also be done, as officially documented, using the get function. savesaveThe save function saves data to the filesystem.
Example: t:([]x: 1 2 3; y: 10 20 30);save `t
setsetDyadic functional form of assignment often used when saving objects to disk. set is used mainly to write data to disk and in this case the left argument is a file path, i.e. a symbol atom beginning with a :
Example: `:c:/q/testTradeTable set trade
setenvsetenvDyadic function which changes or adds an environment variable.
Example: `name setenv value
math absabsReturns the absolute value of a number. i.e. the positive value
Syntax: abs X
Example: abs -2 -1 0 1
acosacosAccepts a single argument in radians and returns the arc cosine.
Syntax: acos[radians]
Example: acos 3.141593
allallFunction all returns a boolean atom 1b if all values in its argument are non-zero, and otherwise 0b.It applies to all data types except symbol, first converting the type to boolean if necessary.
Syntax: r:all A
Example: all 1 2 3=1 2 4

Function all returns a boolean atom 1b if all values in its argument are non-zero, and otherwise 0b.It applies to all data types except symbol, first converting the type to boolean if necessary.
Syntax: any X
Example: any 1010111001b
anyanyReturn 1b if there are any non-zero values in it's argument, otherwise return 0b.
Syntax: any X
Example: any 1010111001b
asinasinAccepts a single argument in radians and returns the arc sine.
Syntax: sin[radians]
Example: sin 3.141593
atanatanAccepts a single argument in radians and returns the arc tan.
Syntax: atan[radians]
Example: atan 3.141593
ceilingceilingWhen passed floating point values, return the smallest integer greater than or equal to those values.
Syntax: ceiling X
Example: ceiling 1.2 3.4 5.8
coscosAccepts a single argument in radians and returns the cosine.
Syntax: cos[radians]
Example: cos 3.141593
crosscrossReturns the cross product (i.e. all possible combinations) of its arguments.
Syntax: R:X cross Y
exceptexceptReturns all elements of its left argument that are not in its right argument.
Syntax: x except y
Example: 1 3 2 4 except 1 2
expexpThis function computes e to the power of x, where e is the base of the natural logarithms. Null is returned if the argument is null.
Syntax: R:exp 1
flipfliptransposes its argument, which may be a list of lists, a dictionary or a table.
Example: flip (`a`b`c; 1 2 3)
floorfloorWhen passed floating point values, return the greatest integer less than or equal to those values.
Syntax: floor X
Example: floor 1.2 3.4 5.8
interinterReturns all elements common to both arguments
Syntax: x inter y
Example: 1 3 2 4 inter 1 2 6 7
invinvinv computes the inverse of a non-singular floating point matrix.
Syntax: r:inv x
Example: inv (3 3#2 4 8 3 5 6 0 7 1f)
loglogReturns the natural logarithm of it's argument
Syntax: log X
Example: log 0 1 2.71828
maxmaxThe max function returns the maximum of its argument. If the argument is an atom, it is returned unchanged.
Syntax: max a
Example: max 1

The max function returns the maximum of its argument. If the argument is a list, it returns the maximum of the list. The list may be any datatype except symbol. Nulls are ignored, except that if the argument has only nulls, the result is negative infinity.
Syntax: max L
Example: max 1 2 3 10 3 2 1
maxsmaxsThe maxs function returns the maximums of the prefixes of its argument. If the argument is an atom, it is returned unchanged.
Syntax: maxs a
Example: maxs 1

The maxs function returns the maximums of the prefixes of its argument. If the argument is a list, it returns the maximums of the prefixes of the list. The list may be any datatype except symbol. Nulls are ignored, except that initial nulls are returned as negative infinity.
Syntax: maxs L
Example: maxs 1 2 3 10 3 2 1
mcountmcountThe mcount verb returns the N-item moving count of the non-null items of its numeric right argument. The first N items of the result are the counts so far, and thereafter the result is the moving count.
Syntax: r:N mcount L
Example: 3 mcount 0N 1 2 3 0N 5
mdevmdevThe mdev verb returns the N-item moving deviation of its numeric right argument, with any nulls after the first element replaced by zero. The first N items of the result are the deviations of the terms so far, and thereafter the result is the moving deviation. The result is floating point.
Syntax: r:N mdev L
Example: 2 mdev 1 2 3 5 7 10
medmedComputes the median of a numeric list.
Syntax: r:med L
Example: med 10 34 23 123 5 56
minminReturns the minimum value within a list
Syntax: min X
Example: 3~min 100 10 3 22
mmaxmmaxThe mmax verb returns the N-item moving maximum of its numeric right argument, with nulls after the first replaced by the preceding maximum. The first N items of the result are the maximums of the terms so far, and thereafter the result is the moving maximum.
Syntax: r:N mmax L
Example: 3 mmax 2 7 1 3 5 2 8
mmummummu computes the matrix multiplication of floating point matrices. The arguments must be floating point and must conform in the usual way, i.e. the columns of x must equal the rows of y.
Syntax: r:x mmu y
Example: (2 4#2 4 8 3 5 6 0 7f) mmu (4 3#`float$til 12)
modmodx mod y returns the remainder of y%x. Applies to numeric types, and gives type error on sym, char and temporal types.
Syntax: r:L mod N
Example: -3 -2 -1 0 1 2 3 4 mod 3
msummsumThe msum verb returns the N-item moving sum of its numeric right argument, with nulls replaced by zero. The first N items of the result are the sums of the terms so far, and thereafter the result is the moving sum.
Syntax: r:N msum L
Example: 3 msum 1 2 3 5 7 11
negnegThe function neg negates its argument, e.g. neg 3 is -3. Applies to all data types except sym and char. Applies item-wise to lists, dict values and table columns.
Syntax: r:neg X
Example: neg -1 0 1 2
prdprdAggregation function, also called multiply over, applies to all numeric data types. It returns a type error with symbol, character and temporal types. prd always returns an atom and in the case of application to an atom returns the argument.
Syntax: ra:prd L
Example: prd 2 4 5 6
randrandIf X is an atom 0, it returns a random value of the same type in the range of that type:
Syntax: r: rand 0
Example: rand each 3#0h

If X is a positive number, it returns a random number of the same type in the range [0,X)
Syntax: r: rand a
Example: rand 100

If X is a list, it returns a random element from the list:
Syntax: r:rand L
Example: rand 1 30 45 32
ratiosratiosThe uniform function ratios returns the ratio of consecutive pairs. It applies to all numeric data types.
Syntax: r:ratios L
Example: ratios 1 2 4 6 7 10
reciprocalreciprocalReturns the reciprocal of its argument. The argument is first cast to float, and the result is float.
Syntax: r:reciprocal X
Example: reciprocal 0 0w 0n 3 10
signumsignumThe function signum returns -1, 0 or 1 if the argument is negative, zero or positive respectively. Applies item-wise to lists, dictionaries and tables, and to all data types except symbol.
Syntax: r:signum X
Example: signum -2 0 1 3
sinsinAccepts a single argument in radians and returns the sine.
Syntax: sin[radians]
Example: sin 3.141593
sqrtsqrtReturns the square root of it's argument
Syntax: sqrt X
Example: sqrt 0 1 4 9
sumsumReturns the sum total of a list
Syntax: sum X
Example: 14~sum 2 4 8
tantanAccepts a single argument in radians and returns the tan.
Syntax: tan[radians]
Example: tan 3.141593
unionunionDyadic function which returns the union of its arguments, i.e. returns the distinct elements of the combined lists respecting the order of the union.
Syntax: R:X union Y
Example: 1 2 3 union 2 4 6 8
varvarAggregation function which applies to a list of numerical types and returns the variance of the list. Again for the usual reason it works on the temporal types.
Syntax: r:var X
Example: var 10 343 232 55
wavgwavgDyadic where first arg is weights, second is values, returns the weighted average.
Syntax: X wavg Y
Example: 7=1 1 2 wavg 5 5 9
wsumwsumThe weighted sum aggregation function wsum produces the sum of the items of its right argument weighted by the items of its left argument. The left argument can be a scalar, or a list of equal length to the right argument. When both arguments are integer lists, they are converted to floating point. Any null elements in the arguments are excluded from the calculation.
Example: 2 3 4 wsum 1 2 4
xexpxexpThis is the dyadic power function.
Syntax: r:xexp[X;Y]
Example: 2 xexp 3
joins ajajAsof Join - Joins tables based on nearest time.
Syntax: aj[c1...cn;t1;t2]
Example: aj[`sym`time; trade; quote]
ejejEqui Join - Same as ij but allows specifying the column names.
Syntax: ej[c;t1;t2]
Example: ej[sym; trade; quote]
ijijInner Join - Where matches occur between t and kt on primary key columns, update or add that column. Non-matches are not returned in the result.
Syntax: t ij kt
Example: ([] a:1 2; b:3 4) ij ([a:2 3]; c:`p`o)
ljljLeft Join - for each row in t, return a result row, where matches are performed by finding the first key in kt that matches. Non-matches have any new columns filled with null.
Syntax: t lj kt
Example: ([] a:1 2; b:3 4) lj ([a:2 3]; c:`p`o)
pjpjPlus Join - Same principle as lj, but existing values are added to where column names match.
Syntax: t pj kt
ujujUnion Join - Combine all columns from both tables. Where possible common columns append or new columns created and filled with nulls.
Syntax: t1 uj t2
Example: ([] a:1 2; b:3 4) uj ([] a:2 3; c:`p`o)
wjwjWindow Join - Join all aggregates within a given time window to a corresponding table.
Syntax: wj[w;c;t;(q;(f0;c0);(f1;c1))]
Example: wj[w;`sym`time;trade; (quote;(max;`ask);(min;`bid))]
misc binbinbin gives the index of the last element in x which is <=y. The result is -1 for y less than the first element of x.It uses a binary search algorithm, which is generally more efficient on large data than the linear search algorithm used by ?.The items of the left argument should be sorted non-descending although q does not enforce it. The right argument can be either an atom or simple list of the same type as the left argument.
Syntax: r:x bin y
Example: 0 2 4 6 8 10 bin 5
colscolsReturn a symbol list of column names for a given table, or a list of keys for a dictionary.
Syntax: cols[table]
Example: cols trade
evalevalThe eval function is the dual to parse and can be used to evaluate a parse tree as returned by that function (as well as manually constructed parse trees).
Example: eval parse "2+3"
fillsfillsUniform function that is used to forward fill a list containing nulls.
Syntax: r:fills A
Example: fills (0N 2 3 0N 0N 7 0N)
groupgroupGroups the distinct elements of its argument, and returns a dictionary whose keys are the distinct elements, and whose values are the indices where the distinct elements occur. The order of the keys is the order in which they are encountered in the argument.
Syntax: D:group L
Example: group "mississippi"
iasciascUniform function that returns the indices needed to sort the list argument.
Syntax: r:iasc L
Example: iasc (2 1 3 4 2 1 2)
idescidescUniform function that returns the indices needed to sort the list argument.
Syntax: r:idesc L
Example: idesc (2 1 3 4 2 1 2)
keykeyGiven a keyed table, Returns the key columns of a keyed table
Syntax: r:key KT
Example: key ([s:`q`w`e]g:1 2 3;h:4 5 6)

Given a directory handle, returns a list of objects in the directory
Syntax: r:key DIR
Example: key`:c:/q

Given a file descriptor, returns the descriptor if the file exists, otherwise returns an empty list
Syntax: r:key filedesc
Example: key`:c:/q/sp.q

Given a foreign key column, returns the name of the foreign key table

Given a simple list, returns the name of the type as a symbol
Syntax: key L
Example: key each ("abc";101b;1 2 3h;1 2 3;1 2 3j;1 2 3f)

Given an enumerated list, it returns the name of the enumerating list
Syntax: key eL

Given a positive integer, it acts like til
Syntax: key n
Example: key 10
keyskeysMonadic function which takes a table as argument and returns a symbol list of the primary key columns of its argument and in the case of no keys it returns an empty symbol list. Can pass the table by reference or by value
Syntax: keys T
Example: keys ([s:`q`w`e]g:1 2 3;h:4 5 6)
lastlastReturns the item at the end of the list or table
Syntax: last X
Example: 7~last 2 3 4 7
overoverThe over adverb takes a function of two arguments on its left, and creates a new atomic function that applies to successive items of its list argument. The result is the result of the last application of the function.
Syntax: r:f over L
Example: {x+2*y} over 2 3 5 7
peachpeachThe parallel each adverb is used for parallel execution of a function over data. In order to execute in parallel, q must be started with multiple slaves (-s).
Example: {sum exp x?1.0}peach 2#1000000
rankrankThe uniform function rank takes a list argument, and returns an integer list of the same length. Each value is the position where the corresponding list element would occur in the sorted list. This is the same as calling iasc twice on the list.
Syntax: r:rank L
Example: rank 2 7 3 2 5
scanscanThe scan adverb takes a function of two arguments on its left, and creates a new uniform function that applies to successive items of its list argument. The result is a list of the same length.
Syntax: r:f scan L
Example: {x+2*y} scan 2 3 5 7
svsvscalar from vector- dyadic function that performs different functions on different data types.

In the special case where the left argument is a `, it returns the concatenated right arg with each element terminated by a newline ( on unix, on windows).
Example: ` sv ("asdf";"hjkl")

When applied to a symbol list where the first element is a file handle and the left argument is a ` sv returns a file handle where the elements of the list are separated by slashes-this is very useful when building write paths
Example: wp:`:c:/q/data; (`)sv wp,`2005.02.02,`trade

In the case of using sv on a symbol list where the left argument is a ` it returns the elements separated by . this is useful for generating files with the required extension
Example: fp:`c:/q/sym; hsym` sv fp,`txt

Evaluates base value
Syntax: rl: N sv L
Example: 10 sv 23 45 677

Converts bytes to ints base 256
Example: 0x0 sv "x"$12 3 4 5
ungroupungroupThe ungroup function monadic function ungroups a table. valuevalueThis is the same verb as get but is typically used for different things.

When passed an object by reference it returns the value of that object
Example: D:`q`w`e!1 2 3 ; value `D

When passed object has an enumerated type, it returns the corresponding symbol list:

When passed object is a lambda, it returns a list:(bytecode;params(8);locals(24);globals(32),Constants(96)

When passed object is a projection, it returns a list where projected function is followed by parameters:
Example: value +[2]

When passed object is a composition, it returns a list of composed functions:
Example: value rank

When passed object is a primitive it returns an internal code:
Example: value each (::;+;-;*;%)

When passed object is an adverb modified verb, it strips the adverb:
Example: value (+/)

When passed a string with valid q code, it evaluates it:
Example: value"b:`a`b`c"

When passed a list, applies the first element to the rest:
Example: value(+;1;2)

If the first element of the list is a symbol, it is evaluated first:
Example: value(`.q.neg;2)
vsvsThe dyadic vs vector from scalar function has several uses.

With 0b on the left hand side, it returns the bit representation of the integer on the right hand side.
Example: 0b vs 1024h

With 0x0 on the left hand side, it returns the byte representation of the number on the right hand side.
Example: 0x0 vs 1024

With ` on the left hand side splits symbols on the . ; breaks file handles into directory and file parts; and domain names into components.
Example: ` vs`:/foo/bar/baz.txt
essential countcountReturns the number of items in a list, for atoms 1 is returned eacheachTakes a function on its left, and creates a new function that applies to each item of its argument.
Example: count each (1 2;`p`o`i)

Adverb that takes a function as it's first argument and applies it to each item of it's separate argument.
Syntax: f each l
Example: reverse each (1 2 3;7 8 9)
enlistenlistTake a single argument and return it wrapped it in a list.
Syntax: enlist X
Example: enlist 1
ininReturns a boolean indicating which items of x are in y. Result is same size as x
Syntax: x in y
Example: 1 4 5 in 10 5 11 1
keykeyGiven a dictionary, it returns the keys
Syntax: r:key D
Example: key (`q`w`e!(1 2;3 4;5 6))
notnotThe logical not function returns a boolean result 0b when the argument is not equal to zero, and 1b otherwise. Applies to all data types except sym. Applies item-wise to lists, dict values and table columns.
Syntax: r:not X
Example: not -1 0 1 2
nullnullThe function null returns 1b if its argument is null.Applies to all data types. Applies item-wise to lists, dict values and table columns.
Syntax: r:null X
Example: null 0 0n 0w 1 0n
ororThe verb or returns the maximum of its arguments. It applies to all data types except symbol.
Syntax: r:L or Y
Example: -2 0 3 7 or 0 1 3 4
razerazeThe raze function joins items of its argument, and collapses one level of nesting. To collapse all levels, use over i.e. raze/[x]. An atom argument is returned as a one-element list.
Example: raze (1 2;3 4 5)
reversereverseUniform function that reverses the items of its argument. On dictionaries, reverses the keys; and on tables, reverses the columns
Example: reverse 1 2 3 4
rotaterotateThe uniform verb rotate takes an integer left argument and a list or table right argument. This rotates L by N positions to the left for positive N, and to the right for negative N.
Syntax: r:N rotate L
Example: 2 rotate 2 3 5 7 11
showshowMonadic function used to pretty-print data to the console.
Example: show 10#enlist til 10
stringstringThe function string converts each atom in its argument to a character string. It applies to all data types.
Syntax: r:string X
Example: string ([]a:1 2 3;b:`ibm`goog`aapl)
sublistsublistThe verb sublist returns a sublist of its right argument, as specified by its left argument. The result contains only as many items as are available in the right argument. If X is a single integer, it returns X items from the beginning of Y if positive, or from the end of Y if negative.If X is an integer pair, it returns X 1 items from Y, starting at item X 0.
Syntax: r:X sublist Y
Example: 3 sublist 2 3 5 7 11
systemsystemMonadic function which executes system commands i.e. OS commands.
Example: system"pwd"
tablestablesMonadic function which returns a list of the tables in the specified namespace, this list is sorted.
Example: tables`.
tiltiltakes positive integer n and returns list of numbers from 0 to n-1
Example: til 9
typetypeThis monadic function returns the type of its argument as a short integer. Negatives numbers are for atoms, positive numbers are for lists, and zero is a general K list. valuevalueWhen passed a dictionary, This gets the values of a dictionary.
Syntax: r: value D
Example: value `q`w`e!1 2 3
viewsviewsMonadic function which returns a list of the currently defined views in the root directory, this list is sorted and has the `s attribute set.
qsql deletedeletetwo Formats. Either delete rows or delete columns from table.
Syntax: delete col from t. delete row from t where filter.
Example: delete from t where price<10
differdifferThe uniform function differ returns a boolean list indicating whether consecutive pairs differ. It applies to all data types. (The first item of the result is always 1b)
Syntax: r:differ A
fbyfbyThis verb is typically used with select, and obviates the need for many common correlated subqueries. It aggregates data in a similar way to by and computes a function on the result.
Syntax: (aggr;data) fby group
fkeysfkeysThe function fkeys takes a table as an argument and returns a dictionary that maps foreign key columns to their tables. insertinsertInsert appends records to a table.
Syntax: `table insert records
Example: `x insert (`s`t;40 50)
metametaThe meta function returns the meta data of its table argument, passed by value or reference.
Syntax: K:meta T
Example: meta ([s:`q`w`e]g:1 2 3;h:4 5 6)
selectselectSelect rows from a table.
Syntax: select columns by groups from table where filters
Example: select max price by date,sym from trade where sym in `AA`C
updateupdateModify the table to update existing values or to create a new column.
Syntax: update col by c2 from t where filter
Example: update price:price+10 from t where sym=`A
upsertupsertFunctional form of inserting into a table using the , primitive. It is called upsert because when applied to keyed tables it performs an insert if the key value is not there and otherwise performs an update.
Syntax: r: T upsert newEntries
Example: ([s:`q`w`e]r:1 2 3;u:5 6 7) upsert (`q;100;500)
wherewhereWhere the argument is a boolean list, this returns the indices of the 1's
Example: where 21 2 5 11 33 9>15
withinwithinThe right argument of this primitive function is always a two-item list. The result is a boolean list with the same number of items as the left argument. The result indicates whether or not each item of the left argument is within the bounds defined by the right argument.
Example: 1 3 10 6 4 within 2 6

The within function also applies to chars and syms because both are ordered
Example: "acyxmpu" within "br"

The within function will also work with a pair of n-ary lists as the right argument and an atom, a n-ary list or n-by-* ragged matrix as the left argument. The results in this case take the shape of the left argument.
Example: 5 within (1 2 6;3 5 7)
wjwjWindow join is a generalization of asof join, and is available from kdb+ 2.6. asof join takes a snapshot of the current state, while window join aggregates all values of specified columns within intervals. xascxascDyadic function-sorts a table in ascending order of a particular column, sorting is order preserving among equals. Takes a symbol list or atom and a table as arguments and returns the original table sorted by the columns as specified in the first argument.
Syntax: R:C xasc T
Example: t:`sym xasc trade

It can be used to sort data on disk directly. xasc can be used to sort a splayed table on disk one column at a time without loading the entire table into memory.
Example: see notes
xbarxbarInterval bars are prominent in aggregation queries. For example, to roll-up prices and sizes in 10 minute bars:
Example: select last price, sum size by 10 xbar time.minute from trade
xcolxcolDyadic function - rename columns in a table. Takes a symbol list of column names and a table as arguments, and returns the table with the new column names. The number of column names must be less than or equal to the number of columns in the table. The table must be passed by value.
Syntax: R:C xcol T
Example: `A`S`D`F xcol trade
xcolsxcolsDyadic function - reorder columns in a table. Takes a symbol list of column names and a table as arguments and returns the table with the named columns moved to the front. The column names given must belong to the table. The table must have no primary keys and is passed by value.
Syntax: R:C xcols T
Example: xcols[reverse cols trade;trade]
xgroupxgroupThe xgroup function dyadic function groups its right argument by the left argument (which is a foreign key). xkeyxkeyDyadic function-sets a primary in a table. Takes a symbol list or atom and a table as arguments and returns the original table with a primary key corresponding to the column(s) specified in the first argument.
Syntax: R:C xkey T
Example: `r xkey ([s:`q`w`e]r:1 2 3;u:5 6 7)
xprevxprevUniform dyadic function, returns the n previous element to each item in its argument list.
Syntax: r:N xprev A
Example: 2 xprev 2 3 4 5 6 7 8
xrankxrankUniform dyadic function which allocates values to buckets based on value. This is commonly used to place items in N equal buckets.
exotic gtimegtimeThe gtime function returns the UTC datetime/timestamp for a given datetime/timestamp. Recall that the UTC and local datetime/timestamps are available as .z.z/.z.p and .z.Z/.z.P respectively. ltimeltimeThe ltime function returns the local datetime/timestamp for a given UTC datetime/timestamp. Recall that the UTC and local datetime/timestamps are available as .z.z/.z.p and .z.Z/.z.P respectively. parseparseparse is a monadic function that takes a string and parses it as a kdb+ expression, returning the parse tree. To execute a parsed expression, use the eval function.
Example: parse "{x+42} each til 10"
viewviewMonadic function which returns the expression defining the dependency passed as its symbol argument.
string likelikePerform simple pattern matching of strings.
Syntax: like[text; pattern]
Example: like[("kim";"kyle";"Jim"); "k*"]
lowerlowerMonadic that converts strings and symbols to lower case
Syntax: lower[text]
Example: `small~lower `SMALL
ltrimltrimMonadic that removes leading whitespace from strings.
Syntax: ltrim[text]
Example: "abc"~ltrim " abc"
rtrimrtrimMonadic that removes trailing whitespace from strings.
Syntax: rtrim[text]
Example: "abc"~rtrim "abc "
ssssThe function ss finds positions of a substring within a string. It also supports some pattern matching capabilities of the function like:
Syntax: r:HayStack ss needle
Example: "toronto ontario" ss "ont"
ssrssrThe function ssr does search and replace on a string.
Syntax: r:ssr[haystack; needle; replacement]
Example: ssr["toronto ontario"; "ont"; "XX"]
svsvWhen applied to a vector of strings it returns the elements of its right argument-the list of strings-separated by the left argument.
Example: "|" sv ("asdf";"hjkl")
trimtrimMonadic that removes leading and trailing whitespace from strings.
Syntax: trim[text]
Example: "abc"~trim " abc "
upperupperMonadic that converts strings and symbols to upper case
Syntax: lower[text]
Example: `BIG~upper `big
vsvsWith a character or a string on the left hand side, it tokenizes a string on the right hand side using the left hand side as the specified delimiter. It returns a vector of substrings.
Example: ","vs"one,two,three"
.z .z.a.z.aip-address ie. "." sv string `int$0x00 vs .z.a .z.ac.z.acHttp authenticate from cookie .z.b.z.bdependencies (more information than \b) .z.d.z.dgmt date .z.D.z.Dlocal date .z.f.z.fstartup file .z.h.z.hhostname .z.i.z.ipid .z.k.z.kkdb+ releasedate .z.K.z.Kkdb+ major version .z.l.z.llicense information (;expirydate;updatedate;;;) .z.o.z.oOS .z.pc.z.pcclose, h handle (already closed) .z.pg.z.pgget .z.ph.z.phhttp get .z.pi.z.piinput (qcon) .z.po.z.poopen, h handle .z.pp.z.pphttp post .z.ps.z.psset .z.pw.z.pwvalidate user and password .z.1.z.1quiet mode .z.s.z.sself, current function definition .z.t.z.tgmt time .z.T.z.Tlocal time .z.ts.z.tstimer expression (called every \t) .z.u.z.uuserid .z.vs.z.vsvalue set .z.w.z.whandle (0 for console, handle to remote for KIPC) .z.x.z.xcommand line parameters (argc..) .z.z.z.zgmt timestamp. e.g. 2013.11.06T15:49:26.559 .z.Z.z.Zlocal timestamp. e.g. 2013.11.06T15:49:26.559 .z.n.z.nGet gmt timespan (nanoseconds). e.g. 0D15:49:07.295301000 .z.N.z.NGet local timespan (nanoseconds). e.g. 0D15:49:07.295301000 .z.p.z.pGet gmt timestamp (nanoseconds). e.g. 2011.11.06D15:48:38.446651000 .z.P.z.PGet local timestamp (nanoseconds). e.g. 2011.11.06D15:48:38.446651000
adverbs ''Each Both
Operate on corresponding items on two lists of equal length.
eacheachEach Monadic
Apply monadic function at nested level rather than topmost
/:/:Each Right
Using same left argument, apply dyadic function to each item of right argument.
\:\:Each Left
Using same right argument, apply dyadic function to each item of left argument.
ScanScanScan
Apply dyadically to first two items, then use result of previous to scan forward over list
\\Scan
Apply dyadically to first two items, then use result of previous to scan forward over list
//Over
Same as scan but only returns the final result, not intermediate calculations.
OverOverOver
Same as scan but only returns the final result, not intermediate calculations.
':':Each Previous
Dyadic function applies to numbers beside each other over entire list
.Q .Q.addmonths.Q.addmonthsAdds y months to x .Q.addr.Q.addrip-address as an integer from a hostname symbol .Q.host.Q.hosthostname as a symbol for an integer ip-address .Q.chk.Q.chkfills missing tables .Q.cn.Q.cnnumber of rows for partitioned table passed by value .Q.pn.Q.pnPartition counts cached since the last time .Q.cn was called .Q.D.Q.DIn segmented dbs, partition vector with each element enlisted .Q.dd.Q.ddShorthand for ` sv x,`$string y .Q.dpft.Q.dpftSaves a table splayed to a specific partition of a database sorted (`p#) on a specified field .Q.dsftg.Q.dsftg(loop M&1000000 rows at a time - load/process/save) .Q.en.Q.enEnumerates any character columns in a table to the list sym and appends any new entries to a file in the db directory. .Q.fc.Q.fcparallel on cut .Q.fk.Q.fkreturn ` if the column is not an fkey or `tab if the column is a fkey into tab .Q.fmt.Q.fmtFormats a number .Q.fs.Q.fsLoops over file (in chunks) applying function .Q.ft.Q.ftcreates a new function that also works on keyed .Q.gc.Q.gcInvokes the garbage collector. .Q.hdpf.Q.hdpfsave all tables and notify host .Q.ind.Q.indit takes a partitioned table and (long!) indices into the table .Q.P.Q.PIn segmented dbs, contains the list of segments that have been loaded .Q.par.Q.parlocate a table (sensitive to par.txt) .Q.PD.Q.PDIn partitioned dbs, contains a list of partition locations .Q.pd.Q.pd.Q.PD as modified by .Q.view. .Q.pf.Q.pfcontains the partition type of a partitioned hdb (only) .Q.PV.Q.PVIn partitioned dbs, contains a list of partition values - conformant to date .Q.pv.Q.pv.Q.PV as modified by .Q.view. .Q.qp.Q.qpReturns 1b if given a partitioned table, 0b if splayed table, else 0 .Q.qt.Q.qtReturns 1b if x is a table, 0b otherwise. .Q.s.Q.sFormat an object to plain text (used by the q console, obeys \c setting .Q.ty.Q.tyreturns character type code of argument eg "i"=.Q.ty 1 2 .Q.u.Q.utrue if each partition is uniquely found in one segment. .Q.v.Q.vgiven file handle sym, returns the splayed table stored there, any other sym, returns global .Q.V.Q.Vreturns a table as a dictionary of column values .Q.view.Q.viewset a subview eg .Q.view 2#date
CommandLine -b-bblock client write access to a kdb+ database -f-fthis is either the script to load (*.q, *.k, *.s), or a file or directory -c-cconsole maxRows maxCols, default 25 80. This is the maximum display size of any single terminal output. -C-Cwebserver maxRows maxCols, default 36 2000. This is the maximum display size of any table shown through the web server. -e-eBoolean flag that if true causes the server to break when an error occurs including on client requests. -g-gSwitch garbage collection between immediate 1 and deferred 0 modes. -l-llog updates to filesystem -L-Lsync log updates to filesystem -o-ooffset N hours from GMT (affects .z.Z,.z.T) -p-pport which KDB server listens on (if -Port used, then server is multithreaded) -P-PDisplay precision for floating point number. (default 7, use 0 to display all available) -q-qQuiet, ie. No startup, baber text or session prompts (typically used where no console required) -r-rreplicate from Host/Port (seems to rely on log and running on same machine) -s-sstart N slaves for parallel execution -t-ttimer in N milliseconds between timer ticks. (default is 0 = no timeout) -T-Ttimeout in seconds for client queries, i.e. maximum time a client call will execute. Default is 0, for no timeout. -u-uusr:password file to protect access. File access restricted to inside start directory -U-Uusr:password file to protect access. File access unrestricted -w-wworkspace MB limit (default:2*RAM) -W-Woffset from Saturday, default is 2, meaning Monday is start of week -z-zformat used for `date$ date parsing. 0 is mm/dd/yyyy (default) and 1 is dd/mm/yyyy.
SystemCommands \\\\Exit q session \\Toggle q/k language or exit debug mode \_\_Compile q script (hide source) \*\*Execute OS command \1\1Redirect standard out to file \2\2Redirect standard error to file \a\aList tables in namespace. No parameter means current NS \b\bList dependencies in NS. No parameter means current NS \B\BInvalid dependencies in NS. No parameter means current NS \c\cReturn/set console height & width -c H W 23 79 \C\CReturn/set web browser display height & width -C H W 36 2000 \d\dReturn/set current namespace `. \e\eReturn/set error trap mode -e [0|1] 0 \f\fList functions in NS. No parameter means current NS \l\lLoad q script or database directory \o\oReturn/set local time offset in hours from GMT -o N 0N \p\pReturn/set port used \p portNumber . Note 0=no listening socket. \P\PReturn/set print precision. 0 = maximum -P N 7 \r\rDisplay replication (host;port); OR oldfile newfile /- Rename a file \s\sDisplay number of slaves used for parallel execution -s N 0 \S\SDisplay/set seed for pseudo-random number generator -S N -314159 \t\tDisplay/set timer in milliseconds. 0=timer off -t N 0 \ts\tstime and space measuring of function call \T\TDisplay/set timeout (secs) for single client call. 0=off -T N 0 \u\uReload user:password file -u F \v\vDisplay list of variables in current namespace \w\wWorkspace memory (used/heap/peak/max/mapped); OR 0 /- print internalised symbol count and memory usage \W\WDisplay/set weekday offset. 0 = Saturday -W N 2 \x\x.z.?? Reset .z function \z\zDisplay/set date conversion format from string -z [0|1] 0

Once you're more experienced at kdb, you may want to change to an alpabetically based lookup, like this very useful page at code kx.

essential

symdescriptionsyntaxeg
countReturns the number of items in a list, for atoms 1 is returned
eachTakes a function on its left, and creates a new function that applies to each item of its argument.count each (1 2;`p`o`i)
eachAdverb that takes a function as it's first argument and applies it to each item of it's separate argument.f each lreverse each (1 2 3;7 8 9)
enlistTake a single argument and return it wrapped it in a list.enlist Xenlist 1
inReturns a boolean indicating which items of x are in y. Result is same size as xx in y1 4 5 in 10 5 11 1
keyGiven a dictionary, it returns the keysr:key Dkey (`q`w`e!(1 2;3 4;5 6))
notThe logical not function returns a boolean result 0b when the argument is not equal to zero, and 1b otherwise. Applies to all data types except sym. Applies item-wise to lists, dict values and table columns. r:not Xnot -1 0 1 2
nullThe function null returns 1b if its argument is null.Applies to all data types. Applies item-wise to lists, dict values and table columns. r:null Xnull 0 0n 0w 1 0n
orThe verb or returns the maximum of its arguments. It applies to all data types except symbol.r:L or Y-2 0 3 7 or 0 1 3 4
razeThe raze function joins items of its argument, and collapses one level of nesting. To collapse all levels, use over i.e. raze/[x]. An atom argument is returned as a one-element list.raze (1 2;3 4 5)
reverseUniform function that reverses the items of its argument. On dictionaries, reverses the keys; and on tables, reverses the columnsreverse 1 2 3 4
rotateThe uniform verb rotate takes an integer left argument and a list or table right argument. This rotates L by N positions to the left for positive N, and to the right for negative N. r:N rotate L2 rotate 2 3 5 7 11
showMonadic function used to pretty-print data to the console.show 10#enlist til 10
stringThe function string converts each atom in its argument to a character string. It applies to all data types.r:string Xstring ([]a:1 2 3;b:`ibm`goog`aapl)
sublistThe verb sublist returns a sublist of its right argument, as specified by its left argument. The result contains only as many items as are available in the right argument. If X is a single integer, it returns X items from the beginning of Y if positive, or from the end of Y if negative.If X is an integer pair, it returns X 1 items from Y, starting at item X 0. r:X sublist Y3 sublist 2 3 5 7 11
systemMonadic function which executes system commands i.e. OS commands.system"pwd"
tablesMonadic function which returns a list of the tables in the specified namespace, this list is sorted.tables`.
tiltakes positive integer n and returns list of numbers from 0 to n-1til 9
typeThis monadic function returns the type of its argument as a short integer. Negatives numbers are for atoms, positive numbers are for lists, and zero is a general K list.
valueWhen passed a dictionary, This gets the values of a dictionary.r: value Dvalue `q`w`e!1 2 3
viewsMonadic function which returns a list of the currently defined views in the root directory, this list is sorted and has the `s attribute set.

exotic

symdescriptionsyntaxeg
gtimeThe gtime function returns the UTC datetime/timestamp for a given datetime/timestamp. Recall that the UTC and local datetime/timestamps are available as .z.z/.z.p and .z.Z/.z.P respectively.
ltimeThe ltime function returns the local datetime/timestamp for a given UTC datetime/timestamp. Recall that the UTC and local datetime/timestamps are available as .z.z/.z.p and .z.Z/.z.P respectively.
parseparse is a monadic function that takes a string and parses it as a kdb+ expression, returning the parse tree. To execute a parsed expression, use the eval function. parse "{x+42} each til 10"
viewMonadic function which returns the expression defining the dependency passed as its symbol argument.

io

symdescriptionsyntaxeg
0:Prepare. The dyadic prepare text function takes a separator character as its first argument and a table or a list of columns as its second. The result is a list of character strings containing text representations of the rows of the second argument separated by the first.show csv 0: ([]a:1 2 3;b:`x`y`z)
0:Save. The dyadic save text function takes a file handle as its first argument and a list of character strings as its second. The strings are saved as lines in the file. The result of the prepare text function can be used as the second argument.
0:Load. The dyadic load text function takes file format description as its first argument and a file handle or a list of character strings as its second.t:("SS";enlist" ")0:`:/tmp/txt /load 2 columns from space delimited file
0:The format description takes the form of a list of types and either a list of widths for each field if the data to be loaded is fixed width, or the delimiter if delimited, if the delimiter is enlisted the first row of the input data will be used as column names and the data is loaded as a table, otherwise the data is loaded as an list of values for each column.t:("IFC D";4 8 10 6 4) 0: `:/q/Fixed.txt /reads a text file containing fixed length records
0:note that when loading text you should specify the identifier as an uppercase letter, to load a field as a nested character column or list rather than symbol use '*' as the identifier and to skip a field from the load use ' '.
0:Optionally, load text can take a three-item list as its second argument, containing the file handle, an offset at which to begin reading, and a length to read.("SS";csv)0:(`:/tmp/data.csv;x;x+100000)
0:Also works for key/value pairs.show "S=;"0:"one=1;two=2;three=3"
1Write to standard output1 "String vector here "
1:The 1: dyadic function is used to read fixed length data from a file or byte sequence. The left argument is a list of types and their widths to read, and the right argument is the file handle or byte sequence.("ich";4 1 2)1:0x00000000410000FF00000042FFFF
1:Optionally, it can also take a three-item list as its second argument, containing the file handle, an offset at which to begin reading, and a length to read.("ii";4 4)1:(`:/tmp/data;x;x+100000)
2write to standard error2 "String vector here "
2:The 2: function is a dyadic function used to dynamically load C functions into Kdb+. Its left argument is a symbol representing the name of the dynamic library from which to load the function. Its right argument is a list of a symbol which is the function name and an integer which is the number of arguments the function to be loaded takes.
getenvReturns the value of the given environment variable.getenv `PATH
hcountGets the size in bytes of a file as a long integer.hcount`:c:/q/test.txt
hcountGets the size in bytes of a file as a long integer.hcount fhhcount `:readme.txt
hdelDelete a file.hdel fhhdel `:readme.txt
hsymConverts its symbol argument into a file name, or valid hostname, ipaddresshsym`10.43.23.197
read0The read0 function reads a text file, returning a list of lines.Lines are assumed delimited by either LF or CRLF, and the delimiters are removed. read0`:test.txt
read0Optionally, read0 can take a three-item list as its argument, containing the file handle, an offset at which to begin reading, and a length to read.read0(`:/tmp/data;0;0+100000)
read1The read1 function reads a file as a list of bytes.read1`:test.txt
read1Optionally, read1 can take a three-item list as its argument, containing the file handle, an offset at which to begin reading, and a length to read.read1(`:/tmp/data;0;0+100000)
rloadThe rload function loads a splayed table. This can also be done, as officially documented, using the get function.
saveThe save function saves data to the filesystem.t:([]x: 1 2 3; y: 10 20 30);save `t
setDyadic functional form of assignment often used when saving objects to disk. set is used mainly to write data to disk and in this case the left argument is a file path, i.e. a symbol atom beginning with a :`:c:/q/testTradeTable set trade
setenvDyadic function which changes or adds an environment variable.`name setenv value

joins

symdescriptionsyntaxeg
ajAsof Join - Joins tables based on nearest time.aj[c1...cn;t1;t2]aj[`sym`time; trade; quote]
ejEqui Join - Same as ij but allows specifying the column names.ej[c;t1;t2]ej[sym; trade; quote]
ijInner Join - Where matches occur between t and kt on primary key columns, update or add that column. Non-matches are not returned in the result.t ij kt([] a:1 2; b:3 4) ij ([a:2 3]; c:`p`o)
ljLeft Join - for each row in t, return a result row, where matches are performed by finding the first key in kt that matches. Non-matches have any new columns filled with null.t lj kt([] a:1 2; b:3 4) lj ([a:2 3]; c:`p`o)
pjPlus Join - Same principle as lj, but existing values are added to where column names match.t pj kt
ujUnion Join - Combine all columns from both tables. Where possible common columns append or new columns created and filled with nulls.t1 uj t2([] a:1 2; b:3 4) uj ([] a:2 3; c:`p`o)
wjWindow Join - Join all aggregates within a given time window to a corresponding table.wj[w;c;t;(q;(f0;c0);(f1;c1))]wj[w;`sym`time;trade; (quote;(max;`ask);(min;`bid))]

math

symdescriptionsyntaxeg
absReturns the absolute value of a number. i.e. the positive valueabs Xabs -2 -1 0 1
acosAccepts a single argument in radians and returns the arc cosine.acos[radians]acos 3.141593
allFunction all returns a boolean atom 1b if all values in its argument are non-zero, and otherwise 0b.It applies to all data types except symbol, first converting the type to boolean if necessary. r:all Aall 1 2 3=1 2 4
allFunction all returns a boolean atom 1b if all values in its argument are non-zero, and otherwise 0b.It applies to all data types except symbol, first converting the type to boolean if necessary.any Xany 1010111001b
anyReturn 1b if there are any non-zero values in it's argument, otherwise return 0b.any Xany 1010111001b
asinAccepts a single argument in radians and returns the arc sine.sin[radians]sin 3.141593
atanAccepts a single argument in radians and returns the arc tan.atan[radians]atan 3.141593
ceilingWhen passed floating point values, return the smallest integer greater than or equal to those values.ceiling Xceiling 1.2 3.4 5.8
cosAccepts a single argument in radians and returns the cosine.cos[radians]cos 3.141593
crossReturns the cross product (i.e. all possible combinations) of its arguments.R:X cross Y
exceptReturns all elements of its left argument that are not in its right argument. x except y1 3 2 4 except 1 2
expThis function computes e to the power of x, where e is the base of the natural logarithms. Null is returned if the argument is null.R:exp 1
fliptransposes its argument, which may be a list of lists, a dictionary or a table.flip (`a`b`c; 1 2 3)
floorWhen passed floating point values, return the greatest integer less than or equal to those values.floor Xfloor 1.2 3.4 5.8
interReturns all elements common to both argumentsx inter y1 3 2 4 inter 1 2 6 7
invinv computes the inverse of a non-singular floating point matrix.r:inv xinv (3 3#2 4 8 3 5 6 0 7 1f)
logReturns the natural logarithm of it's argumentlog Xlog 0 1 2.71828
maxThe max function returns the maximum of its argument. If the argument is an atom, it is returned unchanged. max amax 1
maxThe max function returns the maximum of its argument. If the argument is a list, it returns the maximum of the list. The list may be any datatype except symbol. Nulls are ignored, except that if the argument has only nulls, the result is negative infinity. max Lmax 1 2 3 10 3 2 1
maxsThe maxs function returns the maximums of the prefixes of its argument. If the argument is an atom, it is returned unchanged. maxs amaxs 1
maxsThe maxs function returns the maximums of the prefixes of its argument. If the argument is a list, it returns the maximums of the prefixes of the list. The list may be any datatype except symbol. Nulls are ignored, except that initial nulls are returned as negative infinity. maxs Lmaxs 1 2 3 10 3 2 1
mcountThe mcount verb returns the N-item moving count of the non-null items of its numeric right argument. The first N items of the result are the counts so far, and thereafter the result is the moving count.r:N mcount L3 mcount 0N 1 2 3 0N 5
mdevThe mdev verb returns the N-item moving deviation of its numeric right argument, with any nulls after the first element replaced by zero. The first N items of the result are the deviations of the terms so far, and thereafter the result is the moving deviation. The result is floating point.r:N mdev L2 mdev 1 2 3 5 7 10
medComputes the median of a numeric list.r:med Lmed 10 34 23 123 5 56
minReturns the minimum value within a listmin X3~min 100 10 3 22
mmaxThe mmax verb returns the N-item moving maximum of its numeric right argument, with nulls after the first replaced by the preceding maximum. The first N items of the result are the maximums of the terms so far, and thereafter the result is the moving maximum.r:N mmax L3 mmax 2 7 1 3 5 2 8
mmummu computes the matrix multiplication of floating point matrices. The arguments must be floating point and must conform in the usual way, i.e. the columns of x must equal the rows of y.r:x mmu y(2 4#2 4 8 3 5 6 0 7f) mmu (4 3#`float$til 12)
modx mod y returns the remainder of y%x. Applies to numeric types, and gives type error on sym, char and temporal types.r:L mod N-3 -2 -1 0 1 2 3 4 mod 3
msumThe msum verb returns the N-item moving sum of its numeric right argument, with nulls replaced by zero. The first N items of the result are the sums of the terms so far, and thereafter the result is the moving sum.r:N msum L3 msum 1 2 3 5 7 11
negThe function neg negates its argument, e.g. neg 3 is -3. Applies to all data types except sym and char. Applies item-wise to lists, dict values and table columns. r:neg Xneg -1 0 1 2
prdAggregation function, also called multiply over, applies to all numeric data types. It returns a type error with symbol, character and temporal types. prd always returns an atom and in the case of application to an atom returns the argument.ra:prd Lprd 2 4 5 6
randIf X is an atom 0, it returns a random value of the same type in the range of that type:r: rand 0rand each 3#0h
randIf X is a positive number, it returns a random number of the same type in the range [0,X)r: rand arand 100
randIf X is a list, it returns a random element from the list:r:rand Lrand 1 30 45 32
ratiosThe uniform function ratios returns the ratio of consecutive pairs. It applies to all numeric data types.r:ratios Lratios 1 2 4 6 7 10
reciprocalReturns the reciprocal of its argument. The argument is first cast to float, and the result is float.r:reciprocal Xreciprocal 0 0w 0n 3 10
signumThe function signum returns -1, 0 or 1 if the argument is negative, zero or positive respectively. Applies item-wise to lists, dictionaries and tables, and to all data types except symbol.r:signum Xsignum -2 0 1 3
sinAccepts a single argument in radians and returns the sine.sin[radians]sin 3.141593
sqrtReturns the square root of it's argumentsqrt Xsqrt 0 1 4 9
sumReturns the sum total of a listsum X14~sum 2 4 8
tanAccepts a single argument in radians and returns the tan.tan[radians]tan 3.141593
unionDyadic function which returns the union of its arguments, i.e. returns the distinct elements of the combined lists respecting the order of the union.R:X union Y1 2 3 union 2 4 6 8
varAggregation function which applies to a list of numerical types and returns the variance of the list. Again for the usual reason it works on the temporal types.r:var Xvar 10 343 232 55
wavgDyadic where first arg is weights, second is values, returns the weighted average.X wavg Y7=1 1 2 wavg 5 5 9
wsumThe weighted sum aggregation function wsum produces the sum of the items of its right argument weighted by the items of its left argument. The left argument can be a scalar, or a list of equal length to the right argument. When both arguments are integer lists, they are converted to floating point. Any null elements in the arguments are excluded from the calculation.2 3 4 wsum 1 2 4
xexpThis is the dyadic power function.r:xexp[X;Y]2 xexp 3

misc

symdescriptionsyntaxeg
binbin gives the index of the last element in x which is <=y. The result is -1 for y less than the first element of x.It uses a binary search algorithm, which is generally more efficient on large data than the linear search algorithm used by ?.The items of the left argument should be sorted non-descending although q does not enforce it. The right argument can be either an atom or simple list of the same type as the left argument. r:x bin y0 2 4 6 8 10 bin 5
colsReturn a symbol list of column names for a given table, or a list of keys for a dictionary.cols[table]cols trade
evalThe eval function is the dual to parse and can be used to evaluate a parse tree as returned by that function (as well as manually constructed parse trees). eval parse "2+3"
fillsUniform function that is used to forward fill a list containing nulls.r:fills Afills (0N 2 3 0N 0N 7 0N)
groupGroups the distinct elements of its argument, and returns a dictionary whose keys are the distinct elements, and whose values are the indices where the distinct elements occur. The order of the keys is the order in which they are encountered in the argument.D:group Lgroup "mississippi"
iascUniform function that returns the indices needed to sort the list argument.r:iasc Liasc (2 1 3 4 2 1 2)
idescUniform function that returns the indices needed to sort the list argument.r:idesc Lidesc (2 1 3 4 2 1 2)
keyGiven a keyed table, Returns the key columns of a keyed tabler:key KTkey ([s:`q`w`e]g:1 2 3;h:4 5 6)
keyGiven a directory handle, returns a list of objects in the directoryr:key DIRkey`:c:/q
keyGiven a file descriptor, returns the descriptor if the file exists, otherwise returns an empty listr:key filedesckey`:c:/q/sp.q
keyGiven a foreign key column, returns the name of the foreign key table
keyGiven a simple list, returns the name of the type as a symbolkey Lkey each ("abc";101b;1 2 3h;1 2 3;1 2 3j;1 2 3f)
keyGiven an enumerated list, it returns the name of the enumerating listkey eL
keyGiven a positive integer, it acts like tilkey nkey 10
keysMonadic function which takes a table as argument and returns a symbol list of the primary key columns of its argument and in the case of no keys it returns an empty symbol list. Can pass the table by reference or by valuekeys Tkeys ([s:`q`w`e]g:1 2 3;h:4 5 6)
lastReturns the item at the end of the list or tablelast X7~last 2 3 4 7
overThe over adverb takes a function of two arguments on its left, and creates a new atomic function that applies to successive items of its list argument. The result is the result of the last application of the function.r:f over L{x+2*y} over 2 3 5 7
peachThe parallel each adverb is used for parallel execution of a function over data. In order to execute in parallel, q must be started with multiple slaves (-s). {sum exp x?1.0}peach 2#1000000
rankThe uniform function rank takes a list argument, and returns an integer list of the same length. Each value is the position where the corresponding list element would occur in the sorted list. This is the same as calling iasc twice on the list.r:rank Lrank 2 7 3 2 5
scanThe scan adverb takes a function of two arguments on its left, and creates a new uniform function that applies to successive items of its list argument. The result is a list of the same length.r:f scan L{x+2*y} scan 2 3 5 7
svscalar from vector- dyadic function that performs different functions on different data types.
svIn the special case where the left argument is a `, it returns the concatenated right arg with each element terminated by a newline ( on unix, on windows).` sv ("asdf";"hjkl")
svWhen applied to a symbol list where the first element is a file handle and the left argument is a ` sv returns a file handle where the elements of the list are separated by slashes-this is very useful when building write pathswp:`:c:/q/data; (`)sv wp,`2005.02.02,`trade
svIn the case of using sv on a symbol list where the left argument is a ` it returns the elements separated by . this is useful for generating files with the required extensionfp:`c:/q/sym; hsym` sv fp,`txt
svEvaluates base valuerl: N sv L10 sv 23 45 677
svConverts bytes to ints base 2560x0 sv "x"$12 3 4 5
ungroupThe ungroup function monadic function ungroups a table.
valueThis is the same verb as get but is typically used for different things.
valueWhen passed an object by reference it returns the value of that objectD:`q`w`e!1 2 3 ; value `D
valueWhen passed object has an enumerated type, it returns the corresponding symbol list:
valueWhen passed object is a lambda, it returns a list:(bytecode;params(8);locals(24);globals(32),Constants(96)
valueWhen passed object is a projection, it returns a list where projected function is followed by parameters:value +[2]
valueWhen passed object is a composition, it returns a list of composed functions:value rank
valueWhen passed object is a primitive it returns an internal code:value each (::;+;-;*;%)
valueWhen passed object is an adverb modified verb, it strips the adverb:value (+/)
valueWhen passed a string with valid q code, it evaluates it:value"b:`a`b`c"
valueWhen passed a list, applies the first element to the rest:value(+;1;2)
valueIf the first element of the list is a symbol, it is evaluated first:value(`.q.neg;2)
vsThe dyadic vs vector from scalar function has several uses.
vsWith 0b on the left hand side, it returns the bit representation of the integer on the right hand side.0b vs 1024h
vsWith 0x0 on the left hand side, it returns the byte representation of the number on the right hand side.0x0 vs 1024
vsWith ` on the left hand side splits symbols on the . ; breaks file handles into directory and file parts; and domain names into components.` vs`:/foo/bar/baz.txt

qsql

symdescriptionsyntaxeg
deletetwo Formats. Either delete rows or delete columns from table.delete col from t. delete row from t where filter.delete from t where price<10
differThe uniform function differ returns a boolean list indicating whether consecutive pairs differ. It applies to all data types. (The first item of the result is always 1b)r:differ A
fbyThis verb is typically used with select, and obviates the need for many common correlated subqueries. It aggregates data in a similar way to by and computes a function on the result.(aggr;data) fby group
fkeysThe function fkeys takes a table as an argument and returns a dictionary that maps foreign key columns to their tables.
insertInsert appends records to a table.`table insert records`x insert (`s`t;40 50)
metaThe meta function returns the meta data of its table argument, passed by value or reference.K:meta Tmeta ([s:`q`w`e]g:1 2 3;h:4 5 6)
selectSelect rows from a table.select columns by groups from table where filtersselect max price by date,sym from trade where sym in `AA`C
updateModify the table to update existing values or to create a new column.update col by c2 from t where filterupdate price:price+10 from t where sym=`A
upsertFunctional form of inserting into a table using the , primitive. It is called upsert because when applied to keyed tables it performs an insert if the key value is not there and otherwise performs an update.r: T upsert newEntries([s:`q`w`e]r:1 2 3;u:5 6 7) upsert (`q;100;500)
whereWhere the argument is a boolean list, this returns the indices of the 1'swhere 21 2 5 11 33 9>15
withinThe right argument of this primitive function is always a two-item list. The result is a boolean list with the same number of items as the left argument. The result indicates whether or not each item of the left argument is within the bounds defined by the right argument.1 3 10 6 4 within 2 6
withinThe within function also applies to chars and syms because both are ordered"acyxmpu" within "br"
withinThe within function will also work with a pair of n-ary lists as the right argument and an atom, a n-ary list or n-by-* ragged matrix as the left argument. The results in this case take the shape of the left argument.5 within (1 2 6;3 5 7)
wjWindow join is a generalization of asof join, and is available from kdb+ 2.6. asof join takes a snapshot of the current state, while window join aggregates all values of specified columns within intervals.
xascDyadic function-sorts a table in ascending order of a particular column, sorting is order preserving among equals. Takes a symbol list or atom and a table as arguments and returns the original table sorted by the columns as specified in the first argument.R:C xasc Tt:`sym xasc trade
xascIt can be used to sort data on disk directly. xasc can be used to sort a splayed table on disk one column at a time without loading the entire table into memory. see notes
xbarInterval bars are prominent in aggregation queries. For example, to roll-up prices and sizes in 10 minute bars:select last price, sum size by 10 xbar time.minute from trade
xcolDyadic function - rename columns in a table. Takes a symbol list of column names and a table as arguments, and returns the table with the new column names. The number of column names must be less than or equal to the number of columns in the table. The table must be passed by value.R:C xcol T`A`S`D`F xcol trade
xcolsDyadic function - reorder columns in a table. Takes a symbol list of column names and a table as arguments and returns the table with the named columns moved to the front. The column names given must belong to the table. The table must have no primary keys and is passed by value.R:C xcols Txcols[reverse cols trade;trade]
xgroupThe xgroup function dyadic function groups its right argument by the left argument (which is a foreign key).
xkeyDyadic function-sets a primary in a table. Takes a symbol list or atom and a table as arguments and returns the original table with a primary key corresponding to the column(s) specified in the first argument.R:C xkey T`r xkey ([s:`q`w`e]r:1 2 3;u:5 6 7)
xprevUniform dyadic function, returns the n previous element to each item in its argument list.r:N xprev A2 xprev 2 3 4 5 6 7 8
xrankUniform dyadic function which allocates values to buckets based on value. This is commonly used to place items in N equal buckets.

string

symdescriptionsyntaxeg
likePerform simple pattern matching of strings.like[text; pattern]like[("kim";"kyle";"Jim"); "k*"]
lowerMonadic that converts strings and symbols to lower caselower[text]`small~lower `SMALL
ltrimMonadic that removes leading whitespace from strings.ltrim[text]"abc"~ltrim " abc"
rtrimMonadic that removes trailing whitespace from strings.rtrim[text]"abc"~rtrim "abc "
ssThe function ss finds positions of a substring within a string. It also supports some pattern matching capabilities of the function like: r:HayStack ss needle"toronto ontario" ss "ont"
ssrThe function ssr does search and replace on a string.r:ssr[haystack; needle; replacement]ssr["toronto ontario"; "ont"; "XX"]
svWhen applied to a vector of strings it returns the elements of its right argument-the list of strings-separated by the left argument."|" sv ("asdf";"hjkl")
trimMonadic that removes leading and trailing whitespace from strings.trim[text]"abc"~trim " abc "
upperMonadic that converts strings and symbols to upper caselower[text]`BIG~upper `big
vsWith a character or a string on the left hand side, it tokenizes a string on the right hand side using the left hand side as the specified delimiter. It returns a vector of substrings.","vs"one,two,three"