10-function.md 39.1 KB
Newer Older
1
---
2
title: Functions
D
danielclow 已提交
3 4
sidebar_label: Functions
description: This document describes the standard SQL functions available in TDengine.
5
toc_max_heading_level: 4
6 7
---

8
## Single Row Functions
9

10
Single row functions return a result for each row.
11

12
### Mathematical Functions
13

14
#### ABS
15

16
```sql
G
Ganlin Zhao 已提交
17
ABS(expr)
18
```
19

20
**Description**: The absolute value of a specific field.
21

22
**Return value type**: Same as the field being used
23

24
**Applicable data types**: Numeric
25

26
**Nested query**: It can be used in both the outer query and inner query in a nested query.
27

28
**Applicable table types**: standard tables and supertables
29

30
**Usage**: This function can only be used on data columns. It can be used with selection and projection functions but not with aggregation functions.
31

32
#### ACOS
33

34
```sql
G
Ganlin Zhao 已提交
35
ACOS(expr)
36 37
```

38
**Description**: The arc cosine of a specific field.
39

40
**Return value type**: Double
41

42
**Applicable data types**: Numeric
43

44
**Nested query**: It can be used in both the outer query and inner query in a nested query.
45

46
**Applicable table types**: standard tables and supertables
47

48
**Usage**: This function can only be used on data columns. It can be used with selection and projection functions but not with aggregation functions.
49

50
#### ASIN
51

52
```sql
G
Ganlin Zhao 已提交
53
ASIN(expr)
54 55
```

56
**Description**: The arc sine of a specific field.
57

58
**Return value type**: Double
59

60
**Applicable data types**: Numeric
61

62
**Nested query**: It can be used in both the outer query and inner query in a nested query.
63

64 65 66
**Applicable table types**: standard tables and supertables

**Usage**: This function can only be used on data columns. It can be used with selection and projection functions but not with aggregation functions.
67

68

69
#### ATAN
70

71
```sql
G
Ganlin Zhao 已提交
72
ATAN(expr)
73 74
```

75
**Description**: The arc tangent of a specific field.
76

77
**Return value type**: Double
78

79
**Applicable data types**: Numeric
80

81
**Nested query**: It can be used in both the outer query and inner query in a nested query.
82

83 84 85
**Applicable table types**: standard tables and supertables

**Usage**: This function can only be used on data columns. It can be used with selection and projection functions but not with aggregation functions.
86

87

88
#### CEIL
89

90
```sql
G
Ganlin Zhao 已提交
91
CEIL(expr)
92 93
```

94
**Description**: The rounded up value of a specific field
95

96
**Return value type**: Same as the field being used
97

98
**Applicable data types**: Numeric
99

100
**Applicable table types**: standard tables and supertables
101

102
**Nested query**: It can be used in both the outer query and inner query in a nested query.
103

104
**Usage**: This function can only be used on data columns. It can be used with selection and projection functions but not with aggregation functions.
105

106
#### COS
107

108
```sql
G
Ganlin Zhao 已提交
109
COS(expr)
110 111
```

112
**Description**: The cosine of a specific field.
113

114
**Return value type**: Double
115

116
**Applicable data types**: Numeric
117

118
**Nested query**: It can be used in both the outer query and inner query in a nested query.
119

120
**Applicable table types**: standard tables and supertables
121

122
**Usage**: This function can only be used on data columns. It can be used with selection and projection functions but not with aggregation functions.
123

124
#### FLOOR
125

126
```sql
G
Ganlin Zhao 已提交
127
FLOOR(expr)
128 129
```

G
Ganlin Zhao 已提交
130
**Description**: The rounded down value of a specific field
131
 **More explanations**: The restrictions are same as those of the `CEIL` function.
132 133 134 135

#### LOG

```sql
G
Ganlin Zhao 已提交
136
LOG(expr [, base])
137 138
```

139 140 141
**Description**: The logarithm of a specific field with `base` as the radix. If you do not enter a base, the natural logarithm of the field is returned.

**Return value type**: Double
142

143
**Applicable data types**: Numeric
144

145
**Nested query**: It can be used in both the outer query and inner query in a nested query.
146

147
**Applicable table types**: standard tables and supertables
148

149
**Usage**: This function can only be used on data columns. It can be used with selection and projection functions but not with aggregation functions.
150 151


152
#### POW
153

154
```sql
G
Ganlin Zhao 已提交
155
POW(expr, power)
156
```
157

158 159 160
**Description**: The power of a specific field with `power` as the exponent.

**Return value type**: Double
161

162
**Applicable data types**: Numeric
163

164
**Nested query**: It can be used in both the outer query and inner query in a nested query.
165

166
**Applicable table types**: standard tables and supertables
167

168
**Usage**: This function can only be used on data columns. It can be used with selection and projection functions but not with aggregation functions.
169 170


171
#### ROUND
172

173
```sql
G
Ganlin Zhao 已提交
174
ROUND(expr)
175 176
```

G
Ganlin Zhao 已提交
177
**Description**: The rounded value of a specific field.
178
 **More explanations**: The restrictions are same as those of the `CEIL` function.
179 180


181
#### SIN
182

183
```sql
G
Ganlin Zhao 已提交
184
SIN(expr)
185
```
186

187
**Description**: The sine of a specific field.
188

189
**Return value type**: Double
190

191
**Applicable data types**: Numeric
192

193
**Nested query**: It can be used in both the outer query and inner query in a nested query.
194

195
**Applicable table types**: standard tables and supertables
196

197
**Usage**: This function can only be used on data columns. It can be used with selection and projection functions but not with aggregation functions.
198

199
#### SQRT
200

201
```sql
G
Ganlin Zhao 已提交
202
SQRT(expr)
203
```
204

205
**Description**: The square root of a specific field.
206

207
**Return value type**: Double
208

209
**Applicable data types**: Numeric
G
gccgdb1234 已提交
210

211
**Nested query**: It can be used in both the outer query and inner query in a nested query.
G
gccgdb1234 已提交
212

213
**Applicable table types**: standard tables and supertables
214

215
**Usage**: This function can only be used on data columns. It can be used with selection and projection functions but not with aggregation functions.
G
gccgdb1234 已提交
216

217
#### TAN
218

219
```sql
G
Ganlin Zhao 已提交
220
TAN(expr)
221 222
```

223
**Description**: The tangent of a specific field.
G
gccgdb1234 已提交
224

225
**Return value type**: Double
G
gccgdb1234 已提交
226

227
**Applicable data types**: Numeric
G
gccgdb1234 已提交
228

229
**Nested query**: It can be used in both the outer query and inner query in a nested query.
G
gccgdb1234 已提交
230

231
**Applicable table types**: standard tables and supertables
G
gccgdb1234 已提交
232

233
**Usage**: This function can only be used on data columns. It can be used with selection and projection functions but not with aggregation functions.
G
gccgdb1234 已提交
234

235
### Concatenation Functions
236

237
Concatenation functions take strings as input and produce string or numeric values as output.
238

239
#### CHAR_LENGTH
240

241
```sql
G
Ganlin Zhao 已提交
242
CHAR_LENGTH(expr)
243 244
```

245
**Description**: The length in number of characters of a string
246

247
**Return value type**: Bigint
248

249
**Applicable data types**: VARCHAR and NCHAR
250

251
**Nested query**: It can be used in both the outer query and inner query in a nested query.
252

253
**Applicable table types**: standard tables and supertables
254

255
#### CONCAT
256

257
```sql
G
Ganlin Zhao 已提交
258
CONCAT(expr1, expr2 [, expr] ...)
259 260
```

261
**Description**: The concatenation result of two or more strings
262

263
**Return value type**: If the concatenated strings are VARCHARs, the result is a VARCHAR. If the concatenated strings are NCHARs, the result is an NCHAR. If an input value is null, the result is null.
264

265
**Applicable data types**: VARCHAR and NCHAR You can concatenate between 2 and 8 strings.
266

267
**Nested query**: It can be used in both the outer query and inner query in a nested query.
268

269
**Applicable table types**: standard tables and supertables
270 271


272
#### CONCAT_WS
273

274
```sql
G
Ganlin Zhao 已提交
275
CONCAT_WS(separator_expr, expr1, expr2 [, expr] ...)
276 277
```

278
**Description**: The concatenation result of two or more strings with separator
279

280
**Return value type**: If the concatenated strings are VARCHARs, the result is a VARCHAR. If the concatenated strings are NCHARs, the result is an NCHAR. If an input value is null, the result is null.
281

282
**Applicable data types**: VARCHAR and NCHAR You can concatenate between 3 and 9 strings.
283

284
**Nested query**: It can be used in both the outer query and inner query in a nested query.
285

286
**Applicable table types**: standard tables and supertables
287 288


289
#### LENGTH
290

291
```sql
G
Ganlin Zhao 已提交
292
LENGTH(expr)
293 294
```

295
**Description**: The length in bytes of a string
296

297
**Return value type**: Bigint
298

299
**Applicable data types**: VARCHAR and NCHAR fields or columns
300

301
**Nested query**: It can be used in both the outer query and inner query in a nested query.
302

303
**Applicable table types**: standard tables and supertables
304 305


306
#### LOWER
307

308
```sql
G
Ganlin Zhao 已提交
309
LOWER(expr)
310 311
```

312
**Description**: Convert the input string to lower case
313

314
**Return value type**: Same as input
315

316
**Applicable data types**: VARCHAR and NCHAR
317

318
**Nested query**: It can be used in both the outer query and inner query in a nested query.
319

320
**Applicable table types**: standard tables and supertables
321 322


323
#### LTRIM
324

325
```sql
G
Ganlin Zhao 已提交
326
LTRIM(expr)
327 328
```

329
**Description**: Remove the left leading blanks of a string
330

331
**Return value type**: Same as input
332

333
**Applicable data types**: VARCHAR and NCHAR
334

335
**Nested query**: It can be used in both the outer query and inner query in a nested query.
336

337
**Applicable table types**: standard tables and supertables
338 339


340
#### RTRIM
341

342
```sql
G
Ganlin Zhao 已提交
343
LTRIM(expr)
344 345
```

346
**Description**: Remove the right tailing blanks of a string
347

348
**Return value type**: Same as input
349

350
**Applicable data types**: VARCHAR and NCHAR
351

352
**Nested query**: It can be used in both the outer query and inner query in a nested query.
353

354
**Applicable table types**: standard tables and supertables
355 356


357
#### SUBSTR
358

359
```sql
G
Ganlin Zhao 已提交
360
SUBSTR(expr, pos [, len])
361 362
```

363
**Description**: The sub-string starting from `pos` with length of `len` from the original string `str` - If `len` is not specified, it means from `pos` to the end.
364

365
**Return value type**: Same as input
366

367
**Applicable data types**: VARCHAR and NCHAR Parameter `pos` can be an positive or negative integer; If it's positive, the starting position will be counted from the beginning of the string; if it's negative, the starting position will be counted from the end of the string.
368

369
**Nested query**: It can be used in both the outer query and inner query in a nested query.
370

371
**Applicable table types**: table, STable
372 373


374
#### UPPER
375

376
```sql
G
Ganlin Zhao 已提交
377
UPPER(expr)
378 379
```

380
**Description**: Convert the input string to upper case
381

382
**Return value type**: Same as input
383

384
**Applicable data types**: VARCHAR and NCHAR
385

386
**Nested query**: It can be used in both the outer query and inner query in a nested query.
387

388
**Applicable table types**: table, STable
389 390


391
### Conversion Functions
392

393
Conversion functions change the data type of a value.
394

395
#### CAST
396

397
```sql
G
Ganlin Zhao 已提交
398
CAST(expr AS type_name)
399 400
```

G
Ganlin Zhao 已提交
401
**Description**: Convert the input data `expr` into the type specified by `type_name`. This function can be used only in SELECT statements.
402

403 404 405 406 407
**Return value type**: The type specified by parameter `type_name`

**Applicable data types**: All data types except JSON

**Nested query**: It can be used in both the outer query and inner query in a nested query.
408

409
**Applicable table types**: standard tables and supertables
410

411
**More explanations**:
412

413
- Error will be reported for unsupported type casting
414
- Some values of some supported data types may not be casted, below are known issues:
415 416 417
        1. Some strings cannot be converted to numeric values. For example, the string `a` may be converted to `0`. However, this does not produce an error.
        2. If a converted numeric value is larger than the maximum size for the specified type, an overflow will occur. However, this does not produce an error.
        3. If a converted string value is larger than the maximum size for the specified type, the output value will be truncated. However, this does not produce an error.
418

419
#### TO_ISO8601
420

421
```sql
G
Ganlin Zhao 已提交
422
TO_ISO8601(expr [, timezone])
423 424
```

425
**Description**: The ISO8601 date/time format converted from a UNIX timestamp, plus the timezone. You can specify any time zone with the timezone parameter. If you do not enter this parameter, the time zone on the client is used.
426

427
**Return value type**: VARCHAR
428

429
**Applicable data types**: Integers and timestamps
430

431 432 433
**Nested query**: It can be used in both the outer query and inner query in a nested query.

**Applicable table types**: standard tables and supertables
434

435
**More explanations**:
436

437
- You can specify a time zone in the following format: [z/Z, +/-hhmm, +/-hh, +/-hh:mm]。 For example, TO_ISO8601(1, "+00:00").
G
Ganlin Zhao 已提交
438
- If the input is a UNIX timestamp, the precision of the returned value is determined by the digits of the input timestamp
439 440
- If the input is a column of TIMESTAMP type, the precision of the returned value is same as the precision set for the current data base in use

441

442
#### TO_JSON
443

444
```sql
G
Ganlin Zhao 已提交
445
TO_JSON(str_literal)
446 447
```

448
**Description**: Converts a string into JSON.
449

450
**Return value type**: JSON
451

452
**Applicable data types**: JSON strings in the form `{"literal": literal}`. `{}` indicates a null value. The key must be a string literal. The value can be a numeric literal, string literal, Boolean literal, or null literal. str_literal cannot include escape characters.
453

454 455 456
**Nested query**: It can be used in both the outer query and inner query in a nested query.

**Applicable table types**: table, STable
457 458


459
#### TO_UNIXTIMESTAMP
460

461
```sql
G
Ganlin Zhao 已提交
462
TO_UNIXTIMESTAMP(expr)
463 464
```

465
**Description**: UNIX timestamp converted from a string of date/time format
466

467
**Return value type**: BIGINT
468

469
**Applicable column types**: VARCHAR and NCHAR
470

471 472 473
**Nested query**: It can be used in both the outer query and inner query in a nested query.

**Applicable table types**: standard tables and supertables
474

475
**More explanations**:
476

477 478 479 480 481
- The input string must be compatible with ISO8601/RFC3339 standard, NULL will be returned if the string can't be converted
- The precision of the returned timestamp is same as the precision set for the current data base in use


### Time and Date Functions
482

483
These functions perform operations on times and dates.
484

485
All functions that return the current time, such as `NOW`, `TODAY`, and `TIMEZONE`, are calculated only once per statement even if they appear multiple times.
486

487
#### NOW
488

489
```sql
G
Ganlin Zhao 已提交
490
NOW()
491
```
492

493
**Description**: The current time of the client side system
494

495
**Return value type**: TIMESTAMP
496

497
**Applicable column types**: TIMESTAMP only
498

499 500 501
**Applicable table types**: standard tables and supertables

**Nested query**: It can be used in both the outer query and inner query in a nested query.
502

503
**More explanations**:
504

505 506 507 508
- Add and Subtract operation can be performed, for example NOW() + 1s, the time unit can be:
        b(nanosecond), u(microsecond), a(millisecond)), s(second), m(minute), h(hour), d(day), w(week)
- The precision of the returned timestamp is same as the precision set for the current data base in use

509

510 511 512
#### TIMEDIFF

```sql
G
Ganlin Zhao 已提交
513
TIMEDIFF(expr1, expr2 [, time_unit])
514 515
```

516
**Description**: The difference between two timestamps, and rounded to the time unit specified by `time_unit`
517

518
**Return value type**: BIGINT
519

520
**Applicable column types**: UNIX-style timestamps in BIGINT and TIMESTAMP format and other timestamps in VARCHAR and NCHAR format
521

522
**Applicable table types**: standard tables and supertables
523

524
**Nested query**: It can be used in both the outer query and inner query in a nested query.
525

526
**More explanations**:
527
- Time unit specified by `time_unit` can be:
528 529 530 531
          1b (nanoseconds), 1u (microseconds), 1a (milliseconds), 1s (seconds), 1m (minutes), 1h (hours), 1d (days), or 1w (weeks)
- The precision of the returned timestamp is same as the precision set for the current data base in use
- If the input data is not formatted as a timestamp, the returned value is null.

532

533
#### TIMETRUNCATE
534 535

```sql
536 537 538 539 540 541
TIMETRUNCATE(expr, time_unit [, ignore_timezone])

ignore_timezone: {
    0
  | 1
}
542 543
```

544
**Description**: Truncate the input timestamp with unit specified by `time_unit`
545

546
**Return value type**: TIMESTAMP
547

548
**Applicable column types**: UNIX-style timestamps in BIGINT and TIMESTAMP format and other timestamps in VARCHAR and NCHAR format
549

550
**Applicable table types**: standard tables and supertables
551 552

**More explanations**:
553
- Time unit specified by `time_unit` can be:
554 555 556
          1b (nanoseconds), 1u (microseconds), 1a (milliseconds), 1s (seconds), 1m (minutes), 1h (hours), 1d (days), or 1w (weeks)
- The precision of the returned timestamp is same as the precision set for the current data base in use
- If the input data is not formatted as a timestamp, the returned value is null.
557
- If `1d` is used as `time_unit` to truncate the timestamp, `ignore_timezone` option can be set to indicate if the returned result is affected by client timezone or not.
558 559 560
  For example, if client timezone is set to UTC+0800, TIMETRUNCATE('2020-01-01 23:00:00', 1d, 0) will return '2020-01-01 08:00:00'.
  Otherwise, TIMETRUNCATE('2020-01-01 23:00:00', 1d, 1) will return '2020-01-01 00:00:00'.
  If `ignore_timezone` option is omitted, the default value is set to 1.
561

562
#### TIMEZONE
563 564

```sql
G
Ganlin Zhao 已提交
565
TIMEZONE()
566 567
```

568
**Description**: The timezone of the client side system
569

570
**Applicable data types**: VARCHAR
571

572 573 574
**Applicable column types**: None

**Applicable table types**: standard tables and supertables
575 576


577
#### TODAY
578

579
```sql
G
Ganlin Zhao 已提交
580
TODAY()
581 582
```

583
**Description**: The timestamp of 00:00:00 of the client side system
584

585
**Return value type**: TIMESTAMP
586

587
**Applicable column types**: TIMESTAMP only
588

589
**Applicable table types**: standard tables and supertables
590

591
**More explanations**:
592

593 594 595 596
- Add and Subtract operation can be performed, for example TODAY() + 1s, the time unit can be:
                b(nanosecond), u(microsecond), a(millisecond)), s(second), m(minute), h(hour), d(day), w(week)
- The precision of the returned timestamp is same as the precision set for the current data base in use

597

598
## Aggregate Functions
599

600 601 602
Aggregate functions return one row per group. You can use windows or GROUP BY to group data. Otherwise, the entire query is considered a single group.

TDengine supports the following aggregate functions:
603

G
Ganlin Zhao 已提交
604 605
### APERCENTILE

606
```sql
G
Ganlin Zhao 已提交
607 608 609 610 611 612
APERCENTILE(expr, p [, algo_type])

algo_type: {
    "default"
  | "t-digest"
}
G
Ganlin Zhao 已提交
613 614
```

615
**Description**: Similar to `PERCENTILE`, but a simulated result is returned
G
Ganlin Zhao 已提交
616

617
**Return value type**: DOUBLE
G
Ganlin Zhao 已提交
618

619
**Applicable data types**: Numeric
G
Ganlin Zhao 已提交
620

621
**Applicable table types**: standard tables and supertables
G
Ganlin Zhao 已提交
622

623
**Explanations**
G
Ganlin Zhao 已提交
624
- _p_ is in range [0,100], when _p_ is 0, the result is same as using function MIN; when _p_ is 100, the result is same as function MAX.
625
- `algo_type` can only be input as `default` or `t-digest` Enter `default` to use a histogram-based algorithm. Enter `t-digest` to use the t-digest algorithm to calculate the approximation of the quantile. `default` is used by default.
626
- The approximation result of `t-digest` algorithm is sensitive to input data order. For example, when querying STable with different input data order there might be minor differences in calculated results.
G
Ganlin Zhao 已提交
627

628
### AVG
629

630
```sql
G
Ganlin Zhao 已提交
631
AVG(expr)
632 633
```

634 635 636
**Description**: The average value of the specified fields.

**Return value type**: DOUBLE
637

638
**Applicable data types**: Numeric
639

640
**Applicable table types**: standard tables and supertables
641 642


643
### COUNT
644

645
```sql
G
Ganlin Zhao 已提交
646
COUNT({* | expr})
647 648
```

649
**Description**: The number of records in the specified fields.
650

651
**Return value type**: BIGINT
652

653
**Applicable data types**: Numeric
654

655
**Applicable table types**: standard tables and supertables
656

657
**More explanation**:
658

659 660 661
- Wildcard (\*) is used to represent all columns.
If you input a specific column, the number of non-null values in the column is returned.

662

663
### ELAPSED
664

665
```sql
G
Ganlin Zhao 已提交
666
ELAPSED(ts_primary_key [, time_unit])
667 668
```

669
**Description**`elapsed` function can be used to calculate the continuous time length in which there is valid data. If it's used with `INTERVAL` clause, the returned result is the calcualted time length within each time window. If it's used without `INTERVAL` caluse, the returned result is the calculated time length within the specified time range. Please be noted that the return value of `elapsed` is the number of `time_unit` in the calculated time length.
670

671
**Return value type**: Double if the input value is not NULL;
672

673
**Return value type**: TIMESTAMP
674

675
**Applicable tables**: table, STable, outter in nested query
676

677
**Explanations**
G
Ganlin Zhao 已提交
678
- `ts_primary_key` parameter can only be the first column of a table, i.e. timestamp primary key.
679 680
- The minimum value of `time_unit` is the time precision of the database. If `time_unit` is not specified, the time precision of the database is used as the default time unit. Time unit specified by `time_unit` can be:
          1b (nanoseconds), 1u (microseconds), 1a (milliseconds), 1s (seconds), 1m (minutes), 1h (hours), 1d (days), or 1w (weeks)
681 682 683 684
- It can be used with `INTERVAL` to get the time valid time length of each time window. Please be noted that the return value is same as the time window for all time windows except for the first and the last time window.
- `order by asc/desc` has no effect on the result.
- `group by tbname` must be used together when `elapsed` is used against a STable.
- `group by` must NOT be used together when `elapsed` is used against a table or sub table.
685 686 687
- When used in nested query, it's only applicable when the inner query outputs an implicit timestamp column as the primary key. For example, `select elapsed(ts) from (select diff(value) from sub1)` is legal usage while `select elapsed(ts) from (select * from sub1)` is not. In addition, because elapsed has a strict dependency on the timeline, a statement like `select elapsed(ts) from (select diff(value) from st group by tbname) will return a meaningless result.
- It can't be used with `leastsquares`, `diff`, `derivative`, `top`, `bottom`, `last_row`, `interp`.

688

689
### LEASTSQUARES
690

691
```sql
G
Ganlin Zhao 已提交
692
LEASTSQUARES(expr, start_val, step_val)
693
```
694

695
**Description**: The linear regression function of the specified column and the timestamp column (primary key), `start_val` is the initial value and `step_val` is the step value.
696

697 698 699
**Return value type**: A string in the format of "(slope, intercept)"

**Applicable data types**: Numeric
700

701
**Applicable table types**: table only
702

703

704
### SPREAD
705

706
```sql
G
Ganlin Zhao 已提交
707
SPREAD(expr)
708 709
```

710
**Description**: The difference between the max and the min of a specific column
711

712
**Return value type**: DOUBLE
713

714
**Applicable data types**: Integers and timestamps
715

716
**Applicable table types**: standard tables and supertables
717 718


719
### STDDEV
720

721
```sql
G
Ganlin Zhao 已提交
722
STDDEV(expr)
723 724
```

725
**Description**: Standard deviation of a specific column in a table or STable
726

727
**Return value type**: DOUBLE
728

729 730 731
**Applicable data types**: Numeric

**Applicable table types**: standard tables and supertables
732 733


734
### SUM
735

736
```sql
G
Ganlin Zhao 已提交
737
SUM(expr)
738
```
739

740 741 742
**Description**: The sum of a specific column in a table or STable

**Return value type**: DOUBLE or BIGINT
743

744
**Applicable data types**: Numeric
745

746
**Applicable table types**: standard tables and supertables
747 748


749
### HYPERLOGLOG
750

751
```sql
G
Ganlin Zhao 已提交
752
HYPERLOGLOG(expr)
753
```
754

755 756 757 758 759
**Description**:
  The cardinal number of a specific column is returned by using hyperloglog algorithm. The benefit of using hyperloglog algorithm is that the memory usage is under control when the data volume is huge.
  However, when the data volume is very small, the result may be not accurate, it's recommented to use `select count(data) from (select unique(col) as data from table)` in this case.

**Return value type**: Integer
760

761
**Applicable data types**: Numeric
762

763
**Applicable table types**: standard tables and supertables
764 765


766
### HISTOGRAM
767

768
```sql
G
Ganlin Zhao 已提交
769
HISTOGRAM(expr,bin_type, bin_description, normalized)
770
```
771

772
**Description**:Returns count of data points in user-specified ranges.
773

774
**Return value type** If normalized is set to 1, a DOUBLE is returned; otherwise a BIGINT is returned
775

776
**Applicable data types**: Numeric
777

778
**Applicable table types**: table, STable
779

780
**Explanations**:
G
Ganlin Zhao 已提交
781
- bin_type: parameter to indicate the bucket type, valid inputs are: "user_input", "linear_bin", "log_bin"。
G
Ganlin Zhao 已提交
782 783
- bin_description: parameter to describe how to generate buckets,can be in the following JSON formats for each bin_type respectively:
    - "user_input": "[1, 3, 5, 7]":
784
       User specified bin values.
G
Ganlin Zhao 已提交
785

786 787 788
    - "linear_bin": "{"start": 0.0, "width": 5.0, "count": 5, "infinity": true}"
       "start" - bin starting point.       "width" - bin offset.       "count" - number of bins generated.       "infinity" - whether to add(-inf, inf)as start/end point in generated set of bins.
       The above "linear_bin" descriptor generates a set of bins: [-inf, 0.0, 5.0, 10.0, 15.0, 20.0, +inf].
G
Ganlin Zhao 已提交
789

790 791 792 793
    - "log_bin": "{"start":1.0, "factor": 2.0, "count": 5, "infinity": true}"
       "start" - bin starting point.       "factor" - exponential factor of bin offset.       "count" - number of bins generated.       "infinity" - whether to add(-inf, inf)as start/end point in generated range of bins.
       The above "linear_bin" descriptor generates a set of bins: [-inf, 1.0, 2.0, 4.0, 8.0, 16.0, +inf].
- normalized: setting to 1/0 to turn on/off result normalization. Valid values are 0 or 1.
794 795


G
Ganlin Zhao 已提交
796
### PERCENTILE
797

798
```sql
G
Ganlin Zhao 已提交
799
PERCENTILE(expr, p)
800
```
801

G
Ganlin Zhao 已提交
802
**Description**: The value whose rank in a specific column matches the specified percentage. If such a value matching the specified percentage doesn't exist in the column, an interpolation value will be returned.
803

804
**Return value type**: DOUBLE
805

806
**Applicable column types**: Numeric
807

808
**Applicable table types**: table only
809

G
Ganlin Zhao 已提交
810
**More explanations**: _p_ is in range [0,100], when _p_ is 0, the result is same as using function MIN; when _p_ is 100, the result is same as function MAX.
811 812


813 814 815
## Selection Functions

Selection functions return one or more results depending. You can specify the timestamp column, tbname pseudocolumn, or tag columns to show which rows contain the selected value.
816

817
### BOTTOM
818

819
```sql
G
Ganlin Zhao 已提交
820
BOTTOM(expr, k)
821 822
```

823
**Description**: The least _k_ values of a specific column in a table or STable. If a value has multiple occurrences in the column but counting all of them in will exceed the upper limit _k_, then a part of them will be returned randomly.
824

825
**Return value type**:Same as the data type of the column being operated upon
826

827
**Applicable data types**: Numeric
828

829
**Applicable table types**: standard tables and supertables
830

831
**More explanation**:
832

833 834 835
- _k_ must be in range [1,100]
- The timestamp associated with the selected values are returned too
- Can't be used with `FILL`
836

837
### FIRST
838

839
```sql
G
Ganlin Zhao 已提交
840
FIRST(expr)
841 842
```

843
**Description**: The first non-null value of a specific column in a table or STable
844

845
**Return value type**:Same as the data type of the column being operated upon
846

847
**Applicable data types**: Numeric
848

849
**Applicable table types**: standard tables and supertables
850

851
**More explanation**:
852

853 854 855
- FIRST(\*) can be used to get the first non-null value of all columns
- NULL will be returned if all the values of the specified column are all NULL
- A result will NOT be returned if all the columns in the result set are all NULL
856

857
### INTERP
858

859
```sql
G
Ganlin Zhao 已提交
860
INTERP(expr)
861 862
```

863
**Description**: The value that matches the specified timestamp range is returned, if existing; or an interpolation value is returned.
864

865
**Return value type**: Same as the column being operated upon
866

867
**Applicable data types**: Numeric
868

869
**Applicable table types**: standard tables and supertables
870

871
**More explanations**
872

873 874
- `INTERP` is used to get the value that matches the specified time slice from a column. If no such value exists an interpolation value will be returned based on `FILL` parameter.
- The input data of `INTERP` is the value of the specified column and a `where` clause can be used to filter the original data. If no `where` condition is specified then all original data is the input.
G
Ganlin Zhao 已提交
875
- `INTERP` must be used along with `RANGE`, `EVERY`, `FILL` keywords.
876
- The output time range of `INTERP` is specified by `RANGE(timestamp1,timestamp2)` parameter, with timestamp1 < timestamp2. timestamp1 is the starting point of the output time range and must be specified. timestamp2 is the ending point of the output time range and must be specified.
G
Ganlin Zhao 已提交
877
- The number of rows in the result set of `INTERP` is determined by the parameter `EVERY(time_unit)`. Starting from timestamp1, one interpolation is performed for every time interval specified `time_unit` parameter. The parameter `time_unit` must be an integer, with no quotes, with a time unit of: a(millisecond)), s(second), m(minute), h(hour), d(day), or w(week). For example, `EVERY(500a)` will interpolate every 500 milliseconds.
878
- Interpolation is performed based on `FILL` parameter. For more information about FILL clause, see [FILL Clause](./distinguished/#fill-clause).
G
Ganlin Zhao 已提交
879
- `INTERP` can only be used to interpolate in single timeline. So it must be used with `partition by tbname` when it's used on a STable.
G
Ganlin Zhao 已提交
880
- Pseudocolumn `_irowts` can be used along with `INTERP` to return the timestamps associated with interpolation points(support after version 3.0.1.4).
881
- Pseudocolumn `_isfilled` can be used along with `INTERP` to indicate whether the results are original records or data points generated by interpolation algorithm(support after version 3.0.2.3).
882

883
### LAST
884

885
```sql
G
Ganlin Zhao 已提交
886
LAST(expr)
887 888
```

889
**Description**: The last non-NULL value of a specific column in a table or STable
890

891
**Return value type**:Same as the data type of the column being operated upon
892

893
**Applicable data types**: Numeric
894

895
**Applicable table types**: standard tables and supertables
896

897
**More explanation**:
898

899 900 901
- LAST(\*) can be used to get the last non-NULL value of all columns
- If the values of a column in the result set are all NULL, NULL is returned for that column; if all columns in the result are all NULL, no result will be returned.
- When it's used on a STable, if there are multiple values with the timestamp in the result set, one of them will be returned randomly and it's not guaranteed that the same value is returned if the same query is run multiple times.
902

903

904
### LAST_ROW
905

906
```sql
G
Ganlin Zhao 已提交
907
LAST_ROW(expr)
908 909
```

910
**Description**: The last row of a table or STable
911

912
**Return value type**:Same as the data type of the column being operated upon
913

914
**Applicable data types**: Numeric
915

916
**Applicable table types**: standard tables and supertables
917 918 919

**More explanations**:

920 921
- When it's used on a STable, if there are multiple values with the timestamp in the result set, one of them will be returned randomly and it's not guaranteed that the same value is returned if the same query is run multiple times.
- Can't be used with `INTERVAL`.
922

923
### MAX
924

925
```sql
G
Ganlin Zhao 已提交
926
MAX(expr)
927 928
```

929 930 931
**Description**: The maximum value of a specific column of a table or STable

**Return value type**:Same as the data type of the column being operated upon
932

G
Ganlin Zhao 已提交
933
**Applicable data types**: Numeric
934

935
**Applicable table types**: standard tables and supertables
936 937


938
### MIN
939

940
```sql
G
Ganlin Zhao 已提交
941
MIN(expr)
942
```
943

944 945 946
**Description**: The minimum value of a specific column in a table or STable

**Return value type**:Same as the data type of the column being operated upon
947

G
Ganlin Zhao 已提交
948
**Applicable data types**: Numeric
949

950
**Applicable table types**: standard tables and supertables
951 952


G
Ganlin Zhao 已提交
953
### MODE
954

955
```sql
G
Ganlin Zhao 已提交
956
MODE(expr)
957
```
958

G
Ganlin Zhao 已提交
959
**Description**:The value which has the highest frequency of occurrence. One random value is returned if there are multiple values which have highest frequency of occurrence.
960

961
**Return value type**: Same as the input data
962

963 964 965
**Applicable data types**: Numeric

**Applicable table types**: standard tables and supertables
966 967


G
Ganlin Zhao 已提交
968 969 970
### SAMPLE

```sql
G
Ganlin Zhao 已提交
971
SAMPLE(expr, k)
G
Ganlin Zhao 已提交
972 973 974 975
```

**Description**: _k_ sampling values of a specific column. The applicable range of _k_ is [1,1000].

976
**Return value type**: Same as the column being operated plus the associated timestamp
G
Ganlin Zhao 已提交
977

978
**Applicable data types**: Any data type except for tags of STable
G
Ganlin Zhao 已提交
979

980
**Applicable nested query**: Inner query and Outer query
G
Ganlin Zhao 已提交
981

982
**Applicable table types**: standard tables and supertables
G
Ganlin Zhao 已提交
983

G
Ganlin Zhao 已提交
984
**More explanations**:
985 986 987

This function cannot be used in expression calculation.
- Must be used with `PARTITION BY tbname` when it's used on a STable to force the result on each single timeline
G
Ganlin Zhao 已提交
988

989

990
### TAIL
991

992
```sql
G
Ganlin Zhao 已提交
993
TAIL(expr, k, offset_val)
994 995
```

996
**Description**: The next _k_ rows are returned after skipping the last `offset_val` rows, NULL values are not ignored. `offset_val` is optional parameter. When it's not specified, the last _k_ rows are returned. When `offset_val` is used, the effect is same as `order by ts desc LIMIT k OFFSET offset_val`.
997

998 999 1000
**Parameter value range**: k: [1,100] offset_val: [0,100]

**Return value type**:Same as the data type of the column being operated upon
1001

1002 1003 1004
**Applicable data types**: Any data type except for timestamp, i.e. the primary key

**Applicable table types**: standard tables and supertables
1005 1006


1007
### TOP
1008

1009
```sql
G
Ganlin Zhao 已提交
1010
TOP(expr, k)
1011 1012
```

1013
**Description**: The greatest _k_ values of a specific column in a table or STable. If a value has multiple occurrences in the column but counting all of them in will exceed the upper limit _k_, then a part of them will be returned randomly.
1014

1015
**Return value type**:Same as the data type of the column being operated upon
1016

1017
**Applicable data types**: Numeric
1018

1019
**Applicable table types**: standard tables and supertables
1020

1021
**More explanation**:
1022

1023 1024 1025
- _k_ must be in range [1,100]
- The timestamp associated with the selected values are returned too
- Can't be used with `FILL`
1026

1027
### UNIQUE
1028

1029
```sql
G
Ganlin Zhao 已提交
1030
UNIQUE(expr)
1031 1032
```

1033
**Description**: The values that occur the first time in the specified column. The effect is similar to `distinct` keyword, but it can also be used to match tags or timestamp. The first occurrence of a timestamp or tag is used.
1034

1035
**Return value type**:Same as the data type of the column being operated upon
1036

1037
**Applicable column types**: Any data types except for timestamp
1038

1039
**Applicable table types**: table, STable
1040 1041


1042
## Time-Series Extensions
1043

1044
TDengine includes extensions to standard SQL that are intended specifically for time-series use cases. The functions enabled by these extensions require complex queries to implement in general-purpose databases. By offering them as built-in extensions, TDengine reduces user workload.
1045

1046
### CSUM
1047

1048
```sql
G
Ganlin Zhao 已提交
1049
CSUM(expr)
1050 1051
```

1052
**Description**: The cumulative sum of each row for a specific column. The number of output rows is same as that of the input rows.
1053

1054
**Return value type**: Long integer for integers; Double for floating points. uint64_t for unsigned integers
1055

1056
**Applicable data types**: Numeric
1057

1058
**Nested query**: It can be used in both the outer query and inner query in a nested query.
1059

1060 1061
**Applicable table types**: standard tables and supertables

G
Ganlin Zhao 已提交
1062 1063
**More explanations**:

1064
- Arithmetic operation can't be performed on the result of `csum` function
G
Ganlin Zhao 已提交
1065
- Can only be used with aggregate functions This function can be used with supertables and standard tables.
1066
- Must be used with `PARTITION BY tbname` when it's used on a STable to force the result on each single timeline
1067 1068


1069
### DERIVATIVE
1070

1071
```sql
G
Ganlin Zhao 已提交
1072 1073 1074 1075 1076 1077
DERIVATIVE(expr, time_inerval, ignore_negative)

ignore_negative: {
    0
  | 1
}
1078 1079
```

1080
**Description**: The derivative of a specific column. The time rage can be specified by parameter `time_interval`, the minimum allowed time range is 1 second (1s); the value of `ignore_negative` can be 0 or 1, 1 means negative values are ignored.
1081

1082
**Return value type**: DOUBLE
1083

1084
**Applicable data types**: Numeric
1085

1086
**Applicable table types**: standard tables and supertables
1087

G
Ganlin Zhao 已提交
1088 1089
**More explanation**:

1090
- It can be used together with `PARTITION BY tbname` against a STable.
1091
- It can be used together with a selected column. For example: select \_rowts, DERIVATIVE() from。
1092

1093
### DIFF
1094

1095
```sql
G
Ganlin Zhao 已提交
1096 1097 1098 1099 1100 1101
DIFF(expr [, ignore_negative])

ignore_negative: {
    0
  | 1
}
1102 1103
```

1104
**Description**: The different of each row with its previous row for a specific column. `ignore_negative` can be specified as 0 or 1, the default value is 1 if it's not specified. `1` means negative values are ignored.
1105

1106
**Return value type**:Same as the data type of the column being operated upon
1107

1108
**Applicable data types**: Numeric
1109

1110
**Applicable table types**: standard tables and supertables
1111

G
Ganlin Zhao 已提交
1112
**More explanation**:
1113 1114 1115

- The number of result rows is the number of rows subtracted by one, no output for the first row
- It can be used together with a selected column. For example: select \_rowts, DIFF() from。
1116 1117


1118
### IRATE
1119

1120
```sql
G
Ganlin Zhao 已提交
1121
IRATE(expr)
1122 1123
```

1124
**Description**: instantaneous rate on a specific column. The last two samples in the specified time range are used to calculate instantaneous rate. If the last sample value is smaller, then only the last sample value is used instead of the difference between the last two sample values.
1125

1126
**Return value type**: DOUBLE
1127

1128
**Applicable data types**: Numeric
1129

1130
**Applicable table types**: standard tables and supertables
1131 1132


1133
### MAVG
1134

1135
```sql
G
Ganlin Zhao 已提交
1136
MAVG(expr, k)
1137 1138
```

1139
**Description**: The moving average of continuous _k_ values of a specific column. If the number of input rows is less than _k_, nothing is returned. The applicable range of _k_ is [1,1000].
1140

1141
**Return value type**: DOUBLE
1142

1143
**Applicable data types**: Numeric
1144

1145
**Nested query**: It can be used in both the outer query and inner query in a nested query.
1146

1147
**Applicable table types**: standard tables and supertables
1148

G
Ganlin Zhao 已提交
1149 1150 1151
**More explanations**:

- Arithmetic operation can't be performed on the result of `MAVG`.
1152 1153
- Can only be used with data columns, can't be used with tags. - Can't be used with aggregate functions.
- Must be used with `PARTITION BY tbname` when it's used on a STable to force the result on each single timeline
1154 1155 1156 1157


### STATECOUNT

1158
```sql
G
Ganlin Zhao 已提交
1159
STATECOUNT(expr, oper, val)
1160 1161
```

1162
**Description**: The number of continuous rows satisfying the specified conditions for a specific column. The result is shown as an extra column for each row. If the specified condition is evaluated as true, the number is increased by 1; otherwise the number is reset to -1. If the input value is NULL, then the corresponding row is skipped.
1163 1164 1165

**Applicable parameter values**:

S
Sean Ely 已提交
1166
- oper : Can be one of `'LT'` (lower than), `'GT'` (greater than), `'LE'` (lower than or equal to), `'GE'` (greater than or equal to), `'NE'` (not equal to), `'EQ'` (equal to), the value is case insensitive, the value must be in quotes.
1167
- val : Numeric types
1168

1169
**Return value type**: Integer
1170

1171
**Applicable data types**: Numeric
1172

1173
**Applicable nested query**: Outer query only
1174

1175
**Applicable table types**: standard tables and supertables
1176 1177 1178

**More explanations**:

1179 1180 1181
- Must be used together with `PARTITION BY tbname` when it's used on a STable to force the result into each single timeline]
- Can't be used with window operation, like interval/state_window/session_window

1182 1183 1184

### STATEDURATION

1185
```sql
G
Ganlin Zhao 已提交
1186
STATEDURATION(expr, oper, val, unit)
1187 1188
```

1189
**Description**: The length of time range in which all rows satisfy the specified condition for a specific column. The result is shown as an extra column for each row. The length for the first row that satisfies the condition is 0. Next, if the condition is evaluated as true for a row, the time interval between current row and its previous row is added up to the time range; otherwise the time range length is reset to -1. If the value of the column is NULL, the corresponding row is skipped.
1190 1191 1192

**Applicable parameter values**:

S
Sean Ely 已提交
1193
- oper : Can be one of `'LT'` (lower than), `'GT'` (greater than), `'LE'` (lower than or equal to), `'GE'` (greater than or equal to), `'NE'` (not equal to), `'EQ'` (equal to), the value is case insensitive, the value must be in quotes.
1194 1195
- val : Numeric types
- unit: The unit of time interval. Enter one of the following options: 1b (nanoseconds), 1u (microseconds), 1a (milliseconds), 1s (seconds), 1m (minutes), 1h (hours), 1d (days), or 1w (weeks) If you do not enter a unit of time, the precision of the current database is used by default.
1196

1197
**Return value type**: Integer
1198

1199
**Applicable data types**: Numeric
1200

1201
**Applicable nested query**: Outer query only
1202

1203
**Applicable table types**: standard tables and supertables
1204 1205 1206

**More explanations**:

1207 1208 1209
- Must be used together with `PARTITION BY tbname` when it's used on a STable to force the result into each single timeline]
- Can't be used with window operation, like interval/state_window/session_window

1210

1211
### TWA
1212

1213
```sql
G
Ganlin Zhao 已提交
1214
TWA(expr)
1215 1216
```

1217
**Description**: Time weighted average on a specific column within a time range
1218

1219
**Return value type**: DOUBLE
1220

1221
**Applicable data types**: Numeric
1222

1223
**Applicable table types**: standard tables and supertables
1224

1225
- Must be used together with `PARTITION BY tbname` to force the result into each single timeline.
1226 1227


1228
## System Information Functions
1229

1230
### DATABASE
1231

1232
```sql
1233
SELECT DATABASE();
1234 1235
```

1236 1237
**Description**: The current database. If no database is specified upon logging in and no database is specified with `USE` after login, NULL will be returned by `select database()`.

1238

1239
### CLIENT_VERSION
1240

1241
```sql
1242
SELECT CLIENT_VERSION();
1243 1244
```

1245
**Description**: The client version.
1246

1247
### SERVER_VERSION
1248

1249
```sql
1250
SELECT SERVER_VERSION();
1251 1252
```

1253
**Description**: The server version.
1254

1255
### SERVER_STATUS
1256

1257
```sql
S
Sean Ely 已提交
1258
SELECT SERVER_STATUS();
1259 1260
```

1261
**Description**: The server status.