KX Community

Find answers, ask questions, and connect with our KX Community around the world.
KX Community Guidelines

Home Forums kdb+ How do I add column name as a string to content of data

  • How do I add column name as a string to content of data

    Posted by kpc on November 28, 2023 at 12:00 am

    I have a table contains columns col1, col2.

    I want to prefix the content of each row in col1 as “col1#”. Similarly for col2 as well.

    Is there anyway i can do with functional update query?

    Thanks

    kpc replied 8 months, 2 weeks ago 3 Members · 2 Replies
  • 2 Replies
  • rocuinneagain

    Member
    November 28, 2023 at 12:00 am

    //Sample table

    q)t:([] col1:("abc";"def");col2:("ghi";"jkl")) 
    q)t col1 col2 ----------- "abc" "ghi" "def" "jkl" 
    //qsql update 
    update {"col1#",x} each col1,{"col2#",x} each col2 from t col1 col2 
    --------------------- 
    "col1#abc" "col2#ghi" "col1#def" "col2#jkl" 
    //qsql improved using column name as variable 
    update {string[x],"#",y}[`col1] each col1,{string[x],"#",y}[`col2] each col2 from t col1 col2 
    --------------------- 
    "col1#abc" "col2#ghi" "col1#def" "col2#jkl" \parse the query to see functional form 
    parse"update {string[x],"#",y}[`col1] each col1,{string[x],"#",y}[`col2] each col2 from t" ! `t () 0b `col1`col2!((k){x'y};({string[x],"#",y};,`col1);`col1);(k){x'y};({string[x],"#",y};,`col2);`col2)) 
    //Simplify functional form 
    ![t;();0b;{x!{(each;{string[x],(enlist "#"),y}[x];x)}each x}`col1`col2] col1 col2 
    --------------------- 
    "col1#abc" "col2#ghi" "col1#def" "col2#jkl"
  • megan_mcp

    Administrator
    November 28, 2023 at 12:00 am

    Hi ,

    Can I just note that by converting your symbols to strings in col2, you are going to take up a lot more memory. If it isn’t essential they be stored in the table as strings, you could convert them while querying your data instead.

    Of course this is only relevant if the table will be saved on disk and if you are interested in saving memory.

    Thanks,

    Megan

Log in to reply.