count t vs actual number in kdb select statement

Viewed 98

I noticed the following

select (count t)#`test from t

Returns

flip (enlist `x)!enlist enlist `test`test`test

Vs

select 3#`test from t

Which returns

flip (enlist `x)!enlist `test`test`test

Similar with select (sum 1 2)#1 from t vs select(1 + 2)#1 from t etc

Anyone know the reason why key words in the select seems to cause the return to be a table with one row nested list containing x element vs a table with x rows?

1 Answers

It's because kdb recognises count and sum as aggregations and has special treatment for them (it enlists the result).

For example if you were to slightly change the count and sum to lambdas (which kdb won't recognise) you get the other results you expect:

q)select ({count x}t)#`test from t
x
----
test
test
test

q)select ({sum x}1 2)#1 from t
x
-
1
1
1

The reason kdb "recognises" certain common aggregations and auto-enlists them is because otherwise simple selects such as select sum a from tab would give a rank error as the sum returns an atom but a table column must be a list, e.g.

q)select {sum x}a from t
'rank
  [0]  select {sum x}a from t
       ^

/versus

q)select sum a from t
a
-
6

There's also a deeper reason which is to do with map/reduce aggregations over database partitions but that's beyond scope for this problem. The list of recognised aggregations is stored in the variable .Q.a0. See also https://code.kx.com/q/basics/qsql/#special-functions

Related