Search code examples
kdb

How to select a column containing dot in column name in kdb


I have a table which consists of column named "a.b"

q)t:([]a.b:3?10.0; c:3?10; d:3?`3)

How can we select column a.b and c from table t?
How can we rename column a.b to b?
Is it possible to achieve above two cases without functional select?

Failed attempts:
q)select a.b, c from t
'type
q)?[`t;();0b;enlist (`b`c!`a.b`c)]
'type
q)select b:a.b from t
'type

Solution

  • As much as I hate answering any online forum question by refuting the premise, I really must here, do not use periods in column names, it will cause trouble. .Q.id exists to santise column names for a reason.

    The primary reason that errors are encountered is that the use of dot notation in qSQL is reserved for the resolution of linked columns. We can see how this is actually working by parsing the query itself

    q)parse "select a.b from tab"
    ?
    `tab
    ()
    0b
    (,`b)!,`a.b // Here the referencing of a linked column b via a is occuring
    
    // Compared to a normal select
    q)parse "select b from tab"
    ?
    `tab
    ()
    0b
    (,`b)!,`b
    

    Other issues could crop up depending on future processing, such as q attempting to treat the column names as namespaces or operating on each part of the name with the dot operator.

    Using dot notation in your column names will hamstring any further development, and force all other kdb users to use roundabout methods. The development will be slow and encounter many bugs.

    I would advise that if periods must be included in the column, you create an API for external users to use to translate queries into the sanitised forms.

    You can easily sanitise the whole table with .Q.id

    q)tab:enlist `a.b`c`d!(1 2 3)
    q)tab:.Q.id tab
    q)sel:{[tab;cl] ?[tab;();0b;((),.Q.id each cl)!((),.Q.id each cl)]}
    q)sel[tab;`a.b]
    ab
    --
    1