Back to Update

qSQL · Update · Practice Question

Derive Columns from Boolean Flags

Sign in to track your progress

Derive Columns from Boolean Flags

Question

Given the following table:

t:([] sym:`cfl`bpm`icj`ini`nmo`ojj`bjc`khd`hjb`lhk;
      px:2.296615 6.919531 4.707883 6.346716 9.672398 2.306385 9.49975 4.39081 5.759051 5.919004;
      qty:8 1 9 5 4 6 6 1 8 5)

Add two new columns:

  1. active - a random boolean value for each row.

  2. status - a symbol column such that:

    • status = yes when active is 1b
    • status = no when active is 0b

Example output:

sym px       qty active status
------------------------------
cfl 2.296615 8   0      no
bpm 6.919531 1   1      yes
icj 4.707883 9   1      yes
ini 6.346716 5   0      no
nmo 9.672398 4   0      no
ojj 2.306385 6   0      no
bjc 9.49975  6   1      yes
khd 4.39081  1   0      no
hjb 5.759051 8   1      yes
lhk 5.919004 5   1      yes

Solution

update active:(count t)?0b from `t
update status:`no`yes active from `t

Alternative Solution

update status:?[active;`yes;`no] from update active:(count t)?0b from t

This version returns a new table rather than modifying t.

Note that active must be created before the update that uses it. Within a single update (or select), each column expression sees only the columns of the input table, so writing update active:(count t)?0b, status:`no`yes active from `t fails with 'active.

Explanation

The expression:

(count t)?0b

generates one random boolean value per row in the table.

For a table containing 10 rows:

count t

returns:

10

and:

10?0b

might produce:

0110001011b

These values are assigned to the active column.

Mapping Booleans to Symbols

In q, booleans can be used directly as indices.

Consider:

`no`yes 0

Result:

`no

and:

`no`yes 1

Result:

`yes

Therefore:

`no`yes active

maps every boolean value to its corresponding symbol.

For example, `no`yes 0110b returns:

`no`yes`yes`no

This is often the most concise way to convert boolean flags into labels.

Alternative Approach

The vector conditional:

?[active;`yes;`no]

evaluates:

if active then yes else no

for each row.

While slightly more verbose, it can be easier to read when the logic becomes more complex.

Summary

This question demonstrates two useful techniques:

  • Generating random data using ?
  • Using boolean values as list indices

The expression:

`no`yes active

is a common q idiom for mapping booleans directly to descriptive labels.