Back to Update

qSQL · Update · Practice Question

Applying and Removing Attributes

Sign in to track your progress

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:

  1. Verify that the attribute has been applied.
  2. Remove the attribute from the column.

Solution

Apply the Grouped Attribute

update `g#sym from `t

or

@[`t;`sym;`g#]

Verify the Attribute

attr t[`sym]

Result:

`g

Remove the Attribute

update `#sym from `t

or

@[`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 `t

or directly using amend:

@[`t;`sym;`g#]

After applying the attribute, the column remains unchanged:

t
sym  qty price
---------------
AAPL 100 185.25
MSFT 200 410.1
AAPL 150 186
GOOG 300 142.8
MSFT 250 411.5

but the column now carries the grouped attribute.

Verifying the Attribute

The simplest approach is:

attr t[`sym]

Result:

`g

Alternatively:

attr exec sym from t

or

exec attr sym from t

Both return:

`g

The attribute can also be inspected using:

meta t

Result:

c    | t f a
-----| -----
sym  | s   g
qty  | j
price| f

The a column of the metadata contains the attribute information.

Removing the Attribute

Attributes can be removed by applying the null attribute:

update `#sym from `t

or:

@[`t;`sym;`#]

Verifying again:

attr t[`sym]

Result:

`

which indicates that no attribute is present.

Summary

Apply a grouped attribute:

update `g#sym from `t

Verify it:

attr t[`sym]

or:

meta t

Remove it:

update `#sym from `t

Attributes are an important performance feature in q and can significantly improve the efficiency of certain operations when applied appropriately.