order by
The keyword order by is used to sort the result based on specified column(s).
Starting from version 2.00.5, the order-by column can be a selected column or its alias.
Starting from version 2.00.9, order by supports nulls first/nulls last:
order by col [asc | desc] [nulls first | nulls last]
asc | desc
specifies that the results should be returned in ascending
order or descending order. If the order is not specified, ASC is the default.
nulls first | nulls last
specifies that NULL values should be returned
before or after non-NULL values.
-
When querying a DFS table, order-sensitive or user-defined function cannot be applied to col.
-
asc | desc
is required ifnulls first | nulls last
is specified.
Examples
sym = `C`MS`MS`MS`IBM`IBM`C`C`C$SYMBOL
price= 49.6 29.46 29.52 30.02 174.97 175.23 50.76 50.32 51.29
qty = 2200 1900 2100 3200 6800 5400 1300 2500 8800
timestamp = [09:34:07,09:36:42,09:36:51,09:36:59,09:32:47,09:35:26,09:34:16,09:34:26,09:38:12]
t1 = table(timestamp, sym, qty, price);
t1;
timestamp | sym | qty | price |
---|---|---|---|
09:34:07 | C | 2200 | 49.6 |
09:36:42 | MS | 1900 | 29.46 |
09:36:51 | MS | 2100 | 29.52 |
09:36:59 | MS | 3200 | 30.02 |
09:32:47 | IBM | 6800 | 174.97 |
09:35:26 | IBM | 5400 | 175.23 |
09:34:16 | C | 1300 | 50.76 |
09:34:26 | C | 2500 | 50.32 |
09:38:12 | C | 8800 | 51.29 |
select * from t1 order by sym, timestamp;
timestamp | sym | qty | price |
---|---|---|---|
09:34:07 | C | 2200 | 49.6 |
09:34:16 | C | 1300 | 50.76 |
09:34:26 | C | 2500 | 50.32 |
09:38:12 | C | 8800 | 51.29 |
09:32:47 | IBM | 6800 | 174.97 |
09:35:26 | IBM | 5400 | 175.23 |
09:36:42 | MS | 1900 | 29.46 |
09:36:51 | MS | 2100 | 29.52 |
09:36:59 | MS | 3200 | 30.02 |
We can use keyword "desc" to sort on descending order.
select * from t1 where sym in `C`IBM order by sym, timestamp desc;
timestamp | sym | qty | price |
---|---|---|---|
09:38:12 | C | 8800 | 51.29 |
09:34:26 | C | 2500 | 50.32 |
09:34:16 | C | 1300 | 50.76 |
09:34:07 | C | 2200 | 49.6 |
09:35:26 | IBM | 5400 | 175.23 |
09:32:47 | IBM | 6800 | 174.97 |
t = table(5 3 NULL NULL 1 6 8 as id, 1 2 3 4 5 6 7 as val)
select * from t order by id asc nulls last
id | val |
---|---|
1 | 5 |
3 | 2 |
5 | 1 |
6 | 6 |
8 | 7 |
3 | |
4 |
t = table(5 3 NULL NULL 1 6 8 as id, 1 2 3 4 5 6 7 as val)
select * from t order by id asc nulls first
id | val |
---|---|
3 | |
4 | |
1 | 5 |
3 | 2 |
5 | 1 |
6 | 6 |
8 | 7 |