Advantage of q Functional Queries in kdb+
One of the powerful features of kdb+/q is its ability to express the same operation in different ways. A good example is selecting rows from a table using the functional form of ? versus using #.
Let’s start with a simple table:
q)table:([]name:`sam`ram`eno`sai`choi;age:11 12 13 14 15)
q)?[table;();0b;()]
name age
--------
sam 11
ram 12
eno 13
sai 14
choi 15Functional Query Form
The functional form of select is:
?[table;where;by;select]For example:
q)?[table;();0b;()]
name age
--------
sam 11
ram 12
eno 13
sai 14
choi 15This gives us the complete table.
Now notice what happens when we provide the optional n argument:
q)?[table;();0b;();0]
name age
--------With n=0, no rows are returned.
With n=3:
q)?[table;();0b;();3]
name age
--------
sam 11
ram 12
eno 13And with n=7:
q)?[table;();0b;();7]
name age
--------
sam 11
ram 12
eno 13
sai 14
choi 15Even though we requested 7 rows, the result contains only the 5 rows available in the table.
Now Compare This with #
Consider:
q)0#select from table
name age
--------So far, the behavior looks similar.
Get Sathish Vadivel’s stories in your inbox
Join Medium for free to get updates from this writer.
But now:
q)7#select from table
name age
--------
sam 11
ram 12
eno 13
sai 14
choi 15
sam 11
ram 12Here we get 7 rows, even though the original table contains only 5 rows.
Why?
Because # is the take operator. When the requested count is greater than the number of available items, q takes items cyclically.
So:
5 rows available
7 requested
sam → ram → eno → sai → choi → sam → ramThis produces 7 rows.
Why Is the Functional Query Useful?
This difference becomes important when writing database queries.
The functional query form:
?[table;();0b;();7]is operating as part of q’s query language. It gives us a way to construct and manipulate queries programmatically.
A Simple Comparison:
Understanding this distinction helps avoid subtle bugs and, more importantly, opens the door to one of kdb+/q’s biggest strengths: building powerful queries dynamically using q’s functional form.










