You need to sign in or sign up before continuing.
10-function.md 41.8 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
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 864 865 866 867 868
- `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.
- 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. If `RANGE` is not specified, then the timestamp of the first row that matches the filter condition is treated as timestamp1, the timestamp of the last row that matches the filter condition is treated as timestamp2.
- 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. If `EVERY` parameter is not used, the time windows will be considered as no ending timestamp, i.e. there is only one time window from timestamp1.
- Interpolation is performed based on `FILL` parameter. No interpolation is performed if `FILL` is not used, that means either the original data that matches is returned or nothing is returned.
- `INTERP` can only be used to interpolate in single timeline. So it must be used with `group by tbname` when it's used on a STable. It can't be used with `GROUP BY` when it's used in the inner query of a nested query.
- The result of `INTERP` is not influenced by `ORDER BY TIMESTAMP`, which impacts the output order only..
869

870
### LAST
871

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

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

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

880
**Applicable data types**: Numeric
881

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

884
**More explanation**:
885

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

890

891
### LAST_ROW
892

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

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

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

901
**Applicable data types**: Numeric
902

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

**More explanations**:

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

910
### MAX
911

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

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

920
**Applicable data types**: Numeric
921

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


925
### MIN
926

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

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

935
**Applicable data types**: Numeric
936

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


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

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

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

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

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

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


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

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

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

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

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

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

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

971 972 973 974
**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 已提交
975

976

977
### TAIL
978

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

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

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

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

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

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


994
### TOP
995

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

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

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

1004
**Applicable data types**: Numeric
1005

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

1008
**More explanation**:
1009

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

1014
### UNIQUE
1015

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

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

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

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

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


1029
## Time-Series Extensions
1030

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

1033
### CSUM
1034

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

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

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

1043
**Applicable data types**: Numeric
1044

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

1047 1048 1049 1050 1051 1052 1053
**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
1054 1055


1056
### DERIVATIVE
1057

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

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

1064
**Return value type**: DOUBLE
1065

1066
**Applicable data types**: Numeric
1067

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

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

1075
### DIFF
1076

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

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

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

1085
**Applicable data types**: Numeric
1086

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

1089 1090 1091 1092
**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。
1093 1094


1095
### IRATE
1096

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

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

1103
**Return value type**: DOUBLE
1104

1105
**Applicable data types**: Numeric
1106

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


1110
### MAVG
1111

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

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

1118
**Return value type**: DOUBLE
1119

1120
**Applicable data types**: Numeric
1121

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

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

1126 1127 1128 1129 1130
**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
1131 1132 1133 1134


### STATECOUNT

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

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

**Applicable parameter values**:

1143 1144
- 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
- val : Numeric types
1145

1146
**Return value type**: Integer
1147

1148
**Applicable data types**: Numeric
1149

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

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

**More explanations**:

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

1159 1160 1161

### STATEDURATION

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

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

**Applicable parameter values**:

1170 1171 1172
- 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
- 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.
1173

1174
**Return value type**: Integer
1175

1176
**Applicable data types**: Numeric
1177

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

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

**More explanations**:

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

1187

1188
### TWA
1189

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

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

1196
**Return value type**: DOUBLE
1197

1198
**Applicable data types**: Numeric
1199

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

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


1205
## System Information Functions
1206

1207
### DATABASE
1208

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

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

1215

1216
### CLIENT_VERSION
1217

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

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

1224
### SERVER_VERSION
1225

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

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

1232
### SERVER_STATUS
1233

1234
```sql
1235
SELECT SERVER_VERSION();
1236 1237
```

1238
**Description**: The server status.