Back to Functional Form

qSQL · Functional Form · Practice Question

Function Select

Sign in to track your progress

Question

Given the following table:

t:([] sym:`AAPL`MSFT`GOOG`TSLA`NVDA;
      qty:100 200 150 75 300;
      price:185.25 410.10 142.80 238.50 875.20)

Write the functional equivalent of:

select sym, qty from t

Expected result:

sym  qty
--------
AAPL 100
MSFT 200
GOOG 150
TSLA 75
NVDA 300

Solution

?[t; (); 0b; `sym`qty!`sym`qty]

Explanation

The functional form of select is the ? operator taking four arguments:

?[table; where; by; select]

Breaking this call down:

PositionValueMeaning
tabletthe source table
where()no filter — all rows
by0bno grouping
select`sym`qty!`sym`qtywhich columns to return

The fourth argument is a dictionary. The keys are the output column names; the values are the expressions that produce them. When you just want to pass a column through unchanged, the key and value are the same symbol:

`sym`qty!`sym`qty
/ sym -> sym   (return sym as sym)
/ qty -> qty   (return qty as qty)

This is equivalent to writing {x!x}`sym`qty, which is a convenient shorthand when returning several columns by name.

Why write it this way at all?

For a fixed query like this, the plain syntax is clearly better. The functional form pays off when the columns are not known until the code runs. For example, if a user selects which columns they want:

c: `sym`qty     / could come from user input, a config file, etc.
?[t; (); 0b; c!c]

/ note: don't name the variable cols — cols is a q keyword

You can't write select sym, qty from t when you don't know at write time that it will be sym and qty. The functional form lets you slot in whatever arrives at runtime.