qSQL · Update · Practice Question
Create a Boolean Flag Column
Question
Given the following table:
t:([] sym:`A`B`A`C`B`A`C`B`A`C;
price:120.5 151.2 175.0 160.4 149.9 180.3 130.0 155.5 99.8 201.1)Result:
sym price
---------
A 120.5
B 151.2
A 175
C 160.4
B 149.9
A 180.3
C 130
B 155.5
A 99.8
C 201.1Update the table to add a new column called highPrice, such that:
highPrice=1bwhenprice > 150.0highPrice=0botherwise
Expected result:
sym price highPrice
-------------------
A 120.5 0
B 151.2 1
A 175 1
C 160.4 1
B 149.9 0
A 180.3 1
C 130 0
B 155.5 1
A 99.8 0
C 201.1 1Solution
Method 1
update highPrice:1b from `t where price>150.0Method 2
update highPrice:price>150.0 from `tExplanation
Using a Conditional Update
The statement:
update highPrice:1b from `t where price>150.0updates only the rows that satisfy the condition:
price>150.0Rows that are updated receive 1b. Because highPrice is a new column, the remaining rows are filled with the null value for its type; booleans have no null, so they get 0b.
Result:
sym price highPrice
-------------------
A 120.5 0
B 151.2 1
A 175 1
C 160.4 1
B 149.9 0
A 180.3 1
C 130 0
B 155.5 1
A 99.8 0
C 201.1 1Using a Boolean Expression
A more direct approach is:
update highPrice:price>150.0 from `tThe expression:
price>150.0returns a boolean vector:
0111010101bwhich is assigned directly to the new column.
This approach is often preferred because it clearly expresses the intended logic and avoids the need for a separate where clause.
Summary
Two common approaches are:
update highPrice:1b from `t where price>150.0and
update highPrice:price>150.0 from `tThe second form is generally more concise and is a common q idiom for creating boolean flag columns from a condition.