qSQL · Update · Practice Question
Applying and Removing Attributes
Applying and Removing Attributes
Question
Given the following table:
t:([] sym:`AAPL`MSFT`AAPL`GOOG`MSFT;
qty:100 200 150 300 250;
price:185.25 410.10 186.00 142.80 411.50)Apply a grouped attribute to the sym column.
Then:
- Verify that the attribute has been applied.
- Remove the attribute from the column.
Solution
Apply the Grouped Attribute
update `g#sym from `tor
@[`t;`sym;`g#]Verify the Attribute
attr t[`sym]Result:
`gRemove the Attribute
update `#sym from `tor
@[`t;`sym;`#]Explanation
Attributes can be applied to table columns to provide q with additional information about the data.
The grouped attribute (`g#) makes q maintain an internal index from each distinct value to the positions where it occurs, which speeds up operations such as equality searches.
Applying the Attribute
The grouped attribute can be applied using an update statement:
update `g#sym from `tor directly using amend:
@[`t;`sym;`g#]After applying the attribute, the column remains unchanged:
tsym qty price
---------------
AAPL 100 185.25
MSFT 200 410.1
AAPL 150 186
GOOG 300 142.8
MSFT 250 411.5but the column now carries the grouped attribute.
Verifying the Attribute
The simplest approach is:
attr t[`sym]Result:
`gAlternatively:
attr exec sym from tor
exec attr sym from tBoth return:
`gThe attribute can also be inspected using:
meta tResult:
c | t f a
-----| -----
sym | s g
qty | j
price| fThe a column of the metadata contains the attribute information.
Removing the Attribute
Attributes can be removed by applying the null attribute:
update `#sym from `tor:
@[`t;`sym;`#]Verifying again:
attr t[`sym]Result:
`which indicates that no attribute is present.
Summary
Apply a grouped attribute:
update `g#sym from `tVerify it:
attr t[`sym]or:
meta tRemove it:
update `#sym from `tAttributes are an important performance feature in q and can significantly improve the efficiency of certain operations when applied appropriately.