Column Reference
A column object belongs to a table and holds a sequence of data. To refer to a column object, we can use <table>.<column> if the statement is not a SQL statement. Please note that <table>.<column> is read only and cannot be used to modify a column.
$ t=table(2 3 4 as x, 5 6 7 as y);
$ t;
x |
y |
---|---|
2 |
5 |
3 |
6 |
4 |
7 |
$ t.x;
[2,3,4]
$ a=t.x;
$ a+=1;
$ a;
[3,4,5]
$ t.x;
[2,3,4]
// column t.x is unchanged
$ t.x+=1;
Syntax Error: [line #1] Can't use assignment in expression.
// this is because t.x is read only. To modify column x, use t[`x] or update clause.
In a SQL statement, the table name can be ignored in front of the variable name.
select x from t;
x |
---|
2 |
3 |
4 |
How does the system tell if a variable is column reference, a variable name or a function name? This problem is dynamically disambiguated at runtime with the order of column reference, variable name, function name. Specifically, in a SQL statement, if a table column and a defined variable have the same name, the system always interprets the name as the table column. If we want to refer the defined variable in a SQL statement, we have to rename the variable. If a function has the same name as a table column or a variable and we want to use the function name in a SQL statement, we can use an “&” or module name before the function name to qualify it.
$ x=1..3
$ z=7..9
$ t1=select x, y, z from t;
$ t1;
// since table t has column x, the system interprets x as t.x in the sql statement although there is a separately defined variable x.
// although z is not in t1, the system recognizes it is of the same size as t.x and t.y. Therefore the system uses z together with t.x and t.y to make a new table t1.
x |
y |
z |
---|---|---|
2 |
5 |
7 |
3 |
6 |
8 |
4 |
7 |
9 |
$ avg=12.5
$ t1=table(1 2 2 3 3 as id, 1.5 1.8 3.2 1.7 2.5 as value)
$ select * from t1 where value > contextby(&avg,value,id);
id |
value |
---|---|
2 |
3.2 |
3 |
2.5 |
$ select * from t1 where value > contextby(::avg,value,id);
id |
value |
---|---|
2 |
3.2 |
3 |
2.5 |
$ select * from t1 where value > contextby(avg,value,id);
To use template 'contextby', the first argument must be a function definition
$ t=table(1 2 3 as ID, 4 5 6 as check)
$ check=1
$ check1=10
$ def check(x):x*10
$ def check1(x):x*100
$ def check2(x,y):x+2*y;
$ t;
ID |
check |
---|---|
1 |
4 |
2 |
5 |
3 |
6 |
$ select ID+check from t;
// column ID plus column check from table t
add_ID |
---|
5 |
7 |
9 |
$ select ID+check1 from t;
// column ID plus the variable of check1
add_ID |
---|
11 |
12 |
13 |
$ select accumulate(check2, check) as y from t;
// apply the accumulate template on the function definition of check2 and the column check from table t
y |
---|
4 |
14 |
26 |