10-function.md 41.2 KB
Newer Older
1
---
2
sidebar_label: Functions
3
title: Functions
4
toc_max_heading_level: 4
5 6
---

7
## Single Row Functions
8

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

11
### Mathematical Functions
12

13
#### ABS
14

15 16 17
```sql
SELECT ABS(field_name) FROM { tb_name | stb_name } [WHERE clause]
```
18

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

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

23
**Applicable data types**: Numeric
24

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

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

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

31
#### ACOS
32

33 34
```sql
SELECT ACOS(field_name) FROM { tb_name | stb_name } [WHERE clause]
35 36
```

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

39
**Return value type**: Double
40

41
**Applicable data types**: Numeric
42

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

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

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

49
#### ASIN
50

51 52
```sql
SELECT ASIN(field_name) FROM { tb_name | stb_name } [WHERE clause]
53 54
```

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

57
**Return value type**: Double
58

59
**Applicable data types**: Numeric
60

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

63 64 65
**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.
66

67

68
#### ATAN
69

70 71
```sql
SELECT ATAN(field_name) FROM { tb_name | stb_name } [WHERE clause]
72 73
```

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

76
**Return value type**: Double
77

78
**Applicable data types**: Numeric
79

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

82 83 84
**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.
85

86

87
#### CEIL
88

89
```sql
90
SELECT CEIL(field_name) FROM { tb_name | stb_name } [WHERE clause];
91 92
```

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

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

97
**Applicable data types**: Numeric
98

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

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

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

105
#### COS
106

107 108
```sql
SELECT COS(field_name) FROM { tb_name | stb_name } [WHERE clause]
109 110
```

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

113
**Return value type**: Double
114

115
**Applicable data types**: Numeric
116

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

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

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

123
#### FLOOR
124

125
```sql
126
SELECT FLOOR(field_name) FROM { tb_name | stb_name } [WHERE clause];
127 128
```

129 130
**Description**: The rounded down value of a specific field  
 **More explanations**: The restrictions are same as those of the `CEIL` function.
131 132 133 134

#### LOG

```sql
135
SELECT LOG(field_name[, base]) FROM { tb_name | stb_name } [WHERE clause]
136 137
```

138 139 140
**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
141

142
**Applicable data types**: Numeric
143

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

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

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


151
#### POW
152

153 154 155
```sql
SELECT POW(field_name, power) FROM { tb_name | stb_name } [WHERE clause]
```
156

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

**Return value type**: Double
160

161
**Applicable data types**: Numeric
162

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

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

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


170
#### ROUND
171

172
```sql
173
SELECT ROUND(field_name) FROM { tb_name | stb_name } [WHERE clause];
174 175
```

176 177
**Description**: The rounded value of a specific field.  
 **More explanations**: The restrictions are same as those of the `CEIL` function.
178 179


180
#### SIN
181

182 183 184
```sql
SELECT SIN(field_name) FROM { tb_name | stb_name } [WHERE clause]
```
185

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

188
**Return value type**: Double
189

190
**Applicable data types**: Numeric
191

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

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

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

198
#### SQRT
199

200 201 202
```sql
SELECT SQRT(field_name) FROM { tb_name | stb_name } [WHERE clause]
```
203

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

206
**Return value type**: Double
207

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

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

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

214
**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 已提交
215

216
#### TAN
217

218 219
```sql
SELECT TAN(field_name) FROM { tb_name | stb_name } [WHERE clause]
220 221
```

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

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

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

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

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

232
**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 已提交
233

234
### Concatenation Functions
235

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

238
#### CHAR_LENGTH
239

240
```sql
241
SELECT CHAR_LENGTH(str|column) FROM { tb_name | stb_name } [WHERE clause]
242 243
```

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

246
**Return value type**: Bigint
247

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

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

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

254
#### CONCAT
255

256 257
```sql
SELECT CONCAT(str1|column1, str2|column2, ...) FROM { tb_name | stb_name } [WHERE clause]
258 259
```

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

262
**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.
263

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

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

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


271
#### CONCAT_WS
272

273
```sql
274
SELECT CONCAT_WS(separator, str1|column1, str2|column2, ...) FROM { tb_name | stb_name } [WHERE clause]
275 276
```

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

279
**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.
280

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

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

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


288
#### LENGTH
289

290
```sql
291
SELECT LENGTH(str|column) FROM { tb_name | stb_name } [WHERE clause]
292 293
```

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

296
**Return value type**: Bigint
297

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

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

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


305
#### LOWER
306

307
```sql
308
SELECT LOWER(str|column) FROM { tb_name | stb_name } [WHERE clause]
309 310
```

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

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

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

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

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


322
#### LTRIM
323

324
```sql
325
SELECT LTRIM(str|column) FROM { tb_name | stb_name } [WHERE clause]
326 327
```

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

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

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

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

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


339
#### RTRIM
340

341 342
```sql
SELECT LTRIM(str|column) FROM { tb_name | stb_name } [WHERE clause]
343 344
```

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

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

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

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

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


356
#### SUBSTR
357

358
```sql
359
SELECT SUBSTR(str,pos[,len]) FROM { tb_name | stb_name } [WHERE clause]
360 361
```

362
**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.
363

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

366
**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.
367

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

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


373
#### UPPER
374

375
```sql
376
SELECT UPPER(str|column) FROM { tb_name | stb_name } [WHERE clause]
377 378
```

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

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

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

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

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


390
### Conversion Functions
391

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

394
#### CAST
395

396 397
```sql
SELECT CAST(expression AS type_name) FROM { tb_name | stb_name } [WHERE clause]
398 399
```

400
**Description**: Convert the input data `expression` into the type specified by `type_name`. This function can be used only in SELECT statements.
401

402 403 404 405 406
**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.
407

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

410
**More explanations**:
411

412
- Error will be reported for unsupported type casting
413
- Some values of some supported data types may not be casted, below are known issues:
414 415 416
        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.
417

418
#### TO_ISO8601
419

420
```sql
421
SELECT TO_ISO8601(ts[, timezone]) FROM { tb_name | stb_name } [WHERE clause];
422 423
```

424
**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.
425

426
**Return value type**: VARCHAR
427

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

430 431 432
**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
433

434
**More explanations**:
435

436 437 438 439
- You can specify a time zone in the following format: [z/Z, +/-hhmm, +/-hh, +/-hh:mm]。 For example, TO_ISO8601(1, "+00:00").
- If the input is a UNIX timestamp, the precision of the returned value is determined by the digits of the input timestamp 
- 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

440

441
#### TO_JSON
442

443 444
```sql
SELECT TO_JSON(str_literal) FROM { tb_name | stb_name } [WHERE clause];
445 446
```

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

449
**Return value type**: JSON
450

451
**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.
452

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

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


458
#### TO_UNIXTIMESTAMP
459

460
```sql
461
SELECT TO_UNIXTIMESTAMP(datetime_string) FROM { tb_name | stb_name } [WHERE clause];
462 463
```

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

466
**Return value type**: BIGINT
467

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

470 471 472
**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
473

474
**More explanations**:
475

476 477 478 479 480
- 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
481

482
These functions perform operations on times and dates.
483

484
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.
485

486
#### NOW
487

488 489 490 491 492
```sql
SELECT NOW() FROM { tb_name | stb_name } [WHERE clause];
SELECT select_expr FROM { tb_name | stb_name } WHERE ts_col cond_operatior NOW();
INSERT INTO tb_name VALUES (NOW(), ...);
```
493

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

496
**Return value type**: TIMESTAMP
497

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

500 501 502
**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.
503

504
**More explanations**:
505

506 507 508 509
- 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

510

511 512 513
#### TIMEDIFF

```sql
514
SELECT TIMEDIFF(ts | datetime_string1, ts | datetime_string2 [, time_unit]) FROM { tb_name | stb_name } [WHERE clause];
515 516
```

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

519
**Return value type**: BIGINT
520

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

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

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

527
**More explanations**:
528
- Time unit specified by `time_unit` can be:
529 530 531 532
          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.

533

534
#### TIMETRUNCATE
535 536

```sql
537
SELECT TIMETRUNCATE(ts | datetime_string , time_unit) FROM { tb_name | stb_name } [WHERE clause];
538 539
```

540
**Description**: Truncate the input timestamp with unit specified by `time_unit`
541

542
**Return value type**: TIMESTAMP
543

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

546
**Applicable table types**: standard tables and supertables
547 548

**More explanations**:
549
- Time unit specified by `time_unit` can be:
550 551 552 553
          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.

554

555
#### TIMEZONE
556 557

```sql
558
SELECT TIMEZONE() FROM { tb_name | stb_name } [WHERE clause];
559 560
```

561
**Description**: The timezone of the client side system
562

563
**Applicable data types**: VARCHAR
564

565 566 567
**Applicable column types**: None

**Applicable table types**: standard tables and supertables
568 569


570
#### TODAY
571

572 573 574 575
```sql
SELECT TODAY() FROM { tb_name | stb_name } [WHERE clause];
SELECT select_expr FROM { tb_name | stb_name } WHERE ts_col cond_operatior TODAY()];
INSERT INTO tb_name VALUES (TODAY(), ...);
576 577
```

578
**Description**: The timestamp of 00:00:00 of the client side system
579

580
**Return value type**: TIMESTAMP
581

582
**Applicable column types**: TIMESTAMP only
583

584
**Applicable table types**: standard tables and supertables
585

586
**More explanations**:
587

588 589 590 591
- 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

592

593
## Aggregate Functions
594

595 596 597
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:
598

G
Ganlin Zhao 已提交
599 600
### APERCENTILE

601 602
```sql
SELECT APERCENTILE(field_name, P[, algo_type]) FROM { tb_name | stb_name } [WHERE clause]
G
Ganlin Zhao 已提交
603 604
```

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

607
**Return value type**: DOUBLE
G
Ganlin Zhao 已提交
608

609
**Applicable data types**: Numeric
G
Ganlin Zhao 已提交
610

611
**Applicable table types**: standard tables and supertables
G
Ganlin Zhao 已提交
612

613
**Explanations**
G
Ganlin Zhao 已提交
614
- _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.
615
- `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.
G
Ganlin Zhao 已提交
616

617
### AVG
618

619
```sql
620
SELECT AVG(field_name) FROM tb_name [WHERE clause];
621 622
```

623 624 625
**Description**: The average value of the specified fields.

**Return value type**: DOUBLE
626

627
**Applicable data types**: Numeric
628

629
**Applicable table types**: standard tables and supertables
630 631


632
### COUNT
633

634
```sql
635
SELECT COUNT([*|field_name]) FROM tb_name [WHERE clause];
636 637
```

638
**Description**: The number of records in the specified fields.
639

640
**Return value type**: BIGINT
641

642
**Applicable data types**: Numeric
643

644
**Applicable table types**: standard tables and supertables
645

646
**More explanation**:
647

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

651

652
### ELAPSED
653

654 655
```sql
SELECT ELAPSED(ts_primary_key [, time_unit]) FROM { tb_name | stb_name } [WHERE clause] [INTERVAL(interval [, offset]) [SLIDING sliding]];
656 657
```

658
**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.
659

660
**Return value type**: Double if the input value is not NULL;
661

662
**Return value type**: TIMESTAMP
663

664
**Applicable tables**: table, STable, outter in nested query
665

666 667
**Explanations**
- `field_name` parameter can only be the first column of a table, i.e. timestamp primary key.
668 669
- 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)
670 671 672 673
- 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.
674 675 676
- 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`.

677

678
### LEASTSQUARES
679

680
```sql
681 682
SELECT LEASTSQUARES(field_name, start_val, step_val) FROM tb_name [WHERE clause];
```
683

684
**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.
685

686 687 688
**Return value type**: A string in the format of "(slope, intercept)"

**Applicable data types**: Numeric
689

690
**Applicable table types**: table only
691

692

693
### SPREAD
694

695
```sql
696
SELECT SPREAD(field_name) FROM { tb_name | stb_name } [WHERE clause];
697 698
```

699
**Description**: The difference between the max and the min of a specific column
700

701
**Return value type**: DOUBLE
702

703
**Applicable data types**: Integers and timestamps
704

705
**Applicable table types**: standard tables and supertables
706 707


708
### STDDEV
709

710
```sql
711
SELECT STDDEV(field_name) FROM tb_name [WHERE clause];
712 713
```

714
**Description**: Standard deviation of a specific column in a table or STable
715

716
**Return value type**: DOUBLE
717

718 719 720
**Applicable data types**: Numeric

**Applicable table types**: standard tables and supertables
721 722


723
### SUM
724

725
```sql
726 727
SELECT SUM(field_name) FROM tb_name [WHERE clause];
```
728

729 730 731
**Description**: The sum of a specific column in a table or STable

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

733
**Applicable data types**: Numeric
734

735
**Applicable table types**: standard tables and supertables
736 737


738
### HYPERLOGLOG
739

740
```sql
741 742
SELECT HYPERLOGLOG(field_name) FROM { tb_name | stb_name } [WHERE clause];
```
743

744 745 746 747 748
**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
749

750
**Applicable data types**: Numeric
751

752
**Applicable table types**: standard tables and supertables
753 754


755
### HISTOGRAM
756

757
```sql
758 759
SELECT HISTOGRAM(field_name,bin_type, bin_description, normalized) FROM tb_name [WHERE clause];
```
760

761
**Description**:Returns count of data points in user-specified ranges.
762

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

765
**Applicable data types**: Numeric
766

767
**Applicable table types**: table, STable
768

769
**Explanations**:
G
Ganlin Zhao 已提交
770
- bin_type: parameter to indicate the bucket type, valid inputs are: "user_input", "linear_bin", "log_bin"。
771 772 773 774 775 776 777 778 779 780 781 782
- 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]": 
       User specified bin values.
       
    - "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].
 
    - "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.
783 784


G
Ganlin Zhao 已提交
785
### PERCENTILE
786

787
```sql
G
Ganlin Zhao 已提交
788
SELECT PERCENTILE(field_name, P) FROM { tb_name } [WHERE clause];
789
```
790

G
Ganlin Zhao 已提交
791
**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.
792

793
**Return value type**: DOUBLE
794

795
**Applicable column types**: Numeric
796

797
**Applicable table types**: table only
798

G
Ganlin Zhao 已提交
799
**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.
800 801


802 803 804
## 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.
805

806
### BOTTOM
807

808
```sql
809
SELECT BOTTOM(field_name, K) FROM { tb_name | stb_name } [WHERE clause];
810 811
```

812
**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.
813

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

816
**Applicable data types**: Numeric
817

818
**Applicable table types**: standard tables and supertables
819

820
**More explanation**:
821

822 823 824
- _k_ must be in range [1,100]
- The timestamp associated with the selected values are returned too
- Can't be used with `FILL`
825

826
### FIRST
827

828
```sql
829
SELECT FIRST(field_name) FROM { tb_name | stb_name } [WHERE clause];
830 831
```

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

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

836
**Applicable data types**: Numeric
837

838
**Applicable table types**: standard tables and supertables
839

840
**More explanation**:
841

842 843 844
- 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
845

846
### INTERP
847

848
```sql
G
Ganlin Zhao 已提交
849
SELECT INTERP(field_name) FROM { tb_name | stb_name } [WHERE where_condition] RANGE(timestamp1,timestamp2) EVERY(interval) FILL({ VALUE | PREV | NULL | LINEAR | NEXT});
850 851
```

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

854
**Return value type**: Same as the column being operated upon
855

856
**Applicable data types**: Numeric
857

858
**Applicable table types**: standard tables and supertables
859

860
**More explanations**
861

862 863
- `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 已提交
864 865 866 867
- 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. 
- The number of rows in the result set of `INTERP` is determined by the parameter `EVERY`. Starting from timestamp1, one interpolation is performed for every time interval specified `EVERY` parameter. 
- Interpolation is performed based on `FILL` parameter. 
- `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.
868

869
### LAST
870

871
```sql
872
SELECT LAST(field_name) FROM { tb_name | stb_name } [WHERE clause];
873 874
```

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

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

879
**Applicable data types**: Numeric
880

881
**Applicable table types**: standard tables and supertables
882

883
**More explanation**:
884

885 886 887
- 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.
888

889

890
### LAST_ROW
891

892
```sql
893
SELECT LAST_ROW(field_name) FROM { tb_name | stb_name };
894 895
```

896
**Description**: The last row of a table or STable
897

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

900
**Applicable data types**: Numeric
901

902
**Applicable table types**: standard tables and supertables
903 904 905

**More explanations**:

906 907
- 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`.
908

909
### MAX
910

911
```sql
912
SELECT MAX(field_name) FROM { tb_name | stb_name } [WHERE clause];
913 914
```

915 916 917
**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
918

919
**Applicable data types**: Numeric
920

921
**Applicable table types**: standard tables and supertables
922 923


924
### MIN
925

926
```sql
927 928
SELECT MIN(field_name) FROM {tb_name | stb_name} [WHERE clause];
```
929

930 931 932
**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
933

934
**Applicable data types**: Numeric
935

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


G
Ganlin Zhao 已提交
939
### MODE
940

941
```sql
G
Ganlin Zhao 已提交
942
SELECT MODE(field_name) FROM tb_name [WHERE clause];
943
```
944

G
Ganlin Zhao 已提交
945
**Description**:The value which has the highest frequency of occurrence. NULL is returned if there are multiple values which have highest frequency of occurrence.
946

947
**Return value type**: Same as the input data
948

949 950 951
**Applicable data types**: Numeric

**Applicable table types**: standard tables and supertables
952 953


G
Ganlin Zhao 已提交
954 955 956
### SAMPLE

```sql
957
SELECT SAMPLE(field_name, K) FROM { tb_name | stb_name } [WHERE clause]
G
Ganlin Zhao 已提交
958 959 960 961
```

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

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

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

966
**Applicable nested query**: Inner query and Outer query
G
Ganlin Zhao 已提交
967

968
**Applicable table types**: standard tables and supertables
G
Ganlin Zhao 已提交
969

970 971 972 973
**More explanations**: 

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 已提交
974

975

976
### TAIL
977

978
```sql
979
SELECT TAIL(field_name, k, offset_val) FROM {tb_name | stb_name} [WHERE clause];
980 981
```

982
**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`.
983

984 985 986
**Parameter value range**: k: [1,100] offset_val: [0,100]

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

988 989 990
**Applicable data types**: Any data type except for timestamp, i.e. the primary key

**Applicable table types**: standard tables and supertables
991 992


993
### TOP
994

995
```sql
996
SELECT TOP(field_name, K) FROM { tb_name | stb_name } [WHERE clause];
997 998
```

999
**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.
1000

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

1003
**Applicable data types**: Numeric
1004

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

1007
**More explanation**:
1008

1009 1010 1011
- _k_ must be in range [1,100]
- The timestamp associated with the selected values are returned too
- Can't be used with `FILL`
1012

1013
### UNIQUE
1014

1015
```sql
1016
SELECT UNIQUE(field_name) FROM {tb_name | stb_name} [WHERE clause];
1017 1018
```

1019
**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.
1020

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

1023
**Applicable column types**: Any data types except for timestamp
1024

1025
**Applicable table types**: table, STable
1026 1027


1028
## Time-Series Extensions
1029

1030
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.
1031

1032
### CSUM
1033

1034
```sql
1035
SELECT CSUM(field_name) FROM { tb_name | stb_name } [WHERE clause]
1036 1037
```

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

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

1042
**Applicable data types**: Numeric
1043

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

1046 1047 1048 1049 1050 1051 1052
**Applicable table types**: standard tables and supertables

**More explanations**: 
  
- Arithmetic operation can't be performed on the result of `csum` function
- Can only be used with aggregate functions This function can be used with supertables and standard tables. 
- Must be used with `PARTITION BY tbname` when it's used on a STable to force the result on each single timeline
1053 1054


1055
### DERIVATIVE
1056

1057
```sql
1058
SELECT DERIVATIVE(field_name, time_interval, ignore_negative) FROM tb_name [WHERE clause];
1059 1060
```

1061
**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.
1062

1063
**Return value type**: DOUBLE
1064

1065
**Applicable data types**: Numeric
1066

1067
**Applicable table types**: standard tables and supertables
1068

1069 1070
**More explanation**: 
  
1071
- It can be used together with `PARTITION BY tbname` against a STable.
1072
- It can be used together with a selected column. For example: select \_rowts, DERIVATIVE() from。
1073

1074
### DIFF
1075

1076 1077
```sql
SELECT {DIFF(field_name, ignore_negative) | DIFF(field_name)} FROM tb_name [WHERE clause];
1078 1079
```

1080
**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.
1081

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

1084
**Applicable data types**: Numeric
1085

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

1088 1089 1090 1091
**More explanation**: 

- 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。
1092 1093


1094
### IRATE
1095

1096
```sql
1097
SELECT IRATE(field_name) FROM tb_name WHERE clause;
1098 1099
```

1100
**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.
1101

1102
**Return value type**: DOUBLE
1103

1104
**Applicable data types**: Numeric
1105

1106
**Applicable table types**: standard tables and supertables
1107 1108


1109
### MAVG
1110

1111
```sql
1112
SELECT MAVG(field_name, K) FROM { tb_name | stb_name } [WHERE clause]
1113 1114
```

1115
**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].
1116

1117
**Return value type**: DOUBLE
1118

1119
**Applicable data types**: Numeric
1120

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

1123
**Applicable table types**: standard tables and supertables
1124

1125 1126 1127 1128 1129
**More explanations**: 
  
- Arithmetic operation can't be performed on the result of `MAVG`. 
- 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
1130 1131 1132 1133


### STATECOUNT

1134
```sql
1135 1136 1137
SELECT STATECOUNT(field_name, oper, val) FROM { tb_name | stb_name } [WHERE clause];
```

1138
**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.
1139 1140 1141

**Applicable parameter values**:

S
Sean Ely 已提交
1142
- 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.
1143
- val : Numeric types
1144

1145
**Return value type**: Integer
1146

1147
**Applicable data types**: Numeric
1148

1149
**Applicable nested query**: Outer query only
1150

1151
**Applicable table types**: standard tables and supertables
1152 1153 1154

**More explanations**:

1155 1156 1157
- 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

1158 1159 1160

### STATEDURATION

1161
```sql
1162 1163 1164
SELECT stateDuration(field_name, oper, val, unit) FROM { tb_name | stb_name } [WHERE clause];
```

1165
**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.
1166 1167 1168

**Applicable parameter values**:

S
Sean Ely 已提交
1169
- 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.
1170 1171
- 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.
1172

1173
**Return value type**: Integer
1174

1175
**Applicable data types**: Numeric
1176

1177
**Applicable nested query**: Outer query only
1178

1179
**Applicable table types**: standard tables and supertables
1180 1181 1182

**More explanations**:

1183 1184 1185
- 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

1186

1187
### TWA
1188

1189
```sql
1190
SELECT TWA(field_name) FROM tb_name WHERE clause;
1191 1192
```

1193
**Description**: Time weighted average on a specific column within a time range
1194

1195
**Return value type**: DOUBLE
1196

1197
**Applicable data types**: Numeric
1198

1199
**Applicable table types**: standard tables and supertables
1200

1201
- Must be used together with `PARTITION BY tbname` to force the result into each single timeline.
1202 1203


1204
## System Information Functions
1205

1206
### DATABASE
1207

1208
```sql
1209
SELECT DATABASE();
1210 1211
```

1212 1213
**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()`.

1214

1215
### CLIENT_VERSION
1216

1217
```sql
1218
SELECT CLIENT_VERSION();
1219 1220
```

1221
**Description**: The client version.
1222

1223
### SERVER_VERSION
1224

1225
```sql
1226
SELECT SERVER_VERSION();
1227 1228
```

1229
**Description**: The server version.
1230

1231
### SERVER_STATUS
1232

1233
```sql
S
Sean Ely 已提交
1234
SELECT SERVER_STATUS();
1235 1236
```

1237
**Description**: The server status.