Back to Selecting Data

In Memory Tables · Selecting Data · Practice Question

Select Specific Columns Using a Functional Select

Sign in to track your progress

Question

Given a table t with columns a and b (among others), select columns a and b using a functional select statement — the form of qSQL written as a plain function call rather than the select ... from ... syntax.

For example:

t:([] a:`x`y`z; b:1 2 3; c:10 20 30f)

Solution

?[t;();0b;{x!x} `a`b]

Explanation

The functional form of select is ?[table;where;by;select]:

  • t — the table being queried.
  • () — no where constraints, so every row is kept.
  • 0b — no by grouping.
  • {x!x} ab — the column specification, here built dynamically rather than typed out as a dictionary literal.

{x!x} ab takes the list `a`b and creates a dictionary mapping each column name to itself:

{x!x} `a`b
a| a
b| b

which tells ? "keep these columns, named the same as they already are" — equivalent to writing `a`b!`a`b, but useful when the column list is computed at runtime rather than known in advance, since {x!x} works for any list of column names without having to write it twice.

This is exactly equivalent to:

select a,b from t

but expressed in a form that can be built and passed around programmatically — useful inside functions where the table or column list isn't known until runtime.