Merge branch 'master' into telegraf-v1.33.0

pull/5708/head
Jason Stirnaman 2024-12-20 09:23:50 -06:00 committed by GitHub
commit 6cc07627db
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
237 changed files with 22353 additions and 65382 deletions

View File

@ -10,6 +10,19 @@ aliases:
- /chronograf/v1/about_the_project/release-notes-changelog/
---
## v1.10.6 {date="2024-12-16"}
### Bug Fixes
- Prevent dangerous InfluxQL statements from automatically executing.
- Fix Hosts page loading when there is a large number of connections.
- Support InfluxDB Enterprise when using the Flux Query Builder.
- Support metaqueries for InfluxDB Cloud Serverless environments.
### Dependency updates
- Upgrade Go to 1.22.7.
## v1.10.5 {date="2024-05-31"}
### Dependency updates

View File

@ -593,7 +593,7 @@ _If your project's virtual environment is already running, skip to step 3._
"time"
"text/tabwriter"
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
func Query() error {
@ -659,7 +659,7 @@ _If your project's virtual environment is already running, skip to step 3._
- `io`
- `os`
- `text/tabwriter`
- `github.com/InfluxCommunity/influxdb3-go/influxdb3/v1`
- `github.com/InfluxCommunity/influxdb3-go/v2/influxdb3`
2. Defines a `Query()` function that does the following:

View File

@ -835,7 +835,7 @@ To write data to {{% product-name %}} using Go, use the InfluxDB v3
"fmt"
"log"
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
// Write line protocol data to InfluxDB

View File

@ -21,7 +21,7 @@ list_code_example: |
```go
import (
"context"
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
func Query() error {
@ -94,7 +94,7 @@ to install a recent version of the Go programming language for your system.
In your terminal, enter the following command to download and install the client library:
```sh
go get github.com/InfluxCommunity/influxdb3-go
go get github.com/InfluxCommunity/influxdb3-go/v2
```
- [`influxdb3-go`](https://github.com/InfluxCommunity/influxdb3-go) {{< req text="\* " color="magenta" >}}: Provides the `influxdb3` package and also installs the [Apache `arrow` module](https://arrow.apache.org/docs/python/index.html) for working with Arrow data returned from queries.
@ -139,7 +139,7 @@ import (
"text/tabwriter"
"time"
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
func Query() error {
@ -234,7 +234,7 @@ import (
"text/tabwriter"
"time"
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
func InfluxQL() error {

View File

@ -257,7 +257,7 @@ import (
"os"
"text/tabwriter"
"time"
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
func Query(query string, parameters influxdb3.QueryParameters,

View File

@ -254,7 +254,7 @@ import (
"os"
"text/tabwriter"
"time"
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
func Query(query string, parameters influxdb3.QueryParameters) error {

View File

@ -20,7 +20,7 @@ to write and query data stored in an {{% product-name %}} database.
## Installation
```sh
go get github.com/InfluxCommunity/influxdb3-go
go get github.com/InfluxCommunity/influxdb3-go/v2
```
## Importing the package
@ -31,7 +31,7 @@ Import the package:
```go
import (
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
```
@ -75,7 +75,7 @@ Initializes and returns a `influxdb3.Client` instance with the following:
package main
import (
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
func main() {

View File

@ -369,7 +369,7 @@ Related entries:
A function is an operation that performs a specific task.
Functions take input, operate on that input, and then return output.
For a complete list of available SQL functions, see
[SQL functions](/inflxudb/cloud-dedicated/reference/sql/functions/).
[SQL functions](/influxdb/cloud-dedicated/reference/sql/functions/).
<!-- TODO: Add a link to InfluxQL aggregate functions -->

View File

@ -1,786 +1,13 @@
---
title: InfluxQL reference documentation
list_title: InfluxQL
description: InfluxQL is an SQL-like query language for interacting with data in InfluxDB.
description: >
InfluxQL is an SQL-like query language for interacting with data in InfluxDB.
menu:
influxdb_cloud_dedicated:
parent: Reference
name: InfluxQL reference
identifier: influxql-reference
weight: 102
source: /shared/influxql-v3-reference/_index.md
---
InfluxQL (Influx Query Language) is an SQL-like query language used to interact
with InfluxDB and work with times series data.
{{% warn %}}
#### InfluxQL feature support
InfluxQL is being rearchitected to work with the InfluxDB 3.0 storage engine.
This process is ongoing and some InfluxQL features are still being implemented.
For information about the current implementation status of InfluxQL features,
see [InfluxQL feature support](/influxdb/cloud-dedicated/reference/influxql/feature-support/).
{{% /warn %}}
- [Notation](#notation)
- [Query representation](#query-representation)
- [Characters](#characters)
- [Letters and digits](#letters-and-digits)
- [Identifiers](#identifiers)
- [Keywords](#keywords)
- [Literals](#literals)
- [Queries](#queries)
- [Statements](#statements)
- [Clauses](#clauses)
- [Expressions](#expressions)
- [Comments](#comments)
- [Other](#other)
- [Result set](#result-set)
<!-- To learn more about InfluxQL, browse the following topics:
- [Explore your data with InfluxQL](/influxdb/v2/query-data/influxql/explore-data/)
- [Explore your schema with InfluxQL](/influxdb/v2/query-data/influxql/explore-schema/)
- [Database management](/influxdb/v2/query-data/influxql/manage-database/)
- [Query engine internals](/influxdb/cloud-dedicated/reference/influxql/internals/) -->
## Notation
The syntax is specified using Extended Backus-Naur Form ("EBNF").
EBNF is the same notation used in the [Go programming language specification](https://golang.org/ref/spec).
```go
Production = production_name "=" [ Expression ] "." .
Expression = Alternative { "|" Alternative } .
Alternative = Term { Term } .
Term = production_name | token [ "…" token ] | Group | Option | Repetition .
Group = "(" Expression ")" .
Option = "[" Expression "]" .
Repetition = "{" Expression "}" .
```
Notation operators in order of increasing precedence:
```
| alternation
() grouping
[] option (0 or 1 times)
{} repetition (0 to n times)
```
## Query representation
### Characters
InfluxQL is Unicode text encoded in [UTF-8](http://en.wikipedia.org/wiki/UTF-8).
```
newline = /* the Unicode code point U+000A */ .
unicode_char = /* an arbitrary Unicode code point except newline */ .
```
### Letters and digits
Letters are the set of ASCII letters and the underscore (`_`, U+005F).
Only decimal digits are supported.
```
letter = ascii_letter | "_" .
ascii_letter = "A" … "Z" | "a" … "z" .
digit = "0" … "9" .
```
### Identifiers
Identifiers are tokens that refer to
[database](/influxdb/cloud-dedicated/reference/glossary/#database) names,
[retention policy](/influxdb/cloud-dedicated/reference/glossary/#retention-policy-rp) names,
[measurement](/influxdb/cloud-dedicated/reference/glossary/#measurement) names,
[tag keys](/influxdb/cloud-dedicated/reference/glossary/#tag-key), and
[field keys](/influxdb/cloud-dedicated/reference/glossary/#field-key).
The rules are as follows:
- Double-quoted identifiers can contain any Unicode character except for a new line.
- Double-quoted identifiers can also contain escaped `"` characters (that is, `\"`)
- Double-quoted identifiers can include InfluxQL [keywords](#keywords).
- Unquoted identifiers must start with an upper or lowercase ASCII character or "_".
- Unquoted identifiers may contain only ASCII letters, decimal digits, and "_".
```
identifier = unquoted_identifier | quoted_identifier .
unquoted_identifier = ( letter ) { letter | digit } .
quoted_identifier = `"` unicode_char { unicode_char } `"` .
```
#### Examples
```
cpu
_cpu_stats
"1h"
"anything really"
"1_Crazy-1337.identifier>NAME👍"
```
### Keywords
```
ALL ALTER ANY AS ASC BEGIN
BY CREATE CONTINUOUS DATABASE DATABASES DEFAULT
DELETE DESC DESTINATIONS DIAGNOSTICS DISTINCT DROP
DURATION END EVERY EXPLAIN FIELD FOR
FROM GRANT GRANTS GROUP GROUPS IN
INF INSERT INTO KEY KEYS KILL
LIMIT SHOW MEASUREMENT MEASUREMENTS NAME OFFSET
ON ORDER PASSWORD POLICY POLICIES PRIVILEGES
QUERIES QUERY READ REPLICATION RESAMPLE RETENTION
REVOKE SELECT SERIES SET SHARD SHARDS
SLIMIT SOFFSET STATS SUBSCRIPTION SUBSCRIPTIONS TAG
TO USER USERS VALUES WHERE WITH
WRITE
```
If you use an InfluxQL keyword as an
[identifier](/influxdb/cloud-dedicated/reference/glossary/#identifier),
double-quote the identifier in every query.
The `time` keyword is a special case.
`time` can be a
database name,
[measurement](/influxdb/cloud-dedicated/reference/glossary/#measurement) name,
[retention policy](/influxdb/cloud-dedicated/reference/glossary/#retention-policy-rp) name, and
[user](/influxdb/cloud-dedicated/reference/glossary/#user) name.
In those cases, you don't need to double-quote `time` in queries.
`time` can't be a [field key](/influxdb/cloud-dedicated/reference/glossary/#field-key) or
[tag key](/influxdb/cloud-dedicated/reference/glossary/#tag-key);
InfluxDB rejects writes with `time` as a field key or tag key and returns an error.
<!--
See [Frequently Asked Questions](/influxdb/v2/reference/faq/) for more information.
-->
### Literals
#### Integers
InfluxQL supports decimal integer literals.
Hexadecimal and octal literals aren't currently supported.
```
int_lit = ( "1" … "9" ) { digit } .
```
#### Floats
InfluxQL supports floating-point literals.
Exponents aren't currently supported.
```
float_lit = int_lit "." int_lit .
```
#### Strings
String literals must be surrounded by single quotes.
Strings may contain `'` characters as long as they are escaped (that is, , `\'`)
```
string_lit = `'` { unicode_char } `'` .
```
#### Durations
Duration literals specify a length of time.
An integer literal followed immediately (with no spaces) by one of the duration units listed below is interpreted as a duration literal.
Durations can be specified with mixed units.
##### Duration units
| Units | Meaning |
| ------ | --------------------------------------- |
| ns | nanoseconds (1 billionth of a second) |
| u or µ | microseconds (1 millionth of a second) |
| ms | milliseconds (1 thousandth of a second) |
| s | second |
| m | minute |
| h | hour |
| d | day |
| w | week |
```
duration_lit = int_lit duration_unit .
duration_unit = "ns" | "u" | "µ" | "ms" | "s" | "m" | "h" | "d" | "w" .
```
#### Dates & Times
Unlike other notations used in InfluxQL, the date and time literal format isn't specified by EBNF.
InfluxQL date and time is specified using Go's time parsing format and
[reference date](https://pkg.go.dev/time#pkg-constants) written in the format required by InfluxQL.
The reference date time is:
InfluxQL reference date time: January 2nd, 2006 at 3:04:05 PM
```
time_lit = "2006-01-02 15:04:05.999999" | "2006-01-02" .
```
#### Booleans
```
bool_lit = TRUE | FALSE .
```
#### Regular Expressions
```
regex_lit = "/" { unicode_char } "/" .
```
**Comparators:**
`=~` matches against
`!~` doesn't match against
{{% note %}}
InfluxQL supports using regular expressions when specifying:
- [field keys](/influxdb/cloud-dedicated/reference/glossary/#field-key) and [tag keys](/influxdb/cloud-dedicated/reference/glossary/#tag-key) in the [`SELECT` clause](/influxdb/cloud-dedicated/reference/influxql/select/)
- [measurements](/influxdb/cloud-dedicated/reference/glossary/#measurement) in the [`FROM` clause](/influxdb/cloud-dedicated/reference/influxql/select/#from-clause)
- [tag values](/influxdb/cloud-dedicated/reference/glossary/#tag-value) and
string [field values](/influxdb/cloud-dedicated/reference/glossary/#field-value)
in the [`WHERE` clause](/influxdb/cloud-dedicated/reference/influxql/where/)
- [tag keys](/influxdb/cloud-dedicated/reference/glossary/#tag-key) in the
[`GROUP BY` clause](/influxdb/cloud-dedicated/reference/influxql/group-by/)
Currently, InfluxQL doesn't support using regular expressions to match non-string
field values in the `WHERE` clause, [databases](/influxdb/cloud-dedicated/reference/glossary/#database),
and [retention polices](/influxdb/cloud-dedicated/reference/glossary/#retention-policy-rp).
{{% /note %}}
## Queries
A query is composed of one or more statements separated by a semicolon (`;`).
```
query = statement { ";" statement } .
statement = explain_stmt |
explain_analyze_stmt |
select_stmt |
show_field_keys_stmt |
show_measurements_stmt |
show_retention_policies_stmt |
show_tag_keys_stmt |
show_tag_values_with_key = stmt .
```
<!-- FULL TSM INFLUXQL STATEMENT LIST
```
query = statement { ";" statement } .
statement = explain_stmt |
explain_analyze_stmt |
select_stmt |
show_databases_stmt |
show_field_key_cardinality_stmt |
show_field_keys_stmt |
show_measurement_exact_cardinality_stmt |
show_measurements_stmt |
show_series_exact_cardinality_stmt |
show_series_stmt |
show_tag_key_cardinality_stmt |
show_tag_key_exact_cardinality_stmt |
show_tag_keys_stmt |
show_tag_values_with_key = stmt |
show_tag_values_cardinality_stmt .
``` -->
## Statements
### EXPLAIN
Parses and plans the query, and then prints a summary of estimated costs.
Many SQL engines use the `EXPLAIN` statement to show join order, join algorithms, and predicate and expression pushdown.
Since InfluxQL doesn't support joins, the cost of an InfluxQL query is typically a function of the total series accessed, the number of iterator accesses to a TSM file, and the number of TSM blocks that need to be scanned.
A query plan generated by `EXPLAIN` contains the following elements:
- expression
- auxiliary fields
- number of shards
- number of series
- cached values
- number of files
- number of blocks
- size of blocks
```
explain_stmt = "EXPLAIN" select_stmt .
```
#### Example
```sql
> explain select sum(pointReq) from "_internal"."monitor"."write" group by hostname;
> QUERY PLAN
------
EXPRESSION: sum(pointReq::integer)
NUMBER OF SHARDS: 2
NUMBER OF SERIES: 2
CACHED VALUES: 110
NUMBER OF FILES: 1
NUMBER OF BLOCKS: 1
SIZE OF BLOCKS: 931
```
### EXPLAIN ANALYZE
Executes the specified `SELECT` statement and returns data about the query performance and storage during runtime, visualized as a tree. Use this statement to analyze query performance and storage, including [execution time](#execution-time) and [planning time](#planning-time), and the [iterator type](#iterator-type) and [cursor type](#cursor-type).
For example, if you execute the following statement:
```sql
> explain analyze select mean(usage_steal) from cpu where time >= '2018-02-22T00:00:00Z' and time < '2018-02-22T12:00:00Z'
```
The output is similar to the following:
```sql
EXPLAIN ANALYZE
---------------
.
└── select
├── execution_time: 2.25823ms
├── planning_time: 18.381616ms
├── total_time: 20.639846ms
└── field_iterators
├── labels
│ └── statement: SELECT mean(usage_steal::float) FROM telegraf."default".cpu
└── expression
├── labels
│ └── expr: mean(usage_steal::float)
└── create_iterator
├── labels
│ ├── measurement: cpu
│ └── shard_id: 608
├── cursors_ref: 779
├── cursors_aux: 0
├── cursors_cond: 0
├── float_blocks_decoded: 431
├── float_blocks_size_bytes: 1003552
├── integer_blocks_decoded: 0
├── integer_blocks_size_bytes: 0
├── unsigned_blocks_decoded: 0
├── unsigned_blocks_size_bytes: 0
├── string_blocks_decoded: 0
├── string_blocks_size_bytes: 0
├── boolean_blocks_decoded: 0
├── boolean_blocks_size_bytes: 0
└── planning_time: 14.805277ms```
```
{{% note %}}
`EXPLAIN ANALYZE` ignores query output, so the cost of serialization to JSON or
CSV isn't accounted for.
{{% /note %}}
##### execution_time
Shows the amount of time the query took to execute, including reading the time series data, performing operations as data flows through iterators, and draining processed data from iterators. Execution time doesn't include the time taken to serialize the output into JSON or other formats.
##### planning_time
Shows the amount of time the query took to plan.
Planning a query in InfluxDB requires a number of steps. Depending on the complexity of the query, planning can require more work and consume more CPU and memory resources than executing the query. For example, the number of series keys required to execute a query affects how quickly the query is planned and how much memory the planning requires.
First, InfluxDB determines the effective time range of the query and selects the shards to access.
Next, for each shard and each measurement, InfluxDB performs the following steps:
1. Select matching series keys from the index, filtered by tag predicates in the `WHERE` clause.
2. Group filtered series keys into tag sets based on the `GROUP BY` dimensions.
3. Enumerate each tag set and create a cursor and iterator for each series key.
4. Merge iterators and return the merged result to the query executor.
##### iterator type
`EXPLAIN ANALYZE` supports the following iterator types:
- `create_iterator` node represents work done by the local influxd instance──a complex composition of nested iterators combined and merged to produce the final query output.
- (InfluxDB Enterprise only) `remote_iterator` node represents work done on remote machines.
For more information about iterators, see [Understanding iterators](#understanding-iterators).
##### cursor type
`EXPLAIN ANALYZE` distinguishes 3 cursor types. While the cursor types have the same data structures and equal CPU and I/O costs, each cursor type is constructed for a different reason and separated in the final output. Consider the following cursor types when tuning a statement:
- cursor_ref: Reference cursor created for `SELECT` projections that include a function, such as `last()` or `mean()`.
- cursor_aux: Auxiliary cursor created for simple expression projections (not selectors or an aggregation). For example, `SELECT foo FROM m` or `SELECT foo+bar FROM m`, where `foo` and `bar` are fields.
- cursor_cond: Condition cursor created for fields referenced in a `WHERE` clause.
For more information about cursors, see [Understanding cursors](#understanding-cursors).
##### block types
`EXPLAIN ANALYZE` separates storage block types, and reports the total number of
blocks decoded and their size (in bytes) on disk. The following block types are supported:
| Type | Description |
| :--------- | :------------------------------------ |
| `float` | 64-bit IEEE-754 floating-point number |
| `integer` | 64-bit signed integer |
| `unsigned` | 64-bit unsigned integer |
| `boolean` | 1-bit, LSB encoded |
| `string` | UTF-8 string |
### SELECT
```
select_stmt = "SELECT" fields from_clause [ where_clause ]
[ group_by_clause ] [ order_by_clause ] [ limit_clause ]
[ offset_clause ] [ slimit_clause ] [ soffset_clause ] [ timezone_clause ] .
```
#### Example
Select from measurements grouped by the day with a timezone
```sql
SELECT mean("value") FROM "cpu" GROUP BY region, time(1d) fill(0) tz('America/Chicago')
```
<!-- ### SHOW CARDINALITY
Refers to the group of commands used to estimate or count exactly the cardinality of measurements, series, tag keys, tag key values, and field keys.
The SHOW CARDINALITY commands are available in two variations: _estimated_ and _exact_. Estimated values are calculated using sketches and are a safe default for all cardinality sizes. Exact values are counts directly from TSM (Time-Structured Merge Tree) data, but are expensive to run for high cardinality data. Unless required, use the estimated variety.
Filtering by `time` is only supported when Time Series Index (TSI) is enabled on a database.
See the specific SHOW CARDINALITY commands for details:
- [SHOW FIELD KEY CARDINALITY](#show-field-key-cardinality)
- [SHOW SERIES CARDINALITY](#show-series-cardinality)
- [SHOW TAG KEY CARDINALITY](#show-tag-key-cardinality)
- [SHOW TAG VALUES CARDINALITY](#show-tag-values-cardinality) -->
<!-- ### SHOW DATABASES
```
show_databases_stmt = "SHOW DATABASES" .
```
#### Example
```sql
-- show all databases
SHOW DATABASES
``` -->
<!-- ### SHOW FIELD KEY CARDINALITY
Estimates or counts exactly the cardinality of the field key set for the current
database unless a database is specified using the `ON <database>` option.
{{% note %}}
**Note:** `ON <database>`, `FROM <sources>`, `WITH KEY = <key>`,
`WHERE <condition>`, `GROUP BY <dimensions>`, and `LIMIT/OFFSET` clauses are optional.
When using these query clauses, the query falls back to an exact count.
{{% /note %}}
```sql
show_field_key_cardinality_stmt = "SHOW FIELD KEY CARDINALITY" [ on_clause ] [ from_clause ] [ where_clause ] [ group_by_clause ] [ limit_clause ] [ offset_clause ]
show_field_key_exact_cardinality_stmt = "SHOW FIELD KEY EXACT CARDINALITY" [ on_clause ] [ from_clause ] [ where_clause ] [ group_by_clause ] [ limit_clause ] [ offset_clause ]
```
#### Examples
```sql
-- show estimated cardinality of the field key set of current database
SHOW FIELD KEY CARDINALITY
-- show exact cardinality on field key set of specified database
SHOW FIELD KEY EXACT CARDINALITY ON mydb
``` -->
### SHOW FIELD KEYS
```
show_field_keys_stmt = "SHOW FIELD KEYS" [on_clause] [ from_clause ] .
```
#### Examples
```sql
-- show field keys and field value data types from all measurements
SHOW FIELD KEYS
-- show field keys and field value data types from specified measurement
SHOW FIELD KEYS FROM "cpu"
```
### SHOW MEASUREMENTS
```
show_measurements_stmt = "SHOW MEASUREMENTS" [on_clause] [ with_measurement_clause ] [ where_clause ] [ limit_clause ] [ offset_clause ] .
```
#### Examples
```sql
-- show all measurements
SHOW MEASUREMENTS
-- show measurements where region tag = 'uswest' AND host tag = 'serverA'
SHOW MEASUREMENTS WHERE "region" = 'uswest' AND "host" = 'serverA'
-- show measurements that start with 'h2o'
SHOW MEASUREMENTS WITH MEASUREMENT =~ /h2o.*/
```
<!-- ### SHOW SERIES
```
show_series_stmt = "SHOW SERIES" [on_clause] [ from_clause ] [ where_clause ] [ limit_clause ] [ offset_clause ] .
```
#### Example
```sql
SHOW SERIES FROM "telegraf"."autogen"."cpu" WHERE cpu = 'cpu8'
``` -->
<!-- ### SHOW SERIES EXACT CARDINALITY
Estimates or counts exactly the cardinality of the series for the current
database unless a database is specified using the `ON database` option.
#### Example
SHOW SERIES EXACT CARDINALITY" [ on_clause ] [ from_clause ]
[ where_clause ] [ group_by_clause ] [ limit_clause ] [ offset_clause ]
```sql
SHOW SERIES EXACT CARDINALITY ON mydb
```
{{% note %}}
**NOTE:** `ON <database>`, `FROM <sources>`, `WITH KEY = <key>`,
`WHERE <condition>`, `GROUP BY <dimensions>`, and `LIMIT/OFFSET` clauses are optional.
When using these query clauses, the query falls back to an exact count.
Filtering by `time` is not supported in the `WHERE` clause.
{{% /note %}} -->
<!-- ### SHOW TAG KEY CARDINALITY
Estimates or counts exactly the cardinality of tag key set on the current
database unless a database is specified using the `ON <database>` option.
{{% note %}}
`ON <database>`, `FROM <sources>`, `WITH KEY = <key>`, `WHERE <condition>`,
`GROUP BY <dimensions>`, and `LIMIT/OFFSET` clauses are optional.
When using these query clauses, the query falls back to an exact count.
Filtering by `time` is only supported when TSI (Time Series Index) is enabled
and `time` is not supported in the `WHERE` clause.
{{% /note %}}
```
show_tag_key_cardinality_stmt = "SHOW TAG KEY CARDINALITY" [ on_clause ] [ from_clause ] [ where_clause ] [ group_by_clause ] [ limit_clause ] [ offset_clause ]
show_tag_key_exact_cardinality_stmt = "SHOW TAG KEY EXACT CARDINALITY" [ on_clause ] [ from_clause ] [ where_clause ] [ group_by_clause ] [ limit_clause ] [ offset_clause ]
```
#### Examples
```sql
-- show estimated tag key cardinality
SHOW TAG KEY CARDINALITY
-- show exact tag key cardinality
SHOW TAG KEY EXACT CARDINALITY
``` -->
### SHOW TAG KEYS
```
show_tag_keys_stmt = "SHOW TAG KEYS" [on_clause] [ from_clause ] [ where_clause ]
[ limit_clause ] [ offset_clause ] .
```
#### Examples
```sql
-- show all tag keys
SHOW TAG KEYS
-- show all tag keys from the cpu measurement
SHOW TAG KEYS FROM "cpu"
-- show all tag keys from the cpu measurement where the region key = 'uswest'
SHOW TAG KEYS FROM "cpu" WHERE "region" = 'uswest'
-- show all tag keys where the host key = 'serverA'
SHOW TAG KEYS WHERE "host" = 'serverA'
```
### SHOW TAG VALUES
```
show_tag_values_stmt = "SHOW TAG VALUES" [on_clause] [ from_clause ] with_tag_clause [ where_clause ]
[ limit_clause ] [ offset_clause ] .
```
#### Examples
```sql
-- show all tag values across all measurements for the region tag
SHOW TAG VALUES WITH KEY = "region"
-- show tag values from the cpu measurement for the region tag
SHOW TAG VALUES FROM "cpu" WITH KEY = "region"
-- show tag values across all measurements for all tag keys that do not include the letter c
SHOW TAG VALUES WITH KEY !~ /.*c.*/
-- show tag values from the cpu measurement for region & host tag keys where service = 'redis'
SHOW TAG VALUES FROM "cpu" WITH KEY IN ("region", "host") WHERE "service" = 'redis'
```
<!-- ### SHOW TAG VALUES CARDINALITY
Estimates or counts exactly the cardinality of tag key values for the specified
tag key on the current database unless a database is specified using the
`ON database` option.
{{% note %}}
**Note:** `ON <database>`, `FROM <sources>`, `WITH KEY = <key>`,
`WHERE <condition>`, `GROUP BY <dimensions>`, and `LIMIT/OFFSET` clauses are optional.
When using these query clauses, the query falls back to an exact count.
Filtering by `time` is only supported when TSI (Time Series Index) is enabled.
{{% /note %}}
```
show_tag_values_cardinality_stmt = "SHOW TAG VALUES CARDINALITY" [ on_clause ] [ from_clause ] [ where_clause ] [ group_by_clause ] [ limit_clause ] [ offset_clause ] with_key_clause
show_tag_values_exact_cardinality_stmt = "SHOW TAG VALUES EXACT CARDINALITY" [ on_clause ] [ from_clause ] [ where_clause ] [ group_by_clause ] [ limit_clause ] [ offset_clause ] with_key_clause
```
#### Examples
```sql
-- show estimated tag key values cardinality for a specified tag key
SHOW TAG VALUES CARDINALITY WITH KEY = "myTagKey"
-- show estimated tag key values cardinality for a specified tag key
SHOW TAG VALUES CARDINALITY WITH KEY = "myTagKey"
-- show exact tag key values cardinality for a specified tag key
SHOW TAG VALUES EXACT CARDINALITY WITH KEY = "myTagKey"
-- show exact tag key values cardinality for a specified tag key
SHOW TAG VALUES EXACT CARDINALITY WITH KEY = "myTagKey"
``` -->
## Clauses
```
from_clause = "FROM" measurements .
group_by_clause = "GROUP BY" dimensions fill(fill_option).
limit_clause = "LIMIT" int_lit .
offset_clause = "OFFSET" int_lit .
slimit_clause = "SLIMIT" int_lit .
soffset_clause = "SOFFSET" int_lit .
timezone_clause = tz(string_lit) .
on_clause = "ON" db_name .
order_by_clause = "ORDER BY" sort_fields .
where_clause = "WHERE" expr .
with_measurement_clause = "WITH MEASUREMENT" ( "=" measurement | "=~" regex_lit ) .
with_tag_clause = "WITH KEY" ( "=" tag_key | "!=" tag_key | "=~" regex_lit | "IN (" tag_keys ")" ) .
```
## Expressions
```
binary_op = "+" | "-" | "*" | "/" | "%" | "&" | "|" | "^" | "AND" |
"OR" | "=" | "!=" | "<>" | "<" | "<=" | ">" | ">=" .
expr = unary_expr { binary_op unary_expr } .
unary_expr = "(" expr ")" | var_ref | time_lit | string_lit | int_lit |
float_lit | bool_lit | duration_lit | regex_lit .
```
## Default time range
The default time range is the Unix epoch (`1970-01-01T00:00:00Z`) to _now_.
## Comments
Use comments with InfluxQL statements to describe your queries.
- A single line comment begins with two hyphens (`--`) and ends where InfluxDB detects a line break.
This comment type cannot span several lines.
- A multi-line comment begins with `/*` and ends with `*/`. This comment type can span several lines.
Multi-line comments do not support nested multi-line comments.
## Other
```
alias = "AS" identifier .
back_ref = ( policy_name ".:MEASUREMENT" ) |
( db_name "." [ policy_name ] ".:MEASUREMENT" ) .
db_name = identifier .
dimension = expr .
dimensions = dimension { "," dimension } .
field_key = identifier .
field = expr [ alias ] .
fields = field { "," field } .
fill_option = "null" | "none" | "previous" | int_lit | float_lit | "linear" .
host = string_lit .
measurement = measurement_name |
( policy_name "." measurement_name ) |
( db_name "." [ policy_name ] "." measurement_name ) .
measurements = measurement { "," measurement } .
measurement_name = identifier | regex_lit .
policy_name = identifier .
retention_policy = identifier .
retention_policy_name = "NAME" identifier .
series_id = int_lit .
sort_field = field_key [ ASC | DESC ] .
sort_fields = sort_field { "," sort_field } .
tag_key = identifier .
tag_keys = tag_key { "," tag_key } .
var_ref = measurement .
```

View File

@ -9,163 +9,6 @@ menu:
influxdb_cloud_dedicated:
parent: influxql-reference
weight: 220
source: /shared/influxql-v3-reference/feature-support.md
---
InfluxQL is being rearchitected to work with the InfluxDB 3.0 storage engine.
This process is ongoing and some InfluxQL features are still being implemented.
This page provides information about the current implementation status of
InfluxQL features.
- [In-progress features](#in-progress-features)
- [SLIMIT clause](#slimit-clause)
- [SOFFSET clause](#soffset-clause)
- [Metaqueries](#metaqueries)
- [Function support](#function-support)
- [Aggregate functions](#aggregate-functions)
- [Selector functions](#selector-functions)
- [Transformations](#transformations)
- [Technical and predictive analysis](#technical-and-predictive-analysis)
## In-progress features
### SLIMIT clause
InfluxQL in {{< product-name >}} does not currently support the `SLIMIT` clause,
which limits the number of [series](/influxdb/cloud-dedicated/reference/glossary/#series)
returned in query results.
<!-- **Tracking issue**: [influxdb_iox#6940](https://github.com/influxdata/influxdb_iox/issues/6940) -->
### SOFFSET clause
InfluxQL in {{< product-name >}} does not currently support the `SOFFSET` clause,
which specifies the number of [series](/influxdb/cloud-dedicated/reference/glossary/#series)
to skip before returning results.
<!-- **Tracking issue**: [influxdb_iox#6940](https://github.com/influxdata/influxdb_iox/issues/6940) -->
### Metaqueries
InfluxQL metaqueries return information about the schema of time series data
stored in InfluxDB.
The following table provides information about what metaqueries are available in
{{< product-name >}}:
| Metaquery | Supported |
| :------------------------------------------------------------ | :----------------------: |
| <span style="opacity: .5;">SHOW DATABASES</span> | |
| **SHOW RETENTION POLICIES** | **{{< icon "check" >}}** |
| **SHOW MEASUREMENTS** | **{{< icon "check" >}}** |
| <span style="opacity: .5;">SHOW SERIES</span> | |
| <span style="opacity: .5;">SHOW SERIES CARDINALITY</span> | |
| **SHOW TAG KEYS** | **{{< icon "check" >}}** |
| <span style="opacity: .5;">SHOW TAG KEY CARDINALITY</span> | |
| **SHOW TAG VALUES** | **{{< icon "check" >}}** |
| <span style="opacity: .5;">SHOW TAG VALUES CARDINALITY</span> | |
| **SHOW FIELD KEYS** | **{{< icon "check" >}}** |
| <span style="opacity: .5;">SHOW FIELD KEYS CARDINALITY</span> | |
{{% note %}}
#### Cardinality metaqueries
With the InfluxDB 3.0 storage engine, series cardinality is no longer a limiting
factor for database performance.
Cardinality-related metaqueries will likely not be supported with the InfluxDB 3.0
storage engine.
{{% /note %}}
## Function support
### Aggregate functions
| Function | Supported |
| :---------------------------------------------------------------------------------------- | :----------------------: |
| [COUNT()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#count) | **{{< icon "check" >}}** |
| [DISTINCT()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#distinct) | **{{< icon "check" >}}** |
| <span style="opacity: .5;">INTEGRAL()</span> | |
| [MEAN()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#mean) | **{{< icon "check" >}}** |
| [MEDIAN()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#median) | **{{< icon "check" >}}** |
| [MODE()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#mode) | **{{< icon "check" >}}** |
| [SPREAD()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#spread) | **{{< icon "check" >}}** |
| [STDDEV()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#stddev) | **{{< icon "check" >}}** |
| [SUM()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#sum) | **{{< icon "check" >}}** |
<!--
INTEGRAL [influxdb_iox#6937](https://github.com/influxdata/influxdb_iox/issues/6937)
-->
### Selector functions
| Function | Supported |
| :------------------------------------------------------------------------------------------- | :----------------------: |
| [BOTTOM()](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/#bottom) | **{{< icon "check" >}}** |
| [FIRST()](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/#first) | **{{< icon "check" >}}** |
| [LAST()](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/#last) | **{{< icon "check" >}}** |
| [MAX()](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/#max) | **{{< icon "check" >}}** |
| [MIN()](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/#min) | **{{< icon "check" >}}** |
| [PERCENTILE()](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/#percentile) | **{{< icon "check" >}}** |
| <span style="opacity: .5;">SAMPLE()</span> | |
| [TOP()](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/#top) | **{{< icon "check" >}}** |
<!-- SAMPLE() [influxdb_iox#6935](https://github.com/influxdata/influxdb_iox/issues/6935) -->
### Transformations
| Function | Supported |
| :--------------------------------------------------------------------------------------------------------------------------- | :----------------------: |
| [ABS()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#abs) | **{{< icon "check" >}}** |
| [ACOS()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#acos) | **{{< icon "check" >}}** |
| [ASIN()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#asin) | **{{< icon "check" >}}** |
| [ATAN()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#atan) | **{{< icon "check" >}}** |
| [ATAN2()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#atan2) | **{{< icon "check" >}}** |
| [CEIL()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#ceil) | **{{< icon "check" >}}** |
| [COS()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#cos) | **{{< icon "check" >}}** |
| [CUMULATIVE_SUM()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#cumulative_sum) | **{{< icon "check" >}}** |
| [DERIVATIVE()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#derivative) | **{{< icon "check" >}}** |
| [DIFFERENCE()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#difference) | **{{< icon "check" >}}** |
| [ELAPSED()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#elapsed) | **{{< icon "check" >}}** |
| [EXP()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#exp) | **{{< icon "check" >}}** |
| [FLOOR()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#floor) | **{{< icon "check" >}}** |
| [LN()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#ln) | **{{< icon "check" >}}** |
| [LOG()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#log) | **{{< icon "check" >}}** |
| [LOG2()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#log2) | **{{< icon "check" >}}** |
| [LOG10()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#log10) | **{{< icon "check" >}}** |
| [MOVING_AVERAGE()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#moving_average) | **{{< icon "check" >}}** |
| [NON_NEGATIVE_DERIVATIVE()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#non_negative_derivative) | **{{< icon "check" >}}** |
| [NON_NEGATIVE_DIFFERENCE()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#non_negative_difference) | **{{< icon "check" >}}** |
| [POW()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#pow) | **{{< icon "check" >}}** |
| [ROUND()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#round) | **{{< icon "check" >}}** |
| [SIN()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#sin) | **{{< icon "check" >}}** |
| [SQRT()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#sqrt) | **{{< icon "check" >}}** |
| [TAN()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#tan) | **{{< icon "check" >}}** |
### Technical and predictive analysis
| Function | Supported |
| :-------------------------------------------------------------------- | :-------: |
| <span style="opacity: .5;">CHANDE_MOMENTUM_OSCILLATOR()</span> | |
| <span style="opacity: .5;">DOUBLE_EXPONENTIAL_MOVING_AVERAGE()</span> | |
| <span style="opacity: .5;">EXPONENTIAL_MOVING_AVERAGE()</span> | |
| <span style="opacity: .5;">HOLT_WINTERS()</span> | |
| <span style="opacity: .5;">HOLT_WINTERS_WITH_FIT()</span> | |
| <span style="opacity: .5;">KAUFMANS_EFFICIENCY_RATIO()</span> | |
| <span style="opacity: .5;">KAUFMANS_ADAPTIVE_MOVING_AVERAGE()</span> | |
| <span style="opacity: .5;">RELATIVE_STRENGTH_INDEX()</span> | |
| <span style="opacity: .5;">TRIPLE_EXPONENTIAL_MOVING_AVERAGE()</span> | |
| <span style="opacity: .5;">TRIPLE_EXPONENTIAL_DERIVATIVE()</span> | |
<!-- All technical analysis functions [influxdb_iox#6939](https://github.com/influxdata/influxdb_iox/issues/6939) -->
### Date and time functions
| Function | Supported |
| :------------------------------------------------------------------------------- | :----------------------: |
| [now()](/influxdb/cloud-dedicated/reference/influxql/functions/date-time/#now) | **{{< icon "check" >}}** |
| [time()](/influxdb/cloud-dedicated/reference/influxql/functions/date-time/#time) | **{{< icon "check" >}}** |
| [tz()](/influxdb/cloud-dedicated/reference/influxql/functions/date-time/#tz) | **{{< icon "check" >}}** |
### Miscellaneous functions
| Function | Supported |
| :-------------------------------------------------------------------------- | :----------------------: |
| [fill()](/influxdb/cloud-dedicated/reference/influxql/functions/misc/#fill) | **{{< icon "check" >}}** |

View File

@ -8,79 +8,6 @@ menu:
parent: influxql-reference
identifier: influxql-functions
weight: 208
source: /shared/influxql-v3-reference/functions/_index.md
---
Use InfluxQL functions to aggregate, select, transform, analyze, and predict data.
{{% note %}}
#### Missing InfluxQL functions
Some InfluxQL functions are in the process of being rearchitected to work with
the InfluxDB 3.0 storage engine. If a function you need is not here, check the
[InfluxQL feature support page](/influxdb/cloud-dedicated/reference/influxql/feature-support/#function-support)
for more information.
{{% /note %}}
## InfluxQL functions (by type)
- [Aggregates](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/)
- [COUNT()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#count)
- [DISTINCT()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#distinct)
- [MEAN()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#mean)
- [MEDIAN()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#median)
- [STDDEV()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#stddev)
- [SUM()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#sum)
<!-- - [INTEGRAL()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#integral) -->
<!-- - [MODE()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#mode) -->
<!-- - [SPREAD()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#spread) -->
- [Selectors](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/)
- [BOTTOM()](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/#bottom)
- [FIRST()](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/#first)
- [LAST()](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/#last)
- [MAX()](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/#max)
- [MIN()](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/#min)
- [PERCENTILE()](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/#percentile)
- [TOP()](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/#top)
<!-- - [SAMPLE()](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/#sample) -->
- [Transformations](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/)
- [ABS()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#abs)
- [ACOS()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#acos)
- [ASIN()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#asin)
- [ATAN()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#atan)
- [ATAN2()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#atan2)
- [CEIL()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#ceil)
- [COS()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#cos)
- [CUMULATIVE_SUM()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#cumulative_sum)
- [DERIVATIVE()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#derivative)
- [DIFFERENCE()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#difference)
- [EXP()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#exp)
- [FLOOR()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#floor)
- [HISTOGRAM()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#histogram)
- [LN()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#ln)
- [LOG()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#log)
- [LOG2()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#log2)
- [LOG10()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#log10)
- [MOVING_AVERAGE()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#moving_average)
- [NON_NEGATIVE_DERIVATIVE()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#non_negative_derivative)
- [NON_NEGATIVE_DIFFERENCE()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#non_negative_difference)
- [POW()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#pow)
- [ROUND()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#round)
- [SIN()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#sin)
- [SQRT()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#sqrt)
- [TAN()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#tan)
<!-- - [ELAPSED()](/influxdb/cloud-dedicated/reference/influxql/functions/transformations/#elapsed) -->
- [Date and time](/influxdb/cloud-dedicated/reference/influxql/functions/date-time/)
- [now()](/influxdb/cloud-dedicated/reference/influxql/functions/date-time/#now)
- [time()](/influxdb/cloud-dedicated/reference/influxql/functions/date-time/#time)
- [Miscellaneous](/influxdb/cloud-dedicated/reference/influxql/functions/misc/)
- [fill()](/influxdb/cloud-dedicated/reference/influxql/functions/misc/#fill)
<!-- - [Technical analysis](/influxdb/cloud-dedicated/reference/influxql/functions/technical-analysis/) -->
<!-- - (Predictive analysis) [HOLT_WINTERS()](/influxdb/cloud-dedicated/reference/influxql/functions/technical-analysis/#holt_winters) -->
<!-- - [CHANDE_MOMENTUM_OSCILLATOR()](/influxdb/cloud-dedicated/reference/influxql/functions/technical-analysis/#chande_momentum_oscillator) -->
<!-- - [DOUBLE_EXPONENTIAL_MOVING_AVERAGE()](/influxdb/cloud-dedicated/reference/influxql/functions/technical-analysis/#double_exponential_moving_average) -->
<!-- - [EXPONENTIAL_MOVING_AVERAGE()](/influxdb/cloud-dedicated/reference/influxql/functions/technical-analysis/#exponential_moving_average) -->
<!-- - [KAUFMANS_EFFICIENCY_RATIO()](/influxdb/cloud-dedicated/reference/influxql/functions/technical-analysis/#kaufmans_adaptive_moving_average) -->
<!-- - [KAUFMANS_ADAPTIVE_MOVING_AVERAGE()](/influxdb/cloud-dedicated/reference/influxql/functions/technical-analysis/#kaufmans_adaptive_moving_average) -->
<!-- - [RELATIVE_STRENGTH_INDEX()](/influxdb/cloud-dedicated/reference/influxql/functions/technical-analysis/#relative_strength_index) -->
<!-- - [TRIPLE_EXPONENTIAL_MOVING_AVERAGE()](/influxdb/cloud-dedicated/reference/influxql/functions/technical-analysis/#triple_exponential_moving_average) -->
<!-- - [TRIPLE_EXPONENTIAL_DERIVATIVE()](/influxdb/cloud-dedicated/reference/influxql/functions/technical-analysis/#triple_exponential_derivative) -->

View File

@ -10,922 +10,6 @@ menu:
weight: 205
related:
- /influxdb/cloud-dedicated/query-data/influxql/aggregate-select/
source: /shared/influxql-v3-reference/functions/aggregates.md
---
Use aggregate functions to assess, aggregate, and return values in your data.
Aggregate functions return one row containing the aggregate values from each InfluxQL group.
_Examples use the sample data set provided in the
[Get started with InfluxDB tutorial](/influxdb/cloud-dedicated/get-started/write/#construct-line-protocol)._
- [COUNT()](#count)
- [DISTINCT()](#distinct)
- [MEAN()](#mean)
- [MEDIAN()](#median)
- [MODE()](#mode)
- [SPREAD()](#spread)
- [STDDEV()](#stddev)
- [SUM()](#sum)
<!-- When implemented, place back in alphabetical order -->
<!-- - [INTEGRAL()](#integral) -->
{{% note %}}
#### Missing InfluxQL functions
Some InfluxQL functions are in the process of being rearchitected to work with
the InfluxDB 3.0 storage engine. If a function you need is not here, check the
[InfluxQL feature support page](/influxdb/cloud-dedicated/reference/influxql/feature-support/#function-support)
for more information.
{{% /note %}}
## COUNT()
Returns the number of non-null [field values](/influxdb/cloud-dedicated/reference/glossary/#field-value).
```sql
COUNT(field_expression)
```
#### Arguments
- **field_expression**: Expression to identify one or more fields to operate on.
Can be a [field key](/influxdb/cloud-dedicated/reference/glossary/#field-key),
constant, regular expression, or wildcard (`*`).
Supports all field types.
#### Examples
{{< expand-wrapper >}}
{{% expand "Count the number of non-null values in a field" %}}
```sql
SELECT COUNT(temp) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | count |
| :------------------- | ----: |
| 1970-01-01T00:00:00Z | 26 |
{{% /expand %}}
{{% expand "Count the number of non-null values in each field" %}}
```sql
SELECT COUNT(*) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | count_co | count_hum | count_temp |
| :------------------- | -------: | --------: | ---------: |
| 1970-01-01T00:00:00Z | 26 | 26 | 26 |
{{% /expand %}}
{{% expand "Count the number of non-null values in fields where the field key matches a regular expression" %}}
```sql
SELECT COUNT(/^[th]/) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | count_hum | count_temp |
| :------------------- | --------: | ---------: |
| 1970-01-01T00:00:00Z | 26 | 26 |
{{% /expand %}}
{{% expand "Count distinct values for a field" %}}
InfluxQL supports nesting [`DISTINCT()`](#distinct) in `COUNT()`.
```sql
SELECT COUNT(DISTINCT(co)) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | count |
| :------------------- | ----: |
| 1970-01-01T00:00:00Z | 12 |
{{% /expand %}}
{{% expand "Count the number of non-null field values within time windows (grouped by time)" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
COUNT(temp)
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY time(6h)
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | count |
| :------------------- | ----: |
| 2022-01-01T06:00:00Z | 4 |
| 2022-01-01T12:00:00Z | 6 |
| 2022-01-01T18:00:00Z | 3 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## DISTINCT()
Returns the list of unique [field values](/influxdb/cloud-dedicated/reference/glossary/#field-value).
```sql
DISTINCT(field_key)
```
#### Arguments
- **field_key**: Field key to return distinct values from.
Supports all field types.
#### Notable behaviors
- InfluxQL supports nesting `DISTINCT()` with [`COUNT()`](#count-distinct-values-for-a-field).
#### Examples
{{< expand-wrapper >}}
{{% expand "List the distinct field values" %}}
```sql
SELECT DISTINCT(co) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | distinct |
| :------------------- | -------: |
| 1970-01-01T00:00:00Z | 0 |
| 1970-01-01T00:00:00Z | 1 |
| 1970-01-01T00:00:00Z | 3 |
| 1970-01-01T00:00:00Z | 4 |
| 1970-01-01T00:00:00Z | 7 |
| 1970-01-01T00:00:00Z | 5 |
| 1970-01-01T00:00:00Z | 9 |
| 1970-01-01T00:00:00Z | 18 |
| 1970-01-01T00:00:00Z | 14 |
| 1970-01-01T00:00:00Z | 22 |
| 1970-01-01T00:00:00Z | 17 |
| 1970-01-01T00:00:00Z | 26 |
{{% /expand %}}
{{< /expand-wrapper >}}
<!-- ## INTEGRAL()
Returns the area under the curve for queried [field values](/influxdb/cloud-dedicated/reference/glossary/#field-value)
and converts those results into the summed area per **unit** of time.
{{% note %}}
`INTEGRAL()` does not support [`fill()`](/influxdb/cloud-dedicated/query-data/influxql/explore-data/group-by/#group-by-time-intervals-and-fill).
`INTEGRAL()` supports int64 and float64 field value [data types](/influxdb/cloud-dedicated/reference/glossary/#data-type).
{{% /note %}}
```sql
INTEGRAL(field_expression[, unit])
```
#### Arguments
- **field_expression**: Expression to identify one or more fields to operate on.
Can be a [field key](/influxdb/cloud-dedicated/reference/glossary/#field-key),
constant, regular expression, or wildcard (`*`).
- **unit**: Unit of time to use when calculating the integral.
Default is `1s` (one second).
#### Examples
{{< expand-wrapper >}}
{{% expand "Calculate the integral for a field" %}}
```sql
SELECT
INTEGRAL(co)
FROM home
WHERE room = 'Kitchen'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | integral |
| :------------------- | -------: |
| 1970-01-01T00:00:00Z | 266400 |
{{% /expand %}}
{{% expand "Calculate the integral for a field and specify the unit option" %}}
```sql
SELECT
INTEGRAL(co, 1h)
FROM home
WHERE room = 'Kitchen'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | integral |
| :------------------- | -------: |
| 1970-01-01T00:00:00Z | 74 |
{{% /expand %}}
{{% expand "Calculate the integral for _each_ field and specify the unit option" %}}
Return the area under the curve (in minutes) for the field values associated
with each field key that stores numeric values in the `h2o_feet` measurement.
The `h2o_feet` measurement has on numeric field: `water_level`.
```sql
SELECT
INTEGRAL(*, 1h)
FROM home
WHERE room = 'Kitchen'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | integral_co | integral_hum | integral_temp |
| :------------------- | ----------: | -----------: | ------------: |
| 1970-01-01T00:00:00Z | 74 | 435 | 272.25 |
{{% /expand %}}
{{% expand "Calculate the integral for the field keys that matches a regular expression" %}}
```sql
SELECT
INTEGRAL(/^[th]/, 1h)
FROM home
WHERE room = 'Kitchen'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | integral_hum | integral_temp |
| :------------------- | -----------: | ------------: |
| 1970-01-01T00:00:00Z | 435 | 272.25 |
{{% /expand %}}
{{% expand "Calculate the integral for a field grouping by time" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
INTEGRAL(co, 1h)
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY time(6h)
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | integral |
| :------------------- | -------: |
| 2022-01-01T06:00:00Z | 0 |
| 2022-01-01T12:00:00Z | 30 |
| 2022-01-01T18:00:00Z | 44 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}} -->
## MEAN()
Returns the arithmetic mean (average) of [field values](/influxdb/cloud-dedicated/reference/glossary/#field-value).
```sql
MEAN(field_expression)
```
#### Arguments
- **field_expression**: Expression to identify one or more fields to operate on.
Can be a [field key](/influxdb/cloud-dedicated/reference/glossary/#field-key),
constant, regular expression, or wildcard (`*`).
Supports **numeric fields**.
#### Examples
{{< expand-wrapper >}}
{{% expand "Calculate the mean value of a field" %}}
```sql
SELECT MEAN(temp) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 22.396153846153844 |
{{% /expand %}}
{{% expand "Calculate the mean value of each field" %}}
```sql
SELECT MEAN(*) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | mean_co | mean_hum | mean_temp |
| :------------------- | ----------------: | -------: | -----------------: |
| 1970-01-01T00:00:00Z | 5.269230769230769 | 36.15 | 22.396153846153844 |
{{% /expand %}}
{{% expand "Calculate the mean value of fields where the field key matches a regular expression" %}}
```sql
SELECT MEAN(/^[th]/) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | mean_hum | mean_temp |
| :------------------- | -------: | -----------------: |
| 1970-01-01T00:00:00Z | 36.15 | 22.396153846153844 |
{{% /expand %}}
{{% expand "Calculate the mean value of a field within time windows (grouped by time)" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
MEAN(temp)
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY time(6h)
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 2022-01-01T06:00:00Z | 22.275 |
| 2022-01-01T12:00:00Z | 22.649999999999995 |
| 2022-01-01T18:00:00Z | 23.033333333333335 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## MEDIAN()
Returns the middle value from a sorted list of [field values](/influxdb/cloud-dedicated/reference/glossary/#field-value).
```sql
MEDIAN(field_expression)
```
#### Arguments
- **field_expression**: Expression to identify one or more fields to operate on.
Can be a [field key](/influxdb/cloud-dedicated/reference/glossary/#field-key),
constant, regular expression, or wildcard (`*`).
Supports **numeric fields**.
#### Notable behaviors
- `MEDIAN()` is nearly equivalent to
[`PERCENTILE(field_key, 50)`](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/#percentile),
except `MEDIAN()` returns the average of the two middle field values if the
field contains an even number of values.
#### Examples
{{< expand-wrapper >}}
{{% expand "Calculate the median value of a field" %}}
```sql
SELECT MEDIAN(temp) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | median |
| :------------------- | -----: |
| 1970-01-01T00:00:00Z | 22.45 |
{{% /expand %}}
{{% expand "Calculate the median value of each field" %}}
```sql
SELECT MEDIAN(*) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | median_co | median_hum | median_temp |
| :------------------- | --------: | ---------: | ----------: |
| 1970-01-01T00:00:00Z | 1 | 36.05 | 22.45 |
{{% /expand %}}
{{% expand "Calculate the median value of fields where the field key matches a regular expression" %}}
```sql
SELECT MEDIAN(/^[th]/) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | median_hum | median_temp |
| :------------------- | ---------: | ----------: |
| 1970-01-01T00:00:00Z | 36.05 | 22.45 |
{{% /expand %}}
{{% expand "Calculate the median value of a field within time windows (grouped by time)" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
MEDIAN(temp)
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY time(6h)
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | median |
| :------------------- | -----------------: |
| 2022-01-01T06:00:00Z | 22.549999999999997 |
| 2022-01-01T12:00:00Z | 22.7 |
| 2022-01-01T18:00:00Z | 23.1 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## MODE()
Returns the most frequent value in a list of
[field values](/influxdb/cloud-dedicated/reference/glossary/#field-value).
```sql
MODE(field_expression)
```
#### Arguments
- **field_expression**: Expression to identify one or more fields to operate on.
Can be a [field key](/influxdb/cloud-dedicated/reference/glossary/#field-key),
constant, regular expression, or wildcard (`*`).
Supports all field types.
#### Notable behaviors
- `MODE()` returns the field value with the earliest
[timestamp](/influxdb/cloud-dedicated/reference/glossary/#timestamp)
if there's a tie between two or more values for the maximum number of occurrences.
#### Examples
{{< expand-wrapper >}}
{{% expand "Calculate the mode value of a field" %}}
```sql
SELECT MODE(co) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | mode |
| :------------------- | ---: |
| 1970-01-01T00:00:00Z | 0 |
{{% /expand %}}
{{% expand "Calculate the mode value of each field" %}}
```sql
SELECT MODE(*) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | mode_co | mode_hum | mode_temp |
| :------------------- | ------: | -------: | --------: |
| 1970-01-01T00:00:00Z | 0 | 36 | 22.7 |
{{% /expand %}}
{{% expand "Calculate the mode of field keys that match a regular expression" %}}
```sql
SELECT MODE(/^[th]/) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | mode_hum | mode_temp |
| :------------------- | -------: | --------: |
| 1970-01-01T00:00:00Z | 36 | 22.7 |
{{% /expand %}}
{{% expand "Calculate the mode a field within time windows (grouped by time)" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
MODE(co)
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY time(6h)
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | mode |
| :------------------- | ---: |
| 2022-01-01T06:00:00Z | 0 |
| 2022-01-01T12:00:00Z | 1 |
| 2022-01-01T18:00:00Z | 18 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## SPREAD()
Returns the difference between the minimum and maximum
[field values](/influxdb/cloud-dedicated/reference/glossary/#field-value).
```sql
SPREAD(field_expression)
```
#### Arguments
- **field_expression**: Expression to identify one or more fields to operate on.
Can be a [field key](/influxdb/cloud-dedicated/reference/glossary/#field-key),
constant, regular expression, or wildcard (`*`).
Supports **numeric fields**.
#### Examples
{{< expand-wrapper >}}
{{% expand "Calculate the spread of a field" %}}
```sql
SELECT SPREAD(temp) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | spread |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 2.3000000000000007 |
{{% /expand %}}
{{% expand "Calculate the spread of each field" %}}
```sql
SELECT SPREAD(*) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | spread_co | spread_hum | spread_temp |
| :------------------- | --------: | ---------: | -----------------: |
| 1970-01-01T00:00:00Z | 26 | 1 | 2.3000000000000007 |
{{% /expand %}}
{{% expand "Calculate the spread of field keys that match a regular expression" %}}
```sql
SELECT SPREAD(/^[th]/) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | spread_hum | spread_temp |
| :------------------- | ---------: | -----------------: |
| 1970-01-01T00:00:00Z | 1 | 2.3000000000000007 |
{{% /expand %}}
{{% expand "Calculate the spread of a field within time windows (grouped by time)" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
SPREAD(co)
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY time(6h)
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | spread |
| :------------------- | -----: |
| 2022-01-01T06:00:00Z | 0 |
| 2022-01-01T12:00:00Z | 9 |
| 2022-01-01T18:00:00Z | 8 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## STDDEV()
Returns the standard deviation of [field values](/influxdb/cloud-dedicated/reference/glossary/#field-value).
```sql
STDDEV(field_expression)
```
#### Arguments
- **field_expression**: Expression to identify one or more fields to operate on.
Can be a [field key](/influxdb/cloud-dedicated/reference/glossary/#field-key),
constant, regular expression, or wildcard (`*`).
Supports **numeric fields**.
#### Examples
{{< expand-wrapper >}}
{{% expand "Calculate the standard deviation of a field" %}}
```sql
SELECT STDDEV(temp) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | stddev |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 0.5553238833191091 |
{{% /expand %}}
{{% expand "Calculate the standard deviation of each field" %}}
```sql
SELECT STDDEV(*) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | stddev_co | stddev_hum | stddev_temp |
| :------------------- | ----------------: | ------------------: | -----------------: |
| 1970-01-01T00:00:00Z | 7.774613519951676 | 0.25495097567963926 | 0.5553238833191091 |
{{% /expand %}}
{{% expand "Calculate the standard deviation of fields where the field key matches a regular expression" %}}
```sql
SELECT STDDEV(/^[th]/) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | stddev_hum | stddev_temp |
| :------------------- | ------------------: | -----------------: |
| 1970-01-01T00:00:00Z | 0.25495097567963926 | 0.5553238833191091 |
{{% /expand %}}
{{% expand "Calculate the standard deviation of a field within time windows (grouped by time)" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
STDDEV(co)
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY time(6h)
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | stddev |
| :------------------- | -----------------: |
| 2022-01-01T06:00:00Z | 0 |
| 2022-01-01T12:00:00Z | 3.6742346141747673 |
| 2022-01-01T18:00:00Z | 4 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## SUM()
Returns the sum of [field values](/influxdb/cloud-dedicated/reference/glossary/#field-value).
```sql
SUM(field_expression)
```
#### Arguments
- **field_expression**: Expression to identify one or more fields to operate on.
Can be a [field key](/influxdb/cloud-dedicated/reference/glossary/#field-key),
constant, regular expression, or wildcard (`*`).
Supports **numeric fields**.
#### Examples
{{< expand-wrapper >}}
{{% expand "Calculate the sum of values in a field" %}}
```sql
SELECT SUM(co) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | sum |
| :------------------- | --: |
| 1970-01-01T00:00:00Z | 137 |
{{% /expand %}}
{{% expand "Calculate the sum of values in each field" %}}
```sql
SELECT SUM(*) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | sum_co | sum_hum | sum_temp |
| :------------------- | -----: | ------: | -------: |
| 1970-01-01T00:00:00Z | 137 | 939.9 | 582.3 |
{{% /expand %}}
{{% expand "Calculate the sum of values for fields where the field key matches a regular expression" %}}
```sql
SELECT SUM(/^[th]/) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | sum_hum | sum_temp |
| :------------------- | ------: | -------: |
| 1970-01-01T00:00:00Z | 939.9 | 582.3 |
{{% /expand %}}
{{% expand "Calculate the sum of values in a field within time windows (grouped by time)" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
SUM(co)
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY time(6h)
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | sum |
| :------------------- | --: |
| 2022-01-01T06:00:00Z | 0 |
| 2022-01-01T12:00:00Z | 21 |
| 2022-01-01T18:00:00Z | 66 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -8,138 +8,6 @@ menu:
name: Date and time
parent: influxql-functions
weight: 206
source: /shared/influxql-v3-reference/functions/date-time.md
---
Use InfluxQL date and time functions to perform time-related operations.
- [now()](#now)
- [time()](#time)
- [tz()](#tz)
## now()
Returns the current system time (UTC).
_Supported only in the [`WHERE` clause](/influxdb/cloud-dedicated/reference/influxql/where/)._
```sql
now()
```
## time()
Used in the [`GROUP BY` clause](/influxdb/cloud-dedicated/reference/influxql/group-by/)
to group data into time-based intervals, also known as "windows", using the specified interval.
Timestamps in the `time` column are updated to the start boundary of the window
they're in and grouped by `time`.
Windows use preset round-number boundaries based on the specified interval that
are independent of time conditions in the
[`WHERE` clause](/influxdb/cloud-dedicated/reference/influxql/where/).
This operation can be used to do the following:
- Downsample data by aggregating multiple points in each window into a single
point per window.
- Normalize irregular time series data to occur at regular intervals.
_Supported only in the [`GROUP BY` clause](/influxdb/cloud-dedicated/reference/influxql/group-by/)._
```sql
time(interval[, offset])
```
#### Arguments
- **interval**: Duration literal that specifies the window interval.
- **offset**: Duration literal that shifts preset time boundaries forward or backward.
Can be positive or negative. _Default is `0s`._
##### Examples {#time-examples}
{{< expand-wrapper >}}
{{% expand "Downsample data into time-based intervals" %}}
The following example uses the
[Bitcoin price sample dataset](/influxdb/cloud-dedicated/reference/sample-data/#bitcoin-price-data).
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'GBP'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-15T00:00:00Z'
GROUP BY time(2d)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 2023-05-01T00:00:00Z | 23680.120447159094 |
| 2023-05-03T00:00:00Z | 24048.71484033149 |
| 2023-05-05T00:00:00Z | 24461.9194901099 |
| 2023-05-07T00:00:00Z | 23796.43801933702 |
| 2023-05-09T00:00:00Z | 23118.709889285707 |
| 2023-05-11T00:00:00Z | 22465.008364444446 |
| 2023-05-13T00:00:00Z | 22499.464763186803 |
{{% /expand %}}
{{< /expand-wrapper >}}
## tz()
Applies a timezone offset to timestamps in query results.
Offsets include any seasonal offset such as Daylight Savings Time (DST) or
British Summer Time (BST).
_Supported only in the [time zone clause](/influxdb/cloud-dedicated/reference/influxql/time-and-timezone/#time-zone-clause)._
```sql
tz(time_zone)
```
#### Arguments
- **time_zone**: Timezone string literal to adjust times to.
Uses timezone names defined in the
[Internet Assigned Numbers Authority time zone database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List).
#### Examples {#tz-examples}
{{< expand-wrapper >}}
{{% expand "Return the UTC offset for Chicago's time zone" %}}
The following example uses the
[Get started home sensor sample dataset](/influxdb/cloud-dedicated/reference/sample-data/#get-started-home-sensor-data).
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T12:00:00Z'
tz('America/Chicago')
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------------ | --: | ---: | :------ | ---: |
| 2022-01-01T02:00:00-06:00 | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T03:00:00-06:00 | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T04:00:00-06:00 | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T05:00:00-06:00 | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T06:00:00-06:00 | 0 | 36 | Kitchen | 22.5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -10,237 +10,6 @@ menu:
identifier: influxql-misc-functions
parent: influxql-functions
weight: 206
source: /shared/influxql-v3-reference/functions/misc.md
---
Use InfluxQL miscellaneous functions to perform different operations in
InfluxQL queries.
- [fill()](#fill)
## fill()
Fills _null_ field values returned from empty time windows in `GROUP BY time()`
queries with a specified fill value.
_Supported only in the [`GROUP BY` clause](/influxdb/cloud-dedicated/reference/influxql/group-by/)._
```sql
fill(behavior)
```
#### Arguments
- **behavior**: Defines the behavior of the fill operation.
If no `FILL` clause is included, the default behavior is `fill(null)`.
The following options are available:
- **numeric literal**: Replaces null values with the specified numeric literal.
- **linear**: Uses linear interpolation between existing values to replace null values.
- **none**: Removes rows with null field values.
- **null**: Keeps null values and associated timestamps.
- **previous**: Replaces null values with the most recent non-null value.
#### Examples {#fill-examples}
The following example uses the
[Bitcoin price sample dataset](/influxdb/cloud-dedicated/reference/sample-data/#bitcoin-price-data).
{{< tabs-wrapper >}}
{{% tabs "small" %}}
[fill(numeric_literal)](#)
[fill(linear)](#)
[fill(none)](#)
[fill(null)](#)
[fill(previous)](#)
{{% /tabs %}}
{{% tab-content %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-01T02:00:00Z'
GROUP BY
time(30m)
fill(0)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | ---------: |
| 2023-05-01T00:00:00Z | 29319.9092 |
| 2023-05-01T00:30:00Z | 29307.4416 |
| 2023-05-01T01:00:00Z | 0 |
| 2023-05-01T01:30:00Z | 29263.2886 |
{{% /tab-content %}}
{{% tab-content %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-01T02:00:00Z'
GROUP BY
time(30m)
fill(linear)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | ---------: |
| 2023-05-01T00:00:00Z | 29319.9092 |
| 2023-05-01T00:30:00Z | 29307.4416 |
| 2023-05-01T01:00:00Z | 29285.3651 |
| 2023-05-01T01:30:00Z | 29263.2886 |
{{% /tab-content %}}
{{% tab-content %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-01T02:00:00Z'
GROUP BY
time(30m)
fill(none)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | ---------: |
| 2023-05-01T00:00:00Z | 29319.9092 |
| 2023-05-01T00:30:00Z | 29307.4416 |
| 2023-05-01T01:30:00Z | 29263.2886 |
{{% /tab-content %}}
{{% tab-content %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-01T02:00:00Z'
GROUP BY
time(30m)
fill(null)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | ---------: |
| 2023-05-01T00:00:00Z | 29319.9092 |
| 2023-05-01T00:30:00Z | 29307.4416 |
| 2023-05-01T01:00:00Z | |
| 2023-05-01T01:30:00Z | 29263.2886 |
{{% /tab-content %}}
{{% tab-content %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-01T02:00:00Z'
GROUP BY
time(30m)
fill(previous)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | ---------: |
| 2023-05-01T00:00:00Z | 29319.9092 |
| 2023-05-01T00:30:00Z | 29307.4416 |
| 2023-05-01T01:00:00Z | 29307.4416 |
| 2023-05-01T01:30:00Z | 29263.2886 |
{{% /tab-content %}}
{{< /tabs-wrapper >}}
<!-- ## tz()
Applies a timezone offset to timestamps in query results.
Offsets include any seasonal offset such as Daylight Savings Time (DST) or
British Summer Time (BST).
_Supported only in the [time zone clause](/influxdb/cloud-dedicated/reference/influxql/time-and-timezone/#time-zone-clause)._
```sql
tz(time_zone)
```
#### Arguments
- **time_zone**: Timezone string literal to adjust times to.
Uses timezone names defined in the
[Internet Assigned Numbers Authority time zone database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List).
#### Examples {#tz-examples}
{{< expand-wrapper >}}
{{% expand "Return the UTC offset for Chicago's time zone" %}}
The following example uses the
[Get started home sensor sample dataset](/influxdb/cloud-dedicated/reference/sample-data/#get-started-home-sensor-data).
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T12:00:00Z'
tz('America/Chicago')
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------------ | --: | ---: | :------ | ---: |
| 2022-01-01T02:00:00-06:00 | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T03:00:00-06:00 | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T04:00:00-06:00 | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T05:00:00-06:00 | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T06:00:00-06:00 | 0 | 36 | Kitchen | 22.5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}} -->

View File

@ -13,632 +13,6 @@ list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] GROUP BY group_expression[, ..., group_expression_n]
```
source: /shared/influxql-v3-reference/group-by.md
---
Use the `GROUP BY` clause to group data by one or more specified
[tags](/influxdb/cloud-dedicated/reference/glossary/#tag) or into specified time intervals.
`GROUP BY` requires an [aggregate](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/)
or [selector](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/)
function in the `SELECT` statement.
<!-- TOC -->
- [Syntax](#syntax)
- [GROUP BY clause behaviors](#group-by-clause-behaviors)
- [GROUP BY tags](#group-by-tags)
- [GROUP BY tags examples](#group-by-tags-examples)
- [GROUP BY time](#group-by-time)
- [GROUP by time and fill gaps](#group-by-time-and-fill-gaps)
- [GROUP BY time examples](#group-by-time-examples)
- [GROUP BY time with offset](#group-by-time-with-offset)
- [GROUP BY time and fill gaps](#group-by-time-and-fill-gaps)
- [Result set](#result-set)
- [Default time range](#default-time-range)
- [Notable behaviors of the GROUP BY clause](#notable-behaviors-of-the-group-by-clause)
- [Cannot group by fields](#cannot-group-by-fields)
- [Tag order does not matter](#tag-order-does-not-matter)
- [Grouping by tag and no time range returns unexpected timestamps](#grouping-by-tag-and-no-time-range-returns-unexpected-timestamps)
- [Data grouped by time may return unexpected timestamps](#data-grouped-by-time-may-return-unexpected-timestamps)
- [Example data](#example-data)
- [Query results](#query-results)
- [Fill with no data in the queried time range](#fill-with-no-data-in-the-queried-time-range)
- [Fill with previous if no previous value exists](#fill-with-previous-if-no-previous-value-exists)
- [Fill with linear interpolation if there are not two values to interpolate between](#fill-with-linear-interpolation-if-there-are-not-two-values-to-interpolate-between)
<!-- /TOC -->
## Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] GROUP BY group_expression[, ..., group_expression_n]
```
- **group_expression**: Expression to identify tags or time intervals to group by.
Can be a [tag key](/influxdb/cloud-dedicated/reference/glossary/#tag-key),
constant, [regular expression](/influxdb/cloud-dedicated/reference/influxql/regular-expressions/),
wildcard (`*`), or [function expression](/influxdb/cloud-dedicated/reference/influxql/functions/).
## GROUP BY clause behaviors
- `GROUP BY tag_key` - Groups data by a specific tag
- `GROUP BY tag_key1, tag_key2` - Groups data by more than one tag
- `GROUP BY *` - Groups data by all [tags](/influxdb/cloud-dedicated/reference/glossary/#tag)
- `GROUP BY /regex/` - Groups data by tag keys that match the regular expression
- `GROUP BY time()` - Groups data into time intervals (windows)
{{% note %}}
If a query includes `WHERE` and `GROUP BY`, the `GROUP BY` clause must appear after
the `WHERE` clause.
{{% /note %}}
## GROUP BY tags
Groups data by one or more tag columns.
### GROUP BY tags examples
The following examples use the
[Bitcoin price sample data](/influxdb/cloud-dedicated/reference/sample-data/#bitcoin-price-data).
{{< expand-wrapper >}}
{{% expand "Group data by a single tag" %}}
```sql
SELECT MEAN(*) FROM bitcoin GROUP BY code
```
{{% influxql/table-meta %}}
name: bitcoin
tags: code=EUR
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 27328.848667840004 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=GBP
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 23441.832453919982 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=USD
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 28054.160950480004 |
{{% /expand %}}
{{% expand "Group data by more than one tag" %}}
```sql
SELECT MEAN(*) FROM bitcoin GROUP BY code, description
```
{{% influxql/table-meta %}}
name: bitcoin
tags: code=EUR, description=Euro
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 27328.848667840004 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=GBP, description=British Pound Sterling
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 23441.832453919982 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=USD, description=United States Dollar
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 28054.160950480004 |
{{% /expand %}}
{{% expand "Group data by all tags" %}}
```sql
SELECT MEAN(*) FROM bitcoin GROUP BY *
```
{{% influxql/table-meta %}}
name: bitcoin
tags: code=EUR, crypto=bitcoin, description=Euro, symbol=&euro;
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 27328.848667840004 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=GBP, crypto=bitcoin, description=British Pound Sterling, symbol=&pound;
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 23441.832453919982 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=USD, crypto=bitcoin, description=United States Dollar, symbol=&#36;
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 28054.160950480004 |
{{% /expand %}}
{{% expand "Group data by tag keys that match a regular expression" %}}
```sql
SELECT MEAN(*) FROM bitcoin GROUP BY /^[cd]/
```
{{% influxql/table-meta %}}
name: bitcoin
tags: code=EUR, crypto=bitcoin, description=Euro
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 27328.848667840004 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=GBP, crypto=bitcoin, description=British Pound Sterling
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 23441.832453919982 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=USD, crypto=bitcoin, description=United States Dollar
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 28054.160950480004 |
{{% /expand %}}
{{< /expand-wrapper >}}
## GROUP BY time
`GROUP BY time()` groups data by into specified time intervals, also known as "windows",
and applies the [aggregate](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/)
and [selector](/influxdb/cloud-dedicated/reference/influxql/functions/selectors/)
functions in the `SELECT` clause to each interval.
Use the [`time()` function](/influxdb/cloud-dedicated/reference/influxql/functions/date-time/#time)
to specify the time interval to group by.
```sql
SELECT_clause FROM_clause WHERE <time_range> GROUP BY time(time_interval[, offset])[, group_expression (...)] [fill(behavior)]
```
`GROUP BY time()` intervals use preset round-number time boundaries that
are independent of time conditions in the [`WHERE` clause](/influxdb/cloud-dedicated/reference/influxql/where/).
**Output data uses window start boundaries as the aggregate timestamps.**
Use the `offset` argument of the `time()` function to shift time boundaries forward or
backward in time.
### GROUP by time and fill gaps
When grouping by time, if a window in the queried time range does not contain data,
results return a row for the empty window containing the timestamp of the empty
window and _null_ values for each queried field.
Use the [`fill()` function](/influxdb/cloud-dedicated/reference/influxql/functions/misc/#fill)
_at the end of the `GROUP BY` clause_ to replace _null_ field values.
If no `FILL` clause is included, the default behavior is `fill(null)`.
`fill()` provides the following behaviors for filling values:
- **numeric literal**: Replaces null values with the specified numeric literal.
- **linear**: Uses linear interpolation between existing values to replace null values.
- **none**: Removes rows with null field values.
- **null**: Keeps null values and associated timestamps.
- **previous**: Replaces null values with the most recent non-null value.
_See the [`fill()` documentation](/influxdb/cloud-dedicated/reference/influxql/functions/misc/#fill)
for detailed examples._
### GROUP BY time examples
The following examples use the
[Bitcoin price sample data](/influxdb/cloud-dedicated/reference/sample-data/#bitcoin-price-data).
{{< expand-wrapper >}}
{{% expand "Group and aggregate query results into 1 hour windows" %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-15T00:00:00Z'
GROUP BY time(1h)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 2023-05-01T00:00:00Z | 24494.27265 |
| 2023-05-01T01:00:00Z | 24452.1698 |
| 2023-05-01T02:00:00Z | 23902.666124999996 |
| 2023-05-01T03:00:00Z | 23875.211349999998 |
| 2023-05-01T04:00:00Z | 23855.6441 |
| ... | ... |
{{% /expand %}}
{{% expand "Group and aggregate query results into 1 week intervals by tag" %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-15T00:00:00Z'
GROUP BY time(1w), code
```
{{% influxql/table-meta %}}
name: bitcoin
tags: code=EUR
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 2023-04-27T00:00:00Z | 27681.21808576779 |
| 2023-05-04T00:00:00Z | 27829.413580354256 |
| 2023-05-11T00:00:00Z | 26210.24799033149 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=GBP
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 2023-04-27T00:00:00Z | 23744.083925842704 |
| 2023-05-04T00:00:00Z | 23871.201395652173 |
| 2023-05-11T00:00:00Z | 22482.33174723755 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=USD
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 2023-04-27T00:00:00Z | 28415.88231123595 |
| 2023-05-04T00:00:00Z | 28568.010941384844 |
| 2023-05-11T00:00:00Z | 26905.87242099449 |
{{% /expand %}}
{{< /expand-wrapper >}}
###### GROUP BY time with offset
{{< expand-wrapper >}}
{{% expand "Group and aggregate query results into 1 hour intervals and offset time boundaries by +15 minutes" %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-02T00:00:00Z'
GROUP BY time(1h, 15m)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 2023-04-30T23:15:00Z | |
| 2023-05-01T00:15:00Z | 29313.6754 |
| 2023-05-01T01:15:00Z | 28932.0882 |
| 2023-05-01T02:15:00Z | 28596.375225000003 |
| 2023-05-01T03:15:00Z | 28578.915075 |
| ... | ... |
_Note that `offset` forces the first time boundary to be outside
the queried time range so the query returns no results for that first interval._
{{% /expand %}}
{{% expand "Group and aggregate query results into 1 hour intervals and offset time boundaries by -15 minutes" %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-02T00:00:00Z'
GROUP BY time(1h, -15m)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 2023-04-30T23:45:00Z | 29319.9092 |
| 2023-05-01T00:45:00Z | 29285.3651 |
| 2023-05-01T01:45:00Z | 28607.202666666668 |
| 2023-05-01T02:45:00Z | 28576.056175 |
| 2023-05-01T03:45:00Z | 28566.96315 |
| ... | ... |
{{% /expand %}}
{{< /expand-wrapper >}}
###### GROUP BY time and fill gaps
{{< expand-wrapper >}}
{{% expand "Group and aggregate query results into 30 minute intervals and fill gaps with `0`" %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-01T02:00:00Z'
GROUP BY
time(30m)
fill(0)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| -------------------- | ---------- |
| 2023-05-01T00:00:00Z | 29319.9092 |
| 2023-05-01T00:30:00Z | 29307.4416 |
| 2023-05-01T01:00:00Z | 0 |
| 2023-05-01T01:30:00Z | 29263.2886 |
{{% /expand %}}
{{% expand "Group and aggregate query results into 30 minute intervals and fill gaps using linear interpolation" %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-01T02:00:00Z'
GROUP BY
time(30m)
fill(linear)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| -------------------- | ---------- |
| 2023-05-01T00:00:00Z | 29319.9092 |
| 2023-05-01T00:30:00Z | 29307.4416 |
| 2023-05-01T01:00:00Z | 29285.3651 |
| 2023-05-01T01:30:00Z | 29263.2886 |
{{% /expand %}}
{{% expand "Group and aggregate query results into 30 minute intervals and fill gaps with previous values" %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-01T02:00:00Z'
GROUP BY
time(30m)
fill(previous)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| -------------------- | ---------- |
| 2023-05-01T00:00:00Z | 29319.9092 |
| 2023-05-01T00:30:00Z | 29307.4416 |
| 2023-05-01T01:00:00Z | 29307.4416 |
| 2023-05-01T01:30:00Z | 29263.2886 |
{{% /expand %}}
{{< /expand-wrapper >}}
## Result set
If at least one row satisfies the query, {{% product-name %}} returns row data in the query result set.
If a query uses a `GROUP BY` clause, the result set includes the following:
- Columns listed in the query's `SELECT` clause
- A `time` column that contains the timestamp for the record or the group
- An `iox::measurement` column that contains the record's measurement (table) name
- Columns listed in the query's `GROUP BY` clause; each row in the result set contains the values used for grouping
### Default time range
If a query doesn't specify a time range in the
[`WHERE` clause](/influxdb/cloud-dedicated/reference/influxql/where/), InfluxDB uses the
[default time range](/influxdb/cloud-dedicated/reference/influxql/#default-time-range) for filtering and grouping by time.
If a query includes the `GROUP BY` clause and doesn't specify a time range in the
`WHERE` clause, the default time group is the
[default time range](/influxdb/cloud-dedicated/reference/influxql/#default-time-range), and the `time` column in the result set contains the start of the range--for example:
```sql
SELECT mean(temp) FROM home GROUP BY room
```
{{% influxql/table-meta %}}
name: home
tags: room=Kitchen
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 22.623076923076926 |
{{% influxql/table-meta %}}
name: home
tags: room=Living Room
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | ----------------: |
| 1970-01-01T00:00:00Z | 22.16923076923077 |
## Notable behaviors of the GROUP BY clause
### Cannot group by fields
InfluxQL does not support grouping data by **fields**.
### Tag order does not matter
The order that tags are listed in the `GROUP BY` clause does not affect how
data is grouped.
### Grouping by tag and no time range returns unexpected timestamps
The `time` column contains the start of the [default time range](#default-time-range).
### Data grouped by time may return unexpected timestamps
Because `GROUP BY time()` intervals use preset round-number time boundaries that
are independent of time conditions in the [`WHERE` clause](/influxdb/cloud-dedicated/reference/influxql/where/),
results may include timestamps outside of the queried time range.
Results represent only data with timestamps in the specified time range, but
output timestamps are determined by by the preset time boundaries.
The following example groups data by 1-hour intervals, but the time range defined
in the `WHERE` clause covers only part of a window:
```sql
SELECT MEAN(field)
FROM example
WHERE
time >= '2022-01-01T00:30:00Z'
AND time <= '2022-01-01T01:30:00Z'
GROUP BY time(1h)
```
{{% note %}}
**Note**: The timestamp in the first row of query results data occurs before the start of
the queried time range.
[See why](#why-do-these-results-include-timestamps-outside-of-the-queried-time-range).
{{% /note %}}
{{% influxdb/custom-timestamps %}}
{{< flex >}}
{{% flex-content %}}
#### Example data
| time | field |
| :------------------- | ----: |
| 2022-01-01T00:00:00Z | 8 |
| 2022-01-01T00:15:00Z | 4 |
| 2022-01-01T00:30:00Z | 0 |
| 2022-01-01T00:45:00Z | 8 |
| 2022-01-01T01:00:00Z | 5 |
| 2022-01-01T01:15:00Z | 0 |
| 2022-01-01T01:30:00Z | 8 |
| 2022-01-01T01:45:00Z | 8 |
| 2022-01-01T02:00:00Z | 9 |
| 2022-01-01T02:15:00Z | 6 |
| 2022-01-01T02:30:00Z | 3 |
| 2022-01-01T02:45:00Z | 0 |
{{% /flex-content %}}
{{% flex-content %}}
#### Query results
| time | field |
| :------------------- | ----: |
| 2022-01-01T00:00:00Z | 4 |
| 2022-01-01T01:00:00Z | 5.25 |
| 2022-01-01T02:00:00Z | 6 |
{{% /flex-content %}}
{{< /flex >}}
{{% /influxdb/custom-timestamps %}}
{{< expand-wrapper >}}
{{% expand "Why do these results include timestamps outside of the queried time range?" %}}
`GROUP BY time()` creates windows with predefined time boundaries based on the
specified interval. These boundaries are not determined by the queried time
range, however, aggregate values in query results are calculated using only
values that are in the queried time range.
{{< html-diagram/influxql-windows >}}
{{% /expand %}}
{{< /expand-wrapper >}}
### Fill with no data in the queried time range
Queries ignore `fill()` if no data exists in the queried time range.
This is the expected behavior.
### Fill with previous if no previous value exists
`fill(previous)` doesnt fill null values if there is no previous value in
the queried time range.
### Fill with linear interpolation if there are not two values to interpolate between
`fill(linear)` doesn't fill null values if there are no values before or after
the null value in the queried time range.

View File

@ -6,159 +6,6 @@ menu:
name: InfluxQL internals
parent: influxql-reference
weight: 219
source: /shared/influxql-v3-reference/internals.md
---
Learn about the implementation of InfluxQL to understand how
results are processed and how to create efficient queries:
- [Query life cycle](#query-life-cycle)
- [Understanding iterators](#understanding-iterators)
- [Cursors](#cursors)
- [Auxiliary fields](#auxiliary-fields)
- [Built-in iterators](#built-in-iterators)
- [Call iterators](#call-iterators)
## Query life cycle
1. InfluxQL query string is tokenized and then parsed into an abstract syntax
tree (AST). This is the code representation of the query itself.
2. The AST is passed to the `QueryExecutor` which directs queries to the
appropriate handlers. For example, queries related to meta data are executed
by the **meta service** and `SELECT` statements are executed by the shards
themselves.
3. The query engine then determines the shards that match the `SELECT`
statement's time range. From these shards, iterators are created for each
field in the statement.
4. Iterators are passed to the emitter which drains them and joins the resulting
points. The emitter's job is to convert simple time/value points into the
more complex result objects that are returned to the client.
### Understanding iterators
Iterators provide a simple interface for looping over a set of points.
For example, this is an iterator over Float points:
```
type FloatIterator interface {
Next() *FloatPoint
}
```
These iterators are created through the `IteratorCreator` interface:
```
type IteratorCreator interface {
CreateIterator(opt *IteratorOptions) (Iterator, error)
}
```
The `IteratorOptions` provide arguments about field selection, time ranges,
and dimensions that the iterator creator can use when planning an iterator.
The `IteratorCreator` interface is used at many levels such as the `Shards`,
`Shard`, and `Engine`. This allows optimizations to be performed when applicable
such as returning a precomputed `COUNT()`.
Iterators aren't just for reading raw data from storage, though. Iterators can be
composed so that they provide additional functionality around an input
iterator. For example, a `DistinctIterator` can compute the distinct values for
each time window for an input iterator. Or a `FillIterator` can generate
additional points that are missing from an input iterator.
This composition also lends itself well to aggregation.
For example, in the following SQL, `MEAN(value)` is a `MeanIterator` that wraps an iterator from the
underlying shards:
```sql
SELECT MEAN(value) FROM cpu GROUP BY time(10m)
```
The following example wraps `MEAN(value)` with an additional iterator (`DERIVATIVE()`) to determine
the derivative of the mean:
```sql
SELECT DERIVATIVE(MEAN(value), 20m) FROM cpu GROUP BY time(10m)
```
### Cursors
A **cursor** identifies data by shard in tuples (time, value) for a single series (measurement, tag set and field). The cursor traverses data stored as a log-structured merge-tree and handles deduplication across levels, tombstones for deleted data, and merging the cache (Write Ahead Log). A cursor sorts the `(time, value)` tuples by time in ascending or descending order.
For example, a query that evaluates one field for 1,000 series over 3 shards constructs a minimum of 3,000 cursors (1,000 per shard).
### Auxiliary fields
Because InfluxQL allows users to use selector functions such as `FIRST()`,
`LAST()`, `MIN()`, and `MAX()`, the engine must provide a way to return related
data at the same time with the selected point.
Let's look at the following query:
```sql
SELECT FIRST(value), host FROM cpu GROUP BY time(1h)
```
We are selecting the first `value` that occurs every hour but we also want to
retrieve the `host` associated with that point. Since the `Point` types only
specify a single typed `Value` for efficiency, we push the `host` into the
auxiliary fields of the point. These auxiliary fields are attached to the point
until it is passed to the emitter where the fields get split off to their own
iterator.
### Built-in iterators
There are many helper iterators that let us build queries:
* Merge Iterator - This iterator combines one or more iterators into a single
new iterator of the same type. This iterator guarantees that all points
within a window will be output before starting the next window, but does not
provide ordering guarantees within the window. This allows for fast access
for aggregate queries that don't need stronger sorting guarantees.
* Sorted Merge Iterator - Like `MergeIterator`, this iterator combines one or more iterators
into a new iterator of the same type. However, this iterator guarantees
time ordering of every point. This makes it slower than the `MergeIterator`
but this ordering guarantee is required for non-aggregate queries which
return the raw data points.
* Limit Iterator - This iterator limits the number of points per name or tag
group. This is the implementation of the `LIMIT` & `OFFSET` syntax.
* Fill Iterator - This iterator injects extra points if they are missing from
the input iterator. It can provide `null` points, points with the previous
value, or points with a specific value.
* Buffered Iterator - This iterator provides the ability to "unread" a point
back onto a buffer so it can be read again next time. This is used extensively
to provide lookahead for windowing.
* Reduce Iterator - This iterator calls a reduction function for each point in
a window. When the window is complete, then all points for that window are
output. This is used for simple aggregate functions such as `COUNT()`.
* Reduce Slice Iterator - This iterator collects all points for a window first,
and then passes them all to a reduction function at once. The results are
returned from the iterator. This is used for aggregate functions such as
`DERIVATIVE()`.
* Transform Iterator - This iterator calls a transform function for each point
from an input iterator. This is used for executing binary expressions.
* Dedupe Iterator - This iterator only outputs unique points. Because it is resource-intensive, this iterator is only used for small queries such as meta query statements.
### Call iterators
Function calls in InfluxQL are implemented at two levels:
- Some calls can be
wrapped at multiple layers to improve efficiency. For example, a `COUNT()` can
be performed at the shard level and then multiple `CountIterator`s can be
wrapped with another `CountIterator` to compute the count of all shards. These
iterators can be created using `NewCallIterator()`.
- Some iterators are more complex or need to be implemented at a higher level.
For example, the `DERIVATIVE()` function needs to retrieve all points for a window
before performing the calculation. This iterator is created by the engine itself
and is never requested to be created by the lower levels.

View File

@ -13,249 +13,6 @@ list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] LIMIT row_N SLIMIT series_N
```
source: /shared/influxql-v3-reference/limit-and-slimit.md
---
Use `LIMIT` to limit the number of **rows** returned per InfluxQL group.
Use `SLIMIT` to limit the number of [series](/influxdb/cloud-dedicated/reference/glossary/#series)
returned in query results.
- [LIMIT clause](#limit-clause)
- [Syntax](#limit-syntax)
- [Examples](#limit-examples)
- [SLIMIT clause](#slimit-clause)
<!-- - [Syntax](#slimit-syntax) -->
<!-- - [Examples](#slimit-examples) -->
<!-- - [Use LIMIT and SLIMIT together](#use-limit-and-slimit-together) -->
<!-- - [Syntax](#limit-slimit-syntax) -->
<!-- - [Examples](#limit-slimit-examples) -->
## LIMIT clause
The `LIMIT` clause limits the number of rows to return from each InfluxQL group.
If the query doesn't include a [`GROUP BY` clause](/influxdb/cloud-dedicated/reference/influxql/group-by/),
the entire result set is considered a single group.
If a query [groups data by time](/influxdb/cloud-dedicated/reference/influxql/group-by/#group-by-time),
limits are applied after aggregate and selector operations are applied to each
time window.
### Syntax {#limit-syntax}
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] LIMIT N
```
#### Arguments
- **N**: Maximum number of points to return from each InfluxQL group.
If `N` is greater than the number of points in a group,
all points from the group are returned.
### Examples {#limit-examples}
The following examples use the
[Get started home sensor sample data](/influxdb/cloud-dedicated/reference/sample-data/#get-started-home-sensor-data).
{{< expand-wrapper >}}
{{% expand "Limit the number of rows returned" %}}
```sql
SELECT * FROM home LIMIT 3
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :---------- | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Living Room | 21.1 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Limit the number of rows returned from each InfluxQL group" %}}
```sql
SELECT
MEAN(*)
FROM home
GROUP BY
time(2h),
room
LIMIT 3
```
{{% influxdb/custom-timestamps %}}
{{% influxql/table-meta %}}
name: home
tags: room=Kitchen
{{% /influxql/table-meta %}}
| time | mean_co | mean_hum | mean_temp |
| :------------------- | ------: | -------: | -----------------: |
| 2022-01-01T08:00:00Z | 0 | 36.05 | 22 |
| 2022-01-01T10:00:00Z | 0 | 36.05 | 22.549999999999997 |
| 2022-01-01T12:00:00Z | 0.5 | 36.25 | 22.65 |
{{% influxql/table-meta %}}
name: home
tags: room=Living Room
{{% /influxql/table-meta %}}
| time | mean_co | mean_hum | mean_temp |
| :------------------- | ------: | -------: | -----------------: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | 21.25 |
| 2022-01-01T10:00:00Z | 0 | 36 | 22 |
| 2022-01-01T12:00:00Z | 0 | 35.95 | 22.299999999999997 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## SLIMIT clause
{{% warn %}}
InfluxQL is being rearchitected to work with the InfluxDB 3.0 storage engine.
This process is ongoing and some InfluxQL features, such as `SLIMIT` are still
being implemented. For more information, see
[InfluxQL feature support](/influxdb/cloud-dedicated/reference/influxql/feature-support/).
{{% /warn %}}
<!-- The `SLIMIT` clause limits the number of [series](/influxdb/cloud-dedicated/reference/glossary/#series)
to return in query results.
{{% note %}}
For meaningful results, queries that include the `SLIMIT` clause should also
include the [`GROUP BY` clause](/influxdb/cloud-dedicated/reference/influxql/group-by/) that
[groups by tags](/influxdb/cloud-dedicated/reference/influxql/group-by/#group-by-tags-examples).
Without grouping data by tags, all results are treated as a single series and
`SLIMIT` returns the full queried result set.
{{% /note %}}
### Syntax {#slimit-syntax}
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] [LIMIT_clause] SLIMIT N
```
If the query includes a [`LIMIT` clause](#limit-clause), the `SLIMIT` clause
must come **after** the `LIMIT` clause.
See [Use LIMIT and SLIMIT together](#use-limit-and-slimit-together).
#### Arguments
- **N**: Maximum number of series to return in query results.
If `N` is greater than the number of series in a measurement, the query
returns all series.
### Examples {#slimit-examples}
{{< expand-wrapper >}}
{{% expand "Limit the number of series returned" %}}
The following example uses the
[Bitcoin price sample data](/influxdb/cloud-dedicated/reference/sample-data/#bitcoin-price-data).
```sql
SELECT * FROM bitcoin GROUP BY * SLIMIT 2
```
{{% influxql/table-meta %}}
name: bitcoin
tags: code=EUR, crypto=bitcoin, description=Euro, symbol=&euro;
{{% /influxql/table-meta %}}
| time | price |
| :------------------- | ---------: |
| 2023-05-01T00:19:00Z | 28561.8722 |
| 2023-05-01T00:48:00Z | 28549.727 |
| 2023-05-01T01:31:00Z | 28506.7155 |
| 2023-05-01T02:07:00Z | 27861.4404 |
| 2023-05-01T02:26:00Z | 27864.0643 |
| ... | ... |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=GBP, crypto=bitcoin, description=British Pound Sterling, symbol=&pound;
{{% /influxql/table-meta %}}
| time | price |
| :------------------- | ---------: |
| 2023-05-01T00:19:00Z | 24499.4816 |
| 2023-05-01T00:48:00Z | 24489.0637 |
| 2023-05-01T01:31:00Z | 24452.1698 |
| 2023-05-01T02:07:00Z | 23898.673 |
| 2023-05-01T02:26:00Z | 23900.9237 |
| ... | ... |
{{% /expand %}}
{{< /expand-wrapper >}}
## Use LIMIT and SLIMIT together
Using the `LIMIT` clause and the `SLIMIT` clause together returns the specified
maximum number of rows from the specified maximum number of series in query results.
### Syntax {#limit-slimit-syntax}
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] LIMIT row_N SLIMIT series_N
```
In queries that include both the `LIMIT` clause and the `SLIMIT` clause,
the `LIMIT` clause must come **first**.
#### Arguments
- **row_N**: Maximum number of points to return from each InfluxQL group.
If `row_N` is greater than the number of points in a group,
all points from the group are returned.
- **series_N**: Maximum number of series to return in query results.
If `series_N` is greater than the number of series in a measurement, the query
returns all series.
### Examples {#limit-slimit-examples}
{{< expand-wrapper >}}
{{% expand "Limit the number of rows and series returned" %}}
The following example uses the
[Bitcoin price sample data](/influxdb/cloud-dedicated/reference/sample-data/#bitcoin-price-data).
```sql
SELECT * FROM bitcoin GROUP BY * LIMIT 3 SLIMIT 2
```
{{% influxql/table-meta %}}
name: bitcoin
tags: code=EUR, crypto=bitcoin, description=Euro, symbol=&euro;
{{% /influxql/table-meta %}}
| time | price |
| :------------------- | ---------: |
| 2023-05-01T00:19:00Z | 28561.8722 |
| 2023-05-01T00:48:00Z | 28549.727 |
| 2023-05-01T01:31:00Z | 28506.7155 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=GBP, crypto=bitcoin, description=British Pound Sterling, symbol=&pound;
{{% /influxql/table-meta %}}
| time | price |
| :------------------- | ---------: |
| 2023-05-01T00:19:00Z | 24499.4816 |
| 2023-05-01T00:48:00Z | 24489.0637 |
| 2023-05-01T01:31:00Z | 24452.1698 |
{{% /expand %}}
{{< /expand-wrapper >}} -->

View File

@ -9,273 +9,6 @@ menu:
parent: influxql-reference
identifier: influxql-mathematical-operators
weight: 215
source: /shared/influxql-v3-reference/math-operators.md
---
Use InfluxQL mathematical operators to perform mathematical operations in InfluxQL queries.
Mathematical operators follow the [standard order of operations](https://golang.org/ref/spec#Operator_precedence).
Parentheses take precedence to division and multiplication, which takes precedence to addition and subtraction.
For example `5 / 2 + 3 * 2 = (5 / 2) + (3 * 2)` and `5 + 2 * 3 - 2 = 5 + (2 * 3) - 2`.
- [Addition](#addition)
- [Subtraction](#subtraction)
- [Multiplication](#multiplication)
- [Division](#division)
- [Modulo](#modulo)
- [Bitwise AND](#bitwise-and)
- [Bitwise OR](#bitwise-or)
- [Bitwise Exclusive-OR](#bitwise-exclusive-or)
- [Unsupported Operators](#unsupported-operators)
- [Notable behaviors of mathematical operators](#notable-behaviors-of-mathematical-operators)
## Addition
Add two numeric operands. Operands may be an identifier, constant, or literal
numeric value.
```sql
SELECT A + 5 FROM example
SELECT A + B FROM example
SELECT * FROM example WHERE A + 5 > 10
SELECT * FROM example WHERE A + B > 10
```
## Subtraction
Subtract one numeric operand from another. Operands may be an identifier,
constant, or literal numeric value.
```sql
SELECT 1 - A FROM example
SELECT B - A FROM example
SELECT * FROM example WHERE 1 - A <= 3
SELECT * FROM example WHERE B - A <= 3
```
## Multiplication
Multiply two numeric operands. Operands may be an identifier, constant, or literal
numeric value.
```sql
SELECT A * 10 FROM example
SELECT A * B FROM example
SELECT * FROM example WHERE A * 10 >= 20
SELECT * FROM example WHERE A * B >= 20
```
Multiplication distributes across other operators.
```sql
SELECT 10 * (A + B + C) FROM example
SELECT 10 * (A - B - C) FROM example
SELECT 10 * (A + B - C) FROM example
```
## Division
Divide one numeric operand by another. Operands may be an identifier, constant,
or literal numeric value.
```sql
SELECT A / 10 FROM example
SELECT A / B FROM example
SELECT * FROM example WHERE A / 10 <= 2
SELECT * FROM example WHERE A / B <= 2
```
Division distributes across other operators.
```sql
SELECT 10 / (A + B + C) FROM example
SELECT 10 / (A - B - C) FROM example
SELECT 10 / (A + B - C) FROM example
```
## Modulo
Perform a modulo operation with two numeric operands. Operands may be an
identifier, constant, or literal numeric value.
```sql
SELECT A % 2 FROM example
SELECT A % B FROM example
SELECT A FROM example WHERE A % 2 = 0
SELECT A, B FROM example WHERE A % B = 0
```
## Bitwise AND
Perform a bitwise `AND` operation on two operands _of the same type_.
Supported types are **integers** and **booleans**.
Operands may be an identifier, constant, literal integer value, or literal boolean value.
```sql
SELECT A & 255 FROM example
SELECT A & B FROM example
SELECT (A ^ true) & B FROM example
SELECT * FROM example WHERE A & 15 > 0
```
## Bitwise OR
Perform a bitwise `OR` operation on two operands _of the same type_.
Supported types are **integers** and **booleans**.
Operands may be an identifier, constant, literal integer value, or literal boolean value.
```sql
SELECT A | 5 FROM example
SELECT A | B FROM example
SELECT * FROM example WHERE "bitfield" | 12 = 12
```
## Bitwise Exclusive-OR
Perform a bitwise `Exclusive-OR` operation on two operands _of the same type_.
Supported types are **integers** and **booleans**.
Operands may be an identifier, constant, literal integer value, or literal boolean value.
```sql
SELECT A ^ 255 FROM example
SELECT A ^ B FROM example
SELECT * FROM example WHERE "bitfield" ^ 6 > 0
```
## Unsupported Operators
### Inequalities
Using any of `=`,`!=`,`<`,`>`,`<=`,`>=`,`<>` in the `SELECT` statement yields
empty results for all types.
Comparison operators can only be used in the `WHERE` clause.
### Logical Operators
Using any of `!|`,`NAND`,`XOR`,`NOR` yield a parser error.
Additionally using `AND`, `OR` in the `SELECT` clause of a query will not behave
as mathematical operators and simply yield empty results, as they are InfluxQL tokens.
However, you can apply the bitwise operators `&`, `|` and `^` to boolean values.
### Bitwise Not
There is no bitwise-not operator, because the results you expect depend on the width of your bitfield.
InfluxQL does not know how wide your bitfield is, so cannot implement a suitable
bitwise-not operator.
For example, if your bitfield is 8 bits wide, then the integer 1 represents the bits `0000 0001`.
The bitwise-not of this should return the bits `1111 1110` (that is, the integer 254)
However, if your bitfield is 16 bits wide, then the integer 1 represents the bits `0000 0000 0000 0001`.
The bitwise-not of this should return the bits `1111 1111 1111 1110` (that is, the integer 65534)
#### Solution
You can implement a bitwise-not operation by using the `^` (bitwise xor) operator
together with the number representing all-ones for your word-width:
For 8-bit data:
```sql
SELECT A ^ 255 FROM example
```
For 16-bit data:
```sql
SELECT A ^ 65535 FROM example
```
For 32-bit data:
```sql
SELECT A ^ 4294967295 FROM example
```
In each case, the constant you need can be calculated as `(2 ** width) - 1`.
## Notable behaviors of mathematical operators
- [Mathematical operators with wildcards and regular expressions](#mathematical-operators-with-wildcards-and-regular-expressions)
- [Mathematical operators with functions](#mathematical-operators-with-functions)
### Mathematical operators with wildcards and regular expressions
InfluxQL does not support combining mathematical operations with a wildcard (`*`)
or [regular expression](/influxdb/cloud-dedicated/reference/influxql/regular-expressions/)
in the `SELECT` clause.
The following queries are invalid and the output is an error:
Perform a mathematical operation on a wildcard.
```sql
SELECT * + 2 FROM "nope"
-- ERR: unsupported expression with wildcard: * + 2
```
Perform a mathematical operation on a wildcard within a function.
```sql
SELECT COUNT(*) / 2 FROM "nope"
-- ERR: unsupported expression with wildcard: count(*) / 2
```
Perform a mathematical operation on a regular expression.
```sql
SELECT /A/ + 2 FROM "nope"
-- ERR: error parsing query: found +, expected FROM at line 1, char 12
```
Perform a mathematical operation on a regular expression within a function.
```sql
SELECT COUNT(/A/) + 2 FROM "nope"
-- ERR: unsupported expression with regex field: count(/A/) + 2
```
### Mathematical operators with functions
InfluxQL does not support mathematical operators inside of function calls.
Note that InfluxQL only allows functions in the `SELECT` clause.
For example, the following will work:
```sql
SELECT 10 * mean("value") FROM "cpu"
```
However, the following query will return a parse error:
```sql
SELECT mean(10 * "value") FROM "cpu"
-- Error: expected field argument in mean()
```
<!-- {{% note %}}
InfluxQL supports [subqueries](/influxdb/v2/query-data/influxql/explore-data/subqueries/) which offer similar functionality to using mathematical operators inside a function call.
{{% /note %}} -->

View File

@ -14,236 +14,6 @@ list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] [LIMIT_clause] OFFSET row_N [SLIMIT_clause] SOFFSET series_N
```
source: /shared/influxql-v3-reference/offset-and-soffset.md
---
Use `OFFSET` to specify the number of [rows](/influxdb/cloud-dedicated/reference/glossary/#series)
to skip in each InfluxQL group before returning results.
Use `SOFFSET` to specify the number of [series](/influxdb/cloud-dedicated/reference/glossary/#series)
to skip before returning results.
- [OFFSET clause](#offset-clause)
- [Syntax](#offset-syntax)
- [Notable OFFSET clause behaviors](#notable-offset-clause-behaviors)
- [Examples](#offset-examples)
- [SOFFSET clause](#soffset-clause)
<!-- - [Syntax](#soffset-syntax) -->
<!-- - [Notable SOFFSET clause behaviors](#notable-soffset-clause-behaviors) -->
<!-- - [Examples](#soffset-examples) -->
## `OFFSET` clause
The `OFFSET` clause skips `N` rows in each InfluxQL group before returning results.
Offsets honor row limits specified in the
[`LIMIT` clause](/influxdb/cloud-dedicated/reference/influxql/limit-and-slimit/#limit-clause)
and display the limited number of rows after the specified offset.
Use `LIMIT` and `OFFSET` together to paginate query results.
### Syntax {#offset-syntax}
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] [LIMIT_clause] OFFSET N [SLIMIT_clause] [SOFFSET_clause]
```
#### Arguments
- **N**: Number of rows to skip in each InfluxQL group before returning results.
### Notable OFFSET clause behaviors
- If there is no `LIMIT` clause in a query with an `OFFSET` clause, the query
returns a single row per InfluxQL group at the specified offset.
- If the query doesn't include a [`GROUP BY` clause](/influxdb/cloud-dedicated/reference/influxql/group-by/),
the entire result set is considered a single group and is returned in full.
- If a query [groups data by time](/influxdb/cloud-dedicated/reference/influxql/group-by/#group-by-time),
the offset is applied after aggregate and selector operations are applied to each
time window.
- If the [`WHERE` clause](/influxdb/cloud-dedicated/reference/influxql/where/)
includes a time range and the `OFFSET` clause causes InfluxQL to return points
with timestamps outside of that time range, InfluxQL returns no results.
### Examples {#offset-examples}
The following examples use the
[Get started home sensor sample data](/influxdb/cloud-dedicated/reference/sample-data/#get-started-home-sensor-data).
{{< expand-wrapper >}}
{{% expand "Return the nth row" %}}
```sql
SELECT * FROM home OFFSET 3
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :---------- | ---: |
| 2022-01-01T09:00:00Z | 0 | 35.9 | Living Room | 21.4 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Paginate results by 3 and return the 2nd page of results" %}}
```sql
SELECT * FROM home WHERE room = 'Kitchen' LIMIT 3 OFFSET 3
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :------ | ---: |
| 2022-01-01T11:00:00Z | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T12:00:00Z | 0 | 36 | Kitchen | 22.5 |
| 2022-01-01T13:00:00Z | 1 | 36.5 | Kitchen | 22.8 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Paginate results from each series by 3 and return the 2nd page of each series" %}}
```sql
SELECT * FROM home GROUP BY * LIMIT 3 OFFSET 3
```
{{% influxdb/custom-timestamps %}}
{{% influxql/table-meta %}}
name: home
tags: room=Kitchen
{{% /influxql/table-meta %}}
| time | co | hum | temp |
| :------------------- | --: | ---: | ---: |
| 2022-01-01T11:00:00Z | 0 | 36 | 22.4 |
| 2022-01-01T12:00:00Z | 0 | 36 | 22.5 |
| 2022-01-01T13:00:00Z | 1 | 36.5 | 22.8 |
{{% influxql/table-meta %}}
name: home
tags: room=Living Room
{{% /influxql/table-meta %}}
| time | co | hum | temp |
| :------------------- | --: | ---: | ---: |
| 2022-01-01T11:00:00Z | 0 | 36 | 22.2 |
| 2022-01-01T12:00:00Z | 0 | 35.9 | 22.2 |
| 2022-01-01T13:00:00Z | 0 | 36 | 22.4 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## `SOFFSET` clause
{{% warn %}}
InfluxQL is being rearchitected to work with the InfluxDB 3.0 storage engine.
This process is ongoing and some InfluxQL features, such as `SOFFSET` are still
being implemented. For more information, see
[InfluxQL feature support](/influxdb/cloud-dedicated/reference/influxql/feature-support/).
{{% /warn %}}
<!-- The `SOFFSET` clause skips `N` [series](/influxdb/cloud-dedicated/reference/glossary/#series)
before returning results.
Offsets honor series limits specified in the
[`SLIMIT` clause](/influxdb/cloud-dedicated/reference/influxql/limit-and-slimit/#slimit-clause)
and display the limited number of series after the specified offset.
Use `SLIMIT` and `SOFFSET` together to paginate grouped query results.
The `SOFFSET` clause requires these other clauses:
- [`SLIMIT` clause](/influxdb/cloud-dedicated/reference/influxql/limit-and-slimit/#slimit-clause)
- [`GROUP BY` clause](/influxdb/cloud-dedicated/reference/influxql/group-by/) that
[groups by tags](/influxdb/cloud-dedicated/reference/influxql/group-by/#group-by-tags-examples)
### Syntax {#soffset-syntax}
```sql
SELECT_clause FROM_clause [WHERE_clause] GROUP_BY_clause [ORDER_BY_clause] [LIMIT_clause] [OFFSET_clause] SLIMIT_clause SOFFSET N
```
#### Arguments
- **N**: Number of [series](/influxdb/cloud-dedicated/reference/glossary/#series)
to skip before returning results.
{{% note %}}
**Note:**
{{% /note %}}
### Notable SOFFSET clause behaviors
- If there is no `SLIMIT` clause in a query with an `SOFFSET` clause, the query
returns no results.
- If the query doesn't include a [`GROUP BY` clause](/influxdb/cloud-dedicated/reference/influxql/group-by/),
the query returns no results.
- If the `SOFFSET` clause skips more than the total number of series, the query
returns no results.
### Examples {#soffset-examples}
The following examples use the
[Bitcoin price sample data](/influxdb/cloud-dedicated/reference/sample-data/#bitcoin-price-data).
{{< expand-wrapper >}}
{{% expand "Return the 2nd series" %}}
```sql
SELECT * FROM bitcoin GROUP BY * SLIMIT 1 SOFFSET 1
```
{{% influxql/table-meta %}}
name: bitcoin
tags: code=GBP, crypto=bitcoin, description=British Pound Sterling, symbol=&pound;
{{% /influxql/table-meta %}}
| time | price |
| :------------------- | ---------: |
| 2023-05-01T00:19:00Z | 24499.4816 |
| 2023-05-01T00:48:00Z | 24489.0637 |
| 2023-05-01T01:31:00Z | 24452.1698 |
| 2023-05-01T02:07:00Z | 23898.673 |
| 2023-05-01T02:26:00Z | 23900.9237 |
| ... | ... |
{{% /expand %}}
{{% expand "Paginate series by 2 and return the 2nd page of results" %}}
```sql
SELECT * FROM bitcoin GROUP BY * 2 SOFFSET 2
```
{{% note %}}
Because the **Bitcoin price sample data** contains only 3 series, when paginating
by 2, the 2nd "page" contains only one series.
{{% /note %}}
{{% influxql/table-meta %}}
name: bitcoin
tags: code=USD, crypto=bitcoin, description=United States Dollar, symbol=&#36;
{{% /influxql/table-meta %}}
| time | price |
| :------------------- | ---------: |
| 2023-05-01T00:19:00Z | 29319.9092 |
| 2023-05-01T00:48:00Z | 29307.4416 |
| 2023-05-01T01:31:00Z | 29263.2886 |
| 2023-05-01T02:07:00Z | 28600.8878 |
| 2023-05-01T02:26:00Z | 28603.5813 |
| ... | ... |
{{% /expand %}}
{{< /expand-wrapper >}} -->

View File

@ -13,97 +13,6 @@ list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] ORDER BY time [DESC|ASC]
```
source: /shared/influxql-v3-reference/order-by.md
---
Use the `ORDER BY` clause to sort data by time in ascending or descending order.
InfluxQL only supports sorting data by `time`.
- [Syntax](#syntax)
- [Examples](#examples)
## Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] ORDER BY time [ASC|DESC]
```
- If the the `ORDER BY` clause is not included, the default behavior is to sort data by
time in **ascending** order: `ORDER BY time ASC`.
- If the query includes [`WHERE`](/influxdb/cloud-dedicated/reference/influxql/where/)
and [`GROUP BY`](/influxdb/cloud-dedicated/reference/influxql/group-by/) clauses,
the `ORDER BY` clause must come **after** these clauses.
#### Sort orders
- **ASC (ascending)**: The first row in the results has the oldest timestamp.
The last row in the results has the most recent timestamp.
- **DESC (descending)**: The first row in the results has the most recent timestamp.
The last row in the results has the oldest timestamp.
## Examples
The following examples use the
[Get started home sensor sample data](/influxdb/cloud-dedicated/reference/sample-data/#get-started-home-sensor-data).
{{< expand-wrapper >}}
{{% expand "Sort data with the oldest points first" %}}
{{% note %}}
Ordering data by time in ascending order is the default behavior.
Including `ORDER BY time ASC` in the query isn't necessary, but it is supported.
{{% /note %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T12:00:00Z'
ORDER BY time ASC
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :------ | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T11:00:00Z | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T12:00:00Z | 0 | 36 | Kitchen | 22.5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Sort data with the newest points first" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T12:00:00Z'
ORDER BY time DESC
```
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :------ | ---: |
| 2022-01-01T12:00:00Z | 0 | 36 | Kitchen | 22.5 |
| 2022-01-01T11:00:00Z | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -17,48 +17,6 @@ list_code_example: |
-- Quoted identifier
"this-is-an-identifier"
```
source: /shared/influxql-v3-reference/quoting.md
---
InfluxQL supports both single and double quotation marks, but they each function
differently and serve different purposes.
- [Single quotes](#single-quotes)
- [Double quotes](#double-quotes)
## Single quotes
Use single quotation marks (`'`) in the
[string literal](/influxdb/cloud-dedicated/reference/influxql/#strings) and
[timestamp literal](/influxdb/cloud-dedicated/reference/influxql/#dates--times) syntax.
In the following example, the `WHERE` clause evaluates the value of the `room` tag.
Tags only contain string values, so the right operand of the predicate expression
should be a string literal.
```sql
... WHERE room = 'Kitchen'
```
## Double quotes
Use double quotation marks (`"`) to quote [identifiers](/influxdb/cloud-dedicated/reference/influxql/#identifiers).
Identifiers **must** be double-quoted in the following cases:
- The identifier contains non-word characters.
Word characters are defined as `[a-z,A-Z,0-9,_]`.
- The identifier is case-sensitive.
- The identifier contains [InfluxQL keywords](/influxdb/cloud-dedicated/reference/influxql/#keywords).
- The identifier begins with a digit.
Double-quoted identifiers can also:
- Contain any Unicode character except for a new line.
- Contain escaped `"` characters (for example: `\"`).
- Include [InfluxQL keywords](/influxdb/cloud-dedicated/reference/influxql/#keywords).
**While not always necessary, we recommend that you double quote identifiers.**
{{% note %}}
InfluxQL quoting guidelines differ from
[line protocol quoting guidelines](/influxdb/cloud-dedicated/reference/syntax/line-protocol/#quotes).
{{% /note %}}

View File

@ -13,198 +13,6 @@ list_code_example: |
```sql
SELECT /<regular_expression_field_key>/ FROM /<regular_expression_measurement>/ WHERE [<tag_key> <operator> /<regular_expression_tag_value>/ | <field_key> <operator> /<regular_expression_field_value>/] GROUP BY /<regular_expression_tag_key>/
```
source: /shared/influxql-v3-reference/regular-expressions.md
---
Regular expressions are a sequence of characters used to identify patterns in
identifiers and string values.
InfluxQL supports regular expressions in the following operations:
- Identifying **fields** and **tags** to query in the
[`SELECT` clause](/influxdb/cloud-dedicated/reference/influxql/select/).
- Identifying **measurements** to query in the
[`FROM` clause](/influxdb/cloud-dedicated/reference/influxql/select/#from-clause).
- Testing **tag values** and **string field values** in the
[`WHERE` clause](/influxdb/cloud-dedicated/reference/influxql/where/).
- Identifying **tag keys** to group by in the
[`GROUP BY` clause](/influxdb/cloud-dedicated/reference/influxql/group-by/)
{{% note %}}
#### Query performance
Regular expression comparisons are more computationally intensive than exact
string comparisons. Queries with regular expressions are not as performant
as those without.
{{% /note %}}
## Regular expression syntax
InfluxQL Regular expressions are surrounded by `/` characters and use the
[Go regular expression syntax](http://golang.org/pkg/regexp/syntax/).
```sql
/regular_expression/
```
### Regular expression flags
Regular expression flags modify the pattern-matching behavior of the expression.
InfluxQL supports the following regular expression flags:
| Flag | Description |
| :--- | :------------------------------------------------------------------------------ |
| i | case-insensitive |
| m | multi-line mode: `^` and `$` match begin/end line in addition to begin/end text |
| s | let `.` match `\n` |
| U | ungreedy: swap meaning of `x*` and `x*?`, `x+` and `x+?`, etc. |
Include regular expression flags at the beginning of your regular expression
pattern enclosed in parentheses (`()`) and preceded by a question mark (`?`).
```sql
/(?iU)foo*/
```
## Regular expression operators
InfluxQL provides the following regular expression operators that test if a
string operand matches a regular expression:
- `=~`: Returns true if the string matches the regular expression
- `!~`: Returns true if the string does not match the regular expression
InfluxQL regular expression operators are used to test string column values in
the [`WHERE` clause](/influxdb/cloud-dedicated/reference/influxql/where/).
## Regular expression examples
The examples below use the following sample data sets:
- [NOAA Bay Area weather data](/influxdb/cloud-dedicated/reference/sample-data/#noaa-bay-area-weather-data)
- [Get started home sensor data](/influxdb/cloud-dedicated/reference/sample-data/#get-started-home-sensor-data)
{{< expand-wrapper >}}
{{% expand "Use a regular expression to specify field keys and tag keys in the SELECT clause" %}}
```sql
SELECT /^t/ FROM weather
```
{{% influxql/table-meta %}}
name: weather
{{% /influxql/table-meta %}}
| time | temp_avg | temp_max | temp_min |
| :------------------- | -------: | -------: | -------: |
| 2020-01-01T00:00:00Z | 52 | 66 | 44 |
| 2020-01-01T00:00:00Z | 53 | 59 | 47 |
| 2020-01-01T00:00:00Z | 50 | 57 | 44 |
| 2020-01-02T00:00:00Z | 54 | 61 | 49 |
| 2020-01-02T00:00:00Z | 51 | 60 | 44 |
| 2020-01-02T00:00:00Z | 53 | 66 | 42 |
| ... | ... | ... | ... |
{{% /expand %}}
{{% expand "Use a regular expression to specify measurements in the FROM clause" %}}
```sql
SELECT /^t/ FROM /^[hw]/
```
{{% influxql/table-meta %}}
name: weather
{{% /influxql/table-meta %}}
| time | temp | temp_avg | temp_max | temp_min |
| :------------------- | ---: | -------: | -------: | -------: |
| 2020-01-01T00:00:00Z | | 52 | 66 | 44 |
| 2020-01-01T00:00:00Z | | 53 | 59 | 47 |
| 2020-01-01T00:00:00Z | | 50 | 57 | 44 |
| 2020-01-02T00:00:00Z | | 54 | 61 | 49 |
| 2020-01-02T00:00:00Z | | 51 | 60 | 44 |
| 2020-01-02T00:00:00Z | | 53 | 66 | 42 |
| ... | ... | ... | ... | ... |
{{% /expand %}}
{{% expand "Use a regular expression to specify tag values in the WHERE clause" %}}
```sql
SELECT * FROM weather WHERE location !~ /^[S]/
```
{{% influxql/table-meta %}}
name: weather
{{% /influxql/table-meta %}}
| time | location | precip | temp_avg | temp_max | temp_min | wind_avg |
| :------------------- | :------- | -----: | -------: | -------: | -------: | -------: |
| 2020-01-01T00:00:00Z | Concord | 0 | 52 | 66 | 44 | 3.13 |
| 2020-01-01T00:00:00Z | Hayward | 0 | 50 | 57 | 44 | 2.24 |
| 2020-01-02T00:00:00Z | Concord | 0 | 53 | 66 | 42 | 3.13 |
| 2020-01-02T00:00:00Z | Hayward | 0 | 51 | 60 | 44 | 3.8 |
| 2020-01-03T00:00:00Z | Concord | 0 | 49 | 60 | 38 | 2.68 |
| 2020-01-03T00:00:00Z | Hayward | 0 | 50 | 62 | 41 | 3.13 |
| ... | ... | ... | ... | ... | ... | ... |
{{% /expand %}}
{{% expand "Use a regular expression to specify a tag with no value in the WHERE clause" %}}
```sql
SELECT * FROM home, weather WHERE location !~ /./
```
{{% influxql/table-meta %}}
name: weather
{{% /influxql/table-meta %}}
| time | co | hum | location | precip | room | temp | temp_avg | temp_max | temp_min | wind_avg |
| :------------------- | --: | ---: | -------- | ------ | :---------- | ---: | -------- | -------- | -------- | -------- |
| 2022-01-01T08:00:00Z | 0 | 35.9 | | | Kitchen | 21 | | | | |
| 2022-01-01T08:00:00Z | 0 | 35.9 | | | Living Room | 21.1 | | | | |
| 2022-01-01T09:00:00Z | 0 | 36.2 | | | Kitchen | 23 | | | | |
| 2022-01-01T09:00:00Z | 0 | 35.9 | | | Living Room | 21.4 | | | | |
| 2022-01-01T10:00:00Z | 0 | 36.1 | | | Kitchen | 22.7 | | | | |
| 2022-01-01T10:00:00Z | 0 | 36 | | | Living Room | 21.8 | | | | |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
{{% /expand %}}
{{% expand "Use a regular expression to specify tag keys in the GROUP BY clause" %}}
```sql
SELECT MAX(precip) FROM weather GROUP BY /^l/
```
{{% influxql/table-meta %}}
name: weather
tags: location=Concord
{{% /influxql/table-meta %}}
| time | max |
| :------------------- | ---: |
| 2021-10-24T00:00:00Z | 4.53 |
{{% influxql/table-meta %}}
name: weather
tags: location=Hayward
{{% /influxql/table-meta %}}
| time | max |
| :------------------- | ---: |
| 2022-12-31T00:00:00Z | 4.34 |
{{% influxql/table-meta %}}
name: weather
tags: location=San Francisco
{{% /influxql/table-meta %}}
| time | max |
| :------------------- | ---: |
| 2021-10-24T00:00:00Z | 4.02 |
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -14,451 +14,6 @@ list_code_example: |
```sql
SELECT <field_key>[,<field_key>,<tag_key>] FROM <measurement_name>[,<measurement_name>]
```
source: /shared/influxql-v3-reference/select.md
---
Use the `SELECT` statement to query data from one or more
[measurements](/influxdb/cloud-dedicated/reference/glossary/#measurement).
The `SELECT` statement **requires** a [`SELECT` clause](#select-clause) and a
[`FROM` clause](#from-clause).
- [Syntax](#syntax)
- [SELECT clause](#select-clause)
- [FROM clause](#from-clause)
- [Notable SELECT statement behaviors](#notable-select-statement-behaviors)
- [Data types and casting operations](#data-types-and-casting-operations)
- [SELECT statement examples](#select-statement-examples)
<!-- - [Multiple statements](#multiple-statements) -->
## Syntax
```sql
SELECT field_expression[, ..., field_expression_n[, tag_expression[, ..., tag_expression_n]]] FROM measurement_expression[, ..., measurement_expression_n]
```
### SELECT clause
The `SELECT` clause supports several formats for identifying data to query.
It requires one or more **field expressions** and optional **tag expressions**.
- **field_expression**: Expression to identify one or more fields to return in query results.
Can be a [field key](/influxdb/cloud-dedicated/reference/glossary/#field-key),
constant, [regular expression](/influxdb/cloud-dedicated/reference/influxql/regular-expressions/),
[wildcard (`*`)](#wildcard-expressions-in-select-clauses), or
[function expression](/influxdb/cloud-dedicated/reference/influxql/functions/) and any
combination of arithmetic operators.
- **tag_expression**: Expression to identify one or more tags to return in query results.
Can be a [tag key](/influxdb/cloud-dedicated/reference/glossary/#tag-key) or constant.
#### Select clause behaviors
- `SELECT field_key` - Returns a specific field.
- `SELECT field_key1, field_key2` - Returns two specific fields.
- `SELECT field_key, tag_key` - Returns a specific field and tag.
- `SELECT *` - Returns all [fields](/influxdb/cloud-dedicated/reference/glossary/#field)
and [tags](/influxdb/cloud-dedicated/reference/glossary/#tag).
_See [Wildcard expressions](#wildcard-expressions)._
- `SELECT /^[t]/` - Returns all [fields](/influxdb/cloud-dedicated/reference/glossary/#field)
and [tags](/influxdb/cloud-dedicated/reference/glossary/#tag) with keys that
match the regular expression. At least one field key must match the regular
expression. If no field keys match the regular expression, no results are
returned.
### FROM clause
The `FROM` clause specifies the
[measurement](/influxdb/cloud-dedicated/reference/glossary/#measurement) or
[subquery](/influxdb/cloud-dedicated/reference/influxql/subqueries/) to query.
It requires one or more comma-delimited
[measurement expressions](#measurement_expression) or [subqueries](#subquery).
#### measurement_expression
A measurement expression identifies a measurement to query.
It can be a measurement name, fully-qualified measurement, constant, or
a [regular expression](/influxdb/cloud-dedicated/reference/influxql/regular-expressions/).
- **Measurement name**: When using just the measurement name, InfluxQL assumes
the default retention policy of the database specified in the query request.
```sql
FROM measurement
```
- **Fully-qualified measurement**: A fully qualified measurement includes a
database name, retention policy name, and measurement name, each separated by
a period (`.`). If the retention policy is not specified, InfluxQL uses the
default retention policy for the specified database.
```sql
FROM database.retention_policy.measurement
-- Fully-qualified measurement with default retention policy
FROM database..measurement
```
{{% note %}}
#### InfluxQL retention policies
In {{< product-name >}}, **retention policies** are not part of the data model
like they are in InfluxDB 1.x.
Each {{< product-name >}} database has a **retention period** which defines the
maximum age of data to retain in the database. To use fully-qualified
measurements in InfluxQL queries, use the following naming convention when
[creating a database](/influxdb/cloud-dedicated/admin/databases/create/):
```
database_name/retention_policy
```
{{% /note %}}
#### Subquery
An InfluxQL subquery is a query nested in the `FROM` clause of an InfluxQL query.
The outer query queries results returned by the inner query (subquery).
For more information, see [InfluxQL subqueries](/influxdb/cloud-dedicated/reference/influxql/subqueries/).
## Notable SELECT statement behaviors
- [Must query at least one field](#must-query-at-least-one-field)
- [Wildcard expressions](#wildcard-expressions)
- [Cannot include both aggregate and non-aggregate field expressions](#cannot-include-both-aggregate-and-non-aggregate-field-expressions)
### Must query at least one field
A query requires at least one [field key](/influxdb/cloud-dedicated/reference/glossary/#field-key)
in the `SELECT` clause to return data.
If the `SELECT` clause includes only [tag keys](/influxdb/cloud-dedicated/reference/glossary/#tag-key),
the query returns an empty result.
When using regular expressions in the `SELECT` clause, if regular expression
matches only tag keys and no field keys, the query returns an empty result.
To return data associated with tag keys, include at least one field key in the
`SELECT` clause.
### Wildcard expressions
When using a wildcard expression (`*`) in the `SELECT` clause, the query returns
all tags and fields.
If a [function](/influxdb/cloud-dedicated/reference/influxql/functions/) is
applied to a wildcard expression, the query returns all _fields_ with
the function applied, but does not return _tags_ unless they are included in
the `SELECT` clause.
### Cannot include both aggregate and non-aggregate field expressions
The `SELECT` statement cannot include an aggregate field expression
(one that uses an [aggregate](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/)
or [selector](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/)
function) **and** a non-aggregate field expression.
For example, in the following query, an aggregate function is applied to one
field, but not the other:
```sql
SELECT mean(temp), hum FROM home
```
This query returns an error.
For more information, see [error about mixing aggregate and non-aggregate queries](/enterprise_influxdb/v1/troubleshooting/errors/#error-parsing-query-mixing-aggregate-and-non-aggregate-queries-is-not-supported).
## Data types and casting operations
The [`SELECT` clause](#select-clause) supports specifying a
[field's](/influxdb/cloud-dedicated/reference/glossary/#field) type and basic
casting operations with the `::` syntax.
```sql
SELECT field_expression::type FROM measurement_expression
```
The `::` syntax allows users to perform basic cast operations in queries.
Currently, InfluxQL supports casting _numeric_ [field values](/influxdb/cloud-dedicated/reference/glossary/#field-value)
to other numeric types.
Casting to an **identifier type** acts as a filter on results and returns only
columns of that specific identifier type along with the `time` column.
{{< flex >}}
{{% flex-content "third" %}}
##### Numeric types
- `float`
- `integer`
- `unsigned`
{{% /flex-content %}}
{{% flex-content "third" %}}
##### Non-numeric types
- `string`
- `boolean`
{{% /flex-content %}}
{{% flex-content "third" %}}
##### Identifier types
- `field`
- `tag`
{{% /flex-content %}}
{{< /flex >}}
{{% note %}}
InfluxQL returns no data if the query attempts to cast a numeric value to a
non-numeric type and vice versa.
{{% /note %}}
When casting a float value to an integer or unsigned integer, the float value
is truncated at the decimal point. No rounding is performed.
## SELECT statement examples
The examples below use the following sample data sets:
- [Get started home sensor data](/influxdb/cloud-dedicated/reference/sample-data/#get-started-home-sensor-data)
- [NOAA Bay Area weather data](/influxdb/cloud-dedicated/reference/sample-data/#noaa-bay-area-weather-data)
{{< expand-wrapper >}}
{{% expand "Select all fields and tags from a measurement" %}}
```sql
SELECT * FROM home
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :---------- | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Living Room | 21.1 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T09:00:00Z | 0 | 35.9 | Living Room | 21.4 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T10:00:00Z | 0 | 36 | Living Room | 21.8 |
| ... | ... | ... | ... | ... |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select specific tags and fields from a measurement" %}}
```sql
SELECT temp, hum, room FROM home
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | temp | hum | room |
| :------------------- | ---: | ---: | :---------- |
| 2022-01-01T08:00:00Z | 21 | 35.9 | Kitchen |
| 2022-01-01T08:00:00Z | 21.1 | 35.9 | Living Room |
| 2022-01-01T09:00:00Z | 23 | 36.2 | Kitchen |
| 2022-01-01T09:00:00Z | 21.4 | 35.9 | Living Room |
| 2022-01-01T10:00:00Z | 22.7 | 36.1 | Kitchen |
| 2022-01-01T10:00:00Z | 21.8 | 36 | Living Room |
| ... | ... | ... | ... |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select all fields from a measurement" %}}
```sql
SELECT *::field FROM home
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | hum | temp |
| :------------------- | --: | ---: | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | 21 |
| 2022-01-01T08:00:00Z | 0 | 35.9 | 21.1 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | 23 |
| 2022-01-01T09:00:00Z | 0 | 35.9 | 21.4 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | 22.7 |
| 2022-01-01T10:00:00Z | 0 | 36 | 21.8 |
| ... | ... | ... | ... |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select a field from a measurement and perform basic arithmetic" %}}
```sql
SELECT (temp * (9 / 5)) + 32 FROM home
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | temp |
| :------------------- | ----------------: |
| 2022-01-01T08:00:00Z | 69.80000000000001 |
| 2022-01-01T08:00:00Z | 69.98 |
| 2022-01-01T09:00:00Z | 73.4 |
| 2022-01-01T09:00:00Z | 70.52 |
| 2022-01-01T10:00:00Z | 72.86 |
| 2022-01-01T10:00:00Z | 71.24000000000001 |
| ... | ... |
{{% /influxdb/custom-timestamps %}}
{{% note %}}
**Note:** InfluxDB follows the standard order of operations.
See [InfluxQL mathematical operators](/influxdb/cloud-dedicated/reference/influxql/math-operators/)
for more on supported operators.
{{% /note %}}
{{% /expand %}}
{{% expand "Select all data from more than one measurement" %}}
```sql
SELECT * FROM home, weather
```
{{% influxql/table-meta %}}
Name: weather
{{% /influxql/table-meta %}}
| time | co | hum | location | precip | room | temp | temp_avg | temp_max | temp_min | wind_avg |
| :------------------- | --: | --: | :------------ | -----: | :--- | ---: | -------: | -------: | -------: | -------: |
| 2020-01-01T00:00:00Z | | | Concord | 0 | | | 52 | 66 | 44 | 3.13 |
| 2020-01-01T00:00:00Z | | | San Francisco | 0 | | | 53 | 59 | 47 | 14.32 |
| 2020-01-01T00:00:00Z | | | Hayward | 0 | | | 50 | 57 | 44 | 2.24 |
| 2020-01-02T00:00:00Z | | | San Francisco | 0 | | | 54 | 61 | 49 | 5.82 |
| 2020-01-02T00:00:00Z | | | Hayward | 0 | | | 51 | 60 | 44 | 3.8 |
| 2020-01-02T00:00:00Z | | | Concord | 0 | | | 53 | 66 | 42 | 3.13 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
{{% /expand %}}
{{% expand "Select all data from a fully-qualified measurement (with default retention policy)" %}}
```sql
SELECT * FROM "get-started"..home
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :---------- | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Living Room | 21.1 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T09:00:00Z | 0 | 35.9 | Living Room | 21.4 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T10:00:00Z | 0 | 36 | Living Room | 21.8 |
| ... | ... | ... | ... | ... |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
### Type-casting examples
{{< expand-wrapper >}}
{{% expand "Cast an integer field to a float" %}}
```sql
SELECT co::float FROM home
```
{{% /expand %}}
{{% expand "Cast a float field to an integer" %}}
```sql
SELECT temp::integer FROM home
```
{{% /expand %}}
{{% expand "Cast a float field to an unsigned integer" %}}
```sql
SELECT temp::unsigned FROM home
```
{{% /expand %}}
{{< /expand-wrapper >}}
<!-- ## Multiple statements
Separate multiple `SELECT` statements in a query with a semicolon (`;`).
### Examples
The **InfluxDB v1 query API** returns a JSON response with a `statement_id`
field for each `SELECT` statement.
```json
{
"results": [
{
"statement_id": 0,
"series": [
{
"name": "h2o_feet",
"columns": [
"time",
"mean"
],
"values": [
[
"1970-01-01T00:00:00Z",
4.442107025822522
]
]
}
]
},
{
"statement_id": 1,
"series": [
{
"name": "h2o_feet",
"columns": [
"time",
"water_level"
],
"values": [
[
"2015-08-18T00:00:00Z",
8.12
],
[
"2015-08-18T00:00:00Z",
2.064
]
]
}
]
}
]
}
``` -->

View File

@ -14,153 +14,6 @@ list_code_example: |
```
related:
- /influxdb/cloud-dedicated/query-data/influxql/explore-schema/
source: /shared/influxql-v3-reference/show.md
---
Use InfluxQL `SHOW` statements to query schema information from a database.
- [SHOW RETENTION POLICIES](#show-retention-policies)
- [SHOW MEASUREMENTS](#show-measurements)
- [SHOW FIELD KEYS](#show-field-keys)
- [SHOW TAG KEYS](#show-tag-keys)
- [SHOW TAG VALUES](#show-tag-values)
## SHOW RETENTION POLICIES
Use the `SHOW RETENTION POLICIES` statement to list retention policies associated
with a database.
Each database has a single retention policy--`autogen`.
{{% note %}}
In {{< product-name >}}, retention policies are not part of the
data structure but are expected by InfluxQL and used in fully-qualified measurements
in the [`FROM` clause](/influxdb/cloud-dedicated/reference/influxql/select/#from-clause).
The data returned for each retention policy does not represent the actual
retention-related attributes of the database. The values are placeholder values
meant only for InfluxQL feature parity.
For information about database data retention, see
[List databases](/influxdb/cloud-dedicated/admin/databases/list/).
{{% /note %}}
```sql
SHOW RETENTION POLICIES [ON <database-name>]
```
#### Examples
```sql
-- Show retention policies in the database specified in the query request
SHOW RETENTION POLICIES
-- Show retention policies in a specific database
SHOW RETENTION POLICIES ON "example-database"
```
## SHOW MEASUREMENTS
Use the `SHOW MEASUREMENTS` statement to list measurements in a database.
```sql
SHOW MEASUREMENTS [with_measurement_clause] [where_clause] [limit_clause] [offset_clause]
```
#### Examples
```sql
-- Show all measurements
SHOW MEASUREMENTS
-- Show measurements where region tag = 'uswest' AND host tag = 'serverA'
SHOW MEASUREMENTS WHERE "region" = 'uswest' AND "host" = 'serverA'
-- Show measurements that start with 'h2o'
SHOW MEASUREMENTS WITH MEASUREMENT =~ /h2o.*/
```
## SHOW FIELD KEYS
Use the `SHOW FIELD KEYS` statement to list all field keys in a measurement.
```sql
SHOW FIELD KEYS [from_clause]
```
#### Examples
```sql
-- Show field keys and field value data types from all measurements
SHOW FIELD KEYS
-- Show field keys and field value data types from specified measurement
SHOW FIELD KEYS FROM "cpu"
```
## SHOW TAG KEYS
Use the `SHOW TAG KEYS` statement to list tag keys in a measurement.
```sql
SHOW TAG KEYS [from_clause] [where_clause] [limit_clause] [offset_clause]
```
#### Examples
```sql
-- Show all tag keys
SHOW TAG KEYS
-- Show all tag keys from the cpu measurement
SHOW TAG KEYS FROM "cpu"
-- Show all tag keys from the cpu measurement where the region key = 'uswest'
SHOW TAG KEYS FROM "cpu" WHERE "region" = 'uswest'
-- Show all tag keys where the host key = 'serverA'
SHOW TAG KEYS WHERE "host" = 'serverA'
```
## SHOW TAG VALUES
Use the `SHOW TAG VALUES` statement to list values of specified tags in a database.
```sql
SHOW TAG VALUES [from_clause] WITH KEY = <tag-expression> [where_clause] [limit_clause] [offset_clause]
```
By default, the `SHOW TAG VALUES` statement only returns unique tag values from
**the last day**. To modify the time range, include a
[`WHERE` clause with a time-based predicate](/influxdb/cloud-dedicated/reference/influxql/where/#time-ranges).
{{% note %}}
#### Include a FROM clause
We strongly recommend including a `FROM` clause with the `SHOW TAG VALUES`
statement that specifies 1-50 tables to query.
Without a `FROM` clause, the InfluxDB query engine must read data from all
tables and return unique tag values from each.
Depending on the number of tables in your database and the number of unique tag
values in each table, excluding a `FROM` clause can result in poor query performance,
query timeouts, or unnecessary resource allocation that may affect other queries.
{{% /note %}}
#### Examples
```sql
-- Show tag values from the cpu measurement for the region tag
SHOW TAG VALUES FROM "cpu" WITH KEY = "region"
-- Show tag values from the cpu measurement for the region tag for a custom time range
SHOW TAG VALUES FROM "cpu" WITH KEY = "region" WHERE time > -7d
-- Show tag values from multiple measurements for the region tag
SHOW TAG VALUES FROM "cpu", "memory", "disk" WITH KEY = "region"
-- Show tag values from the cpu measurement for all tag keys that do not include the letter c
SHOW TAG VALUES FROM "cpu" WITH KEY !~ /.*c.*/
-- Show tag values from the cpu measurement for region & host tag keys where service = 'redis'
SHOW TAG VALUES FROM "cpu" WITH KEY IN ("region", "host") WHERE "service" = 'redis'
```

View File

@ -13,234 +13,6 @@ list_code_example: |
```sql
SELECT_clause FROM ( SELECT_statement ) [...]
```
source: /shared/influxql-v3-reference/subqueries.md
---
An InfluxQL subquery is a query nested in the `FROM` clause of an InfluxQL query.
The outer query queries results returned by the inner query (subquery).
- [Syntax](#syntax)
- [Examples](#examples)
- [Notable subquery behaviors](#notable-subquery-behaviors)
{{% note %}}
InfluxQL does not support a `HAVING` clause, however InfluxQL subqueries offer
functionality similar to the [SQL `HAVING` clause](/influxdb/cloud-dedicated/reference/sql/having/).
{{% /note %}}
## Syntax
```sql
SELECT_clause FROM ( SELECT_statement ) [...]
```
When using subqueries, InfluxQL **performs the inner query first**, then performs
the outer query.
The outer query requires a [`SELECT` clause](/influxdb/cloud-dedicated/reference/influxql/select/#select-clause)
and a [`FROM` clause](/influxdb/cloud-dedicated/reference/influxql/select/#from-clause).
The inner query is enclosed in parentheses in the outer query's `FROM` clause.
InfluxQL supports multiple nested subqueries:
```sql
SELECT_clause FROM ( SELECT_clause FROM ( SELECT_statement ) [...] ) [...]
```
## Examples
{{% note %}}
#### Sample data
The examples below use the following sample data sets:
- [Get started home sensor data](/influxdb/cloud-dedicated/reference/sample-data/#get-started-home-sensor-data)
- [Random numbers sample data](/influxdb/cloud-dedicated/reference/sample-data/#random-numbers-sample-data)
{{% /note %}}
{{< expand-wrapper >}}
{{% expand "Apply an aggregate function to an aggregated result set" %}}
```sql
SELECT
SUM(max)
FROM
(
SELECT
MAX(temp)
FROM
home
GROUP BY
room
)
```
{{% influxql/table-meta %}}
Table: home
{{% /influxql/table-meta %}}
| time | sum |
| :------------------- | ---: |
| 1970-01-01T00:00:00Z | 46.1 |
{{% /expand %}}
{{% expand "Calculate the average difference between two fields" %}}
```sql
SELECT
MEAN(difference)
FROM
(
SELECT
a - b AS difference
FROM
numbers
)
```
{{% influxql/table-meta %}}
Table: numbers
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -------------------: |
| 1970-01-01T00:00:00Z | -0.03629771779732732 |
{{% /expand %}}
{{% expand "Filter aggregate values based on a threshold" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
co_change
FROM
(
SELECT
SPREAD(co) AS co_change
FROM
home
GROUP BY
room,
time(2h)
)
WHERE
time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
AND co_change >= 4
```
{{% influxql/table-meta %}}
Table: home
{{% /influxql/table-meta %}}
| time | co_chnage |
| :------------------- | --------: |
| 2022-01-01T18:00:00Z | 4 |
| 2022-01-01T18:00:00Z | 5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Perform additional aggregate operations on aggregate values" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
SUM(co_derivative) AS sum_derivative
FROM
(
SELECT
DERIVATIVE(MEAN(co)) AS co_derivative
FROM
home
GROUP BY
time(12m),
room
)
WHERE
time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY
room
```
{{% /influxdb/custom-timestamps %}}
{{% influxql/table-meta %}}
Table: home
{{% /influxql/table-meta %}}
| time | room | sum_derivative |
| :------------------- | :---------- | -------------: |
| 1970-01-01T00:00:00Z | Kitchen | 5.2 |
| 1970-01-01T00:00:00Z | Living Room | 3.4 |
{{% /expand %}}
{{< /expand-wrapper >}}
## Notable subquery behaviors
- [Apply time bounds to the outer query to improve performance](#apply-time-bounds-to-the-outer-query-to-improve-performance)
- [Cannot use multiple SELECT statements in a subquery](#cannot-use-multiple-select-statements-in-a-subquery)
### Apply time bounds to the outer query to improve performance
To improve the performance of InfluxQL queries that use subqueries and a
specified time range, apply the `WHERE` clause with time-based predicates to the
outer query rather than the inner query.
For example--the following queries return the same results, but **the query with
time-based predicate on the outer query is more performant than the query with
time-based predicate on the inner query**:
{{% influxdb/custom-timestamps %}}
#### Time bounds on the outer query {note="(Recommended)"}
```sql
SELECT
inner_value AS value
FROM
(
SELECT
raw_value as inner_value
)
WHERE
time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
```
#### Time bounds on the inner query
```sql
SELECT
inner_value AS value
FROM
(
SELECT
raw_value as inner_value
WHERE
time >= '2022-07-19T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
)
```
{{% /influxdb/custom-timestamps %}}
### Cannot use multiple SELECT statements in a subquery
InfluxQL does not support multiple
[`SELECT` statements](/influxdb/cloud-dedicated/reference/influxql/select/)
per subquery:
```sql
SELECT_clause FROM (SELECT_statement; SELECT_statement) [...]
```
However, InfluxQL does support multiple nested subqueries per outer query:
```sql
SELECT_clause FROM ( SELECT_clause FROM ( SELECT_statement ) [...] ) [...]
------------------ ----------------
Subquery 1 Subquery 2
```

View File

@ -13,362 +13,6 @@ list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] [LIMIT_clause] [OFFSET_clause] [SLIMIT_clause] [SOFFSET_clause] tz('<time_zone>')
```
source: /shared/influxql-v3-reference/time-and-timezone.md
---
InfluxQL is designed for working with time series data and includes features specifically for working with time.
You can review the following ways to work with time and timestamps in your InfluxQL queries:
- [Time syntax](#time-syntax)
- [Add and subtract time values](#add-and-subtract-time-values)
- [Query time range](#query-time-range)
- [Supported operators](#supported-operators)
- [Query examples](#query-examples)
- [Time zone clause](#time-zone-clause)
- [Notable behaviors](#notable-behaviors)
- [Cannot query multiple time ranges](#cannot-query-multiple-time-ranges)
- [Querying future data with a `GROUP BY time()` clause](#querying-future-data-with-a-group-by-time-clause)
- [Cannot use parameters for durations](#cannot-use-parameters-for-durations)
## Time syntax
InfluxQL supports the following timestamp literal syntaxes:
```sql
'2006-01-02T15:04:05.00Z' -- RFC3339 date-time string
'2006-01-02 15:04:05.00' -- RFC3339-like date-time string
1136189045000000000 -- Unix nanosecond epoch time
1136189045s -- Unix epoch time
```
- **RFC3339 date-time string**:
[String literal](/influxdb/cloud-dedicated/reference/influxql/#strings) using
the RFC3339 timestamp format, `YYYY-MM-DDTHH:MM:SS.nnnnnnnnnZ`.
- **RFC3339-like date-time string**:
[String literal](/influxdb/cloud-dedicated/reference/influxql/#strings) using
the RFC3339-like timestamp format, `YYYY-MM-DD HH:MM:SS.nnnnnnnnn`.
- **Unix nanosecond epoch time**:
[Integer](/influxdb/cloud-dedicated/reference/influxql/#integers) that
represents the number of nanoseconds elapsed since the
[Unix epoch](/influxdb/cloud-dedicated/reference/glossary/#unix-epoch).
- **Unix epoch time**:
[Duration literal](/influxdb/cloud-dedicated/reference/influxql/#durations)
that represents the number of specified time units elapsed since the
[Unix epoch](/influxdb/cloud-dedicated/reference/glossary/#unix-epoch).
_[View supported duration units](/influxdb/cloud-dedicated/reference/influxql/#durations)_.
##### Supported timestamp values
| | RFC3339 | Unix nanosecond time |
| ----------- | :----------------------------: | -------------------: |
| **Maximum** | 2262-04-11T23:47:16.854775807Z | 9223372036854775807 |
| **Minimum** | 1677-09-21T00:12:43.145224193Z | -9223372036854775807 |
### Add and subtract time values
Timestamp values support addition and subtraction operations with
[duration literals](/influxdb/cloud-dedicated/reference/influxql/#durations).
Add (`+`) or subtract (`-`) a duration to or from a timestamp to return an
updated timestamp.
```sql
'2023-01-01T00:00:00Z' + 2h -- Resolves to 2023-01-01T02:00:00Z
'2023-01-01 00:00:00' - 20h -- Resolves to 2022-12-31T04:00:00Z
1672531200000000000 + 1y -- Resolves to 2024-01-01T00:00:00Z
```
{{% note %}}
InfluxQL requires a whitespace between the `+` operators `-` and the duration literal.
{{% /note %}}
## Query time range
To specify the time range of a query, use conditional expressions in the
[`WHERE` clause](/inflxudb/cloud-dedicated/reference/influxql/where/) that
compare the value of the `time` column to an absolute timestamp or a relative
timestamp.
- **Absolute time range**: Define query time bounds with timestamp literals
```sql
WHERE time >= '2023-01-01T00:00:00Z' AND time <= '2023-07-01T00:00:00Z'
WHERE time >= '2023-01-01 00:00:00' AND time <= '2023-07-01 00:00:00'
WHERE time >= 1672531200000000000 AND time <= 1688169600000000000
WHERE time >= 1672531200s and time <= 1688169600000ms
```
- **Relative time range**: Define query time bounds with a duration literal
added to or subtracted from timestamp literals.
{{% note %}}
Use `now()` to return the current system time (UTC).
{{% /note %}}
```sql
-- Query data from the last day
WHERE time >= now() - 1d
-- Query data from the previous week
WHERE time >= now() - 1w AND time <= now() - 2w
-- Query data relative to a specific time
WHERE time >= '2023-01-01' - 1w AND time <= '2023-01-01' + 1w
```
### Supported operators
Conditional expressions with time operands support the following comparison operators:
| Operator | Meaning |
|:--------:|:------- |
| `=` | equal to |
| `<>` | not equal to |
| `!=` | not equal to |
| `>` | greater than |
| `>=` | greater than or equal to |
| `<` | less than |
| `<=` | less than or equal to |
{{% note %}}
Currently, InfluxQL supports the `AND` logical operator to define query time bounds,
but does not support using the `OR` logical operator to query multiple time ranges.
{{% /note %}}
## Query examples
The following examples use the
[Get started home sensor sample dataset](/influxdb/cloud-dedicated/reference/sample-data/#get-started-home-sensor-data).
{{< expand-wrapper >}}
{{% expand "Specify a time range with RFC3339 date-time strings" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T12:00:00Z'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :------ | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T11:00:00Z | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T12:00:00Z | 0 | 36 | Kitchen | 22.5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Specify a time range with RFC3339-like date-time strings" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01 08:00:00'
AND time <= '2022-01-01 12:00:00'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :------ | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T11:00:00Z | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T12:00:00Z | 0 | 36 | Kitchen | 22.5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Specify a time range with nanosecond epoch timestamps" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= 1641024000000000000
AND time <= 1641038400000000000
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :------ | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T11:00:00Z | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T12:00:00Z | 0 | 36 | Kitchen | 22.5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Specify a time range with second-precision epoch timestamps" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= 1641024000s
AND time <= 1641038400s
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :------ | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T11:00:00Z | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T12:00:00Z | 0 | 36 | Kitchen | 22.5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Specify a time range relative to a timestamp" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT * FROM home WHERE time >= '2022-01-01T20:00:00Z' - 2h
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :---------- | ---: |
| 2022-01-01T18:00:00Z | 18 | 36.9 | Kitchen | 23.3 |
| 2022-01-01T18:00:00Z | 9 | 36.2 | Living Room | 22.8 |
| 2022-01-01T19:00:00Z | 22 | 36.6 | Kitchen | 23.1 |
| 2022-01-01T19:00:00Z | 14 | 36.3 | Living Room | 22.5 |
| 2022-01-01T20:00:00Z | 26 | 36.5 | Kitchen | 22.7 |
| 2022-01-01T20:00:00Z | 17 | 36.4 | Living Room | 22.2 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Specify a time range relative to now" %}}
```sql
SELECT * FROM home WHERE time >= now() - 2h
```
{{% /expand %}}
{{< /expand-wrapper >}}
## Time zone clause
By default, InfluxDB stores and returns timestamps in UTC.
Use the time zone clause and the `tz()` function to apply a time zone offset to
UTC times and return timestamps in the specified time zone including any applicable
seasonal offset such as Daylight Savings Time (DST) or British Summer Time (BST).
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] [LIMIT_clause] [OFFSET_clause] [SLIMIT_clause] [SOFFSET_clause] tz('time_zone')
```
- **time_zone**: Time zone string literal to adjust times to.
Uses time zone names defined in the
[Internet Assigned Numbers Authority time zone database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List).
### Time zone example
{{< expand-wrapper >}}
{{% expand "Return the UTC offset for Chicago's time zone" %}}
{{% influxdb/custom-timestamps %}}
The following example uses the
[Get started home sensor sample dataset](/influxdb/cloud-dedicated/reference/sample-data/#get-started-home-sensor-data).
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T12:00:00Z'
tz('America/Chicago')
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------------ | --: | ---: | :------ | ---: |
| 2022-01-01T02:00:00-06:00 | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T03:00:00-06:00 | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T04:00:00-06:00 | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T05:00:00-06:00 | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T06:00:00-06:00 | 0 | 36 | Kitchen | 22.5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## Notable behaviors
- [Cannot query multiple time ranges](#cannot-query-multiple-time-ranges)
- [Querying future data with a `GROUP BY time()` clause](#querying-future-data-with-a-group-by-time-clause)
- [Cannot use parameters for durations](#cannot-use-parameters-for-durations)
### Cannot query multiple time ranges
InfluxDB does not support using `OR` in the `WHERE` clause to query multiple time ranges.
For example, the following query returns no results:
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
(time >= '2022-01-01T08:00:00Z' AND time <= '2022-01-01T10:00:00Z')
OR (time >= '2022-01-01T18:00:00Z' AND time <= '2022-01-01T20:00:00Z')
```
{{% /influxdb/custom-timestamps %}}
### Querying future data with a `GROUP BY time()` clause
Queries that do not specify time bounds in the `WHERE` clause and do not include
a `GROUP BY time()` clause use the [minimum and maximum timestamps](#supported-timestamp-values)
as the default time range.
If the query includes a `GROUP BY time()` clause, the default time range is
between `1677-09-21T00:12:43.145224193Z` and
[`now()`](/influxdb/cloud-dedicated/reference/influxql/functions/date-time/#now).
To query data with timestamps that occur in the future (after `now()`),
provide an explicit upper bound in the `WHERE` clause.
### Cannot use parameters for durations
Currently, InfluxDB doesn't support using parameters for durations in
[parameterized queries](/influxdb/cloud-dedicated/query-data/parameterized-queries/).

View File

@ -12,359 +12,6 @@ list_code_example: |
```sql
SELECT_clause FROM_clause WHERE <conditional_expression> [(AND|OR) <conditional_expression> [...]]
```
source: /shared/influxql-v3-reference/where.md
---
Use the `WHERE` clause to filter data based on
[field values](/influxdb/cloud-dedicated/reference/glossary/#field),
[tag values](/influxdb/cloud-dedicated/reference/glossary/#tag), and
[timestamps](/influxdb/cloud-dedicated/reference/glossary/#timestamp).
- [Syntax](#syntax)
- [Operators](#comparison-operators)
- [Comparison operators](#comparison-operators)
- [Logical operators](#logical-operators)
- [Time ranges](#time-ranges)
- [Regular expressions](#regular-expressions)
- [WHERE clause examples](#where-clause-examples)
- [Notable behaviors](#notable-behaviors)
- [Single and double quotes](#single-and-double-quotes)
- [Cannot query multiple time ranges](#cannot-query-multiple-time-ranges)
## Syntax
```sql
SELECT_clause FROM_clause WHERE <conditional_expression> [(AND|OR) <conditional_expression> [...]]
```
- **conditional_expression**: Comparison between two operands that evaluates to
`true` or `false`. Comparison logic is determined by
[operators](#operators) used in the expression.
These expressions can operate on InfluxDB fields, tags, and timestamps.
Use logical operators (`AND`, `OR`) to chain multiple conditional expressions
together.
## Operators
Operators evaluate the relationship between two operands and return
`true` or `false`.
### Comparison operators
| Operator | Meaning | Supported data types |
| :------: | :--------------------------------- | :---------------------- |
| `=` | Equal to | all |
| `<>` | Not equal to | all |
| `!=` | Not equal to | all |
| `>` | Greater than | numeric, timestamp |
| `>=` | Greater than or equal to | numeric, timestamp |
| `<` | Less than | numeric, timestamp |
| `<=` | Less than or equal to | numeric, timestamp |
| `=~` | Matches a regular expression | strings |
| `!~` | Doesn't match a regular expression | strings |
### Logical operators
| Operator | Meaning |
| :------- | :---------------------------------------------------------------------- |
| `AND` | Returns `true` if both operands are `true`. Otherwise, returns `false`. |
| `OR` | Returns `true` if any operand is `true`. Otherwise, returns `false`. |
## Time ranges
Use the `WHERE` clause to specify a time range to query.
If a time range isn't specified in the `WHERE` clause, the [default time range](/influxdb/cloud-dedicated/reference/influxql/#default-time-range) is used.
Timestamps are stored in the `time` column.
Use comparison operators to compare the value of the `time` column to a
timestamp literal, integer (Unix nanosecond timestamp), or [expression](/influxdb/cloud-dedicated/reference/glossary/#expression).
{{< code-tabs-wrapper >}}
{{% code-tabs %}}
[Timestamp](#)
[Integer](#)
[Expression](#)
{{% /code-tabs %}}
{{% code-tab-content %}}
```sql
WHERE
time >= '2023-01-01T00:00:00Z'
AND time < '2023-07-01T00:00:00Z'
```
{{% /code-tab-content %}}
{{% code-tab-content %}}
```sql
WHERE
time >= 1672531200000000000
AND time < 1688169600000000000
```
{{% /code-tab-content %}}
{{% code-tab-content %}}
```sql
WHERE
time >= now() - 1d
AND time < now()
```
{{% /code-tab-content %}}
{{< /code-tabs-wrapper >}}
See [Time syntax](/influxdb/cloud-dedicated/reference/influxql/time-and-timezone/#time-syntax)
for information on how to specify alternative time ranges in the `WHERE` clause.
{{% note %}}
InfluxQL [does not support querying multiple time ranges](#cannot-query-multiple-time-ranges).
{{% /note %}}
## Regular expressions
Regular expressions can be used to evaluate _string_ values in the `WHERE` clause
using regular expression comparison operators:
- `=~`: Matches a regular expression
- `!~`: Doesn't match a regular expression
```sql
SELECT * FROM home WHERE room =~ /^K/
```
For more information about InfluxQL regular expression syntax, see
[InfluxQL regular expressions](/influxdb/cloud-dedicated/reference/influxql/regular-expressions/).
## WHERE clause examples
The following examples use the
[Get started home sensor sample dataset](/influxdb/cloud-dedicated/reference/sample-data/#get-started-home-sensor-data).
{{< expand-wrapper >}}
{{% expand "Select data with a specific tag value" %}}
```sql
SELECT * FROM home WHERE room = 'Living Room'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :---------- | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Living Room | 21.1 |
| 2022-01-01T09:00:00Z | 0 | 35.9 | Living Room | 21.4 |
| 2022-01-01T10:00:00Z | 0 | 36 | Living Room | 21.8 |
| 2022-01-01T11:00:00Z | 0 | 36 | Living Room | 22.2 |
| 2022-01-01T12:00:00Z | 0 | 35.9 | Living Room | 22.2 |
| ... | ... | ... | ... | ... |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select data from a specific time range" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T10:00:00Z'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :---------- | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Living Room | 21.1 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T09:00:00Z | 0 | 35.9 | Living Room | 21.4 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T10:00:00Z | 0 | 36 | Living Room | 21.8 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select data from a relative time range" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT * FROM home WHERE time >= '2022-01-01T20:00:00Z' - 2h
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :---------- | ---: |
| 2022-01-01T18:00:00Z | 18 | 36.9 | Kitchen | 23.3 |
| 2022-01-01T18:00:00Z | 9 | 36.2 | Living Room | 22.8 |
| 2022-01-01T19:00:00Z | 22 | 36.6 | Kitchen | 23.1 |
| 2022-01-01T19:00:00Z | 14 | 36.3 | Living Room | 22.5 |
| 2022-01-01T20:00:00Z | 26 | 36.5 | Kitchen | 22.7 |
| 2022-01-01T20:00:00Z | 17 | 36.4 | Living Room | 22.2 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select field values above a threshold" %}}
```sql
SELECT co FROM home WHERE co > 9
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co |
| :------------------- | --: |
| 2022-01-01T18:00:00Z | 18 |
| 2022-01-01T19:00:00Z | 14 |
| 2022-01-01T19:00:00Z | 22 |
| 2022-01-01T20:00:00Z | 17 |
| 2022-01-01T20:00:00Z | 26 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select specific field values" %}}
```sql
SELECT room, co FROM home WHERE co = 9
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | room | co |
| :------------------- | :---------- | --: |
| 2022-01-01T17:00:00Z | Kitchen | 9 |
| 2022-01-01T18:00:00Z | Living Room | 9 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select field values based on arithmetic" %}}
```sql
SELECT room, co FROM home WHERE co - 10 > 5
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | room | co |
| :------------------- | :---------- | --: |
| 2022-01-01T18:00:00Z | Kitchen | 18 |
| 2022-01-01T19:00:00Z | Kitchen | 22 |
| 2022-01-01T20:00:00Z | Living Room | 17 |
| 2022-01-01T20:00:00Z | Kitchen | 26 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select data with field values above a threshold and a specific tag value" %}}
```sql
SELECT * FROM home WHERE temp > 22.7 AND room = 'Kitchen'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :------ | ---: |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T13:00:00Z | 1 | 36.5 | Kitchen | 22.8 |
| 2022-01-01T14:00:00Z | 1 | 36.3 | Kitchen | 22.8 |
| 2022-01-01T18:00:00Z | 18 | 36.9 | Kitchen | 23.3 |
| 2022-01-01T19:00:00Z | 22 | 36.6 | Kitchen | 23.1 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select data based on the relationship between columns" %}}
```sql
SELECT co, temp FROM home WHERE co > temp
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | temp |
| :------------------- | --: | ---: |
| 2022-01-01T20:00:00Z | 26 | 22.7 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## Notable behaviors
- [Single and double quotes](#single-and-double-quotes)
- [Cannot query multiple time ranges](#cannot-query-multiple-time-ranges)
### Single and double quotes
In InfluxQL, single quotation marks (`'`) and double quotation marks (`"`) work
differently and can alter the way a `WHERE` clause functions.
Single quotes are used in [string](/influxdb/cloud-dedicated/reference/influxql/#strings)
and [timestamp](/influxdb/cloud-dedicated/reference/influxql/#dates--times) literals.
Double quotes are used to quote [identifiers](/influxdb/cloud-dedicated/reference/influxql/#identifiers),
(time, field, and tag column names).
For example, the following conditional expression compares the value of the
`location` _column_ to the _literal string_, `London`:
```sql
"location" = 'London'
```
The following conditional expression compares the value of the `location` _column_
to the value of the `London` _column_:
```sql
"location" = "London"
```
Misused double and single quotes in the `WHERE` clause often results in unexpected
empty query results.
For more information about quotation marks, see
[InfluxQL quotation](/influxdb/cloud-dedicated/reference/influxql/quoting/).
### Cannot query multiple time ranges
InfluxDB does not support using `OR` in the `WHERE` clause to query multiple time ranges.
For example, the following query returns no results:
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
(time >= '2022-01-01T08:00:00Z' AND time <= '2022-01-01T10:00:00Z')
OR (time >= '2022-01-01T18:00:00Z' AND time <= '2022-01-01T20:00:00Z')
```
{{% /influxdb/custom-timestamps %}}

View File

@ -9,689 +9,10 @@ menu:
weight: 101
related:
- /influxdb/cloud-dedicated/reference/internals/arrow-flightsql/
source: /content/shared/sql-reference/_index.md
---
{{% product-name %}} uses the [Apache Arrow DataFusion](https://arrow.apache.org/datafusion/) implementation of SQL.
- [Identifiers](#identifiers)
- [Quoting and case sensitivity](#quoting-and-case-sensitivity)
- [Literals](#literals)
- [Duration units](#duration-units)
- [Operators](#operators)
- [Keywords](#keywords)
- [Conditional expressions](#conditional-expressions)
- [Statements and clauses](#statements-and-clauses)
- [Comments](#comments)
- [Functions](#functions)
## Identifiers
An identifier is a token which refers to the name of an InfluxDB database object, such as a **measurement** or a column name (**time**, **tag keys**, or **field keys**).
## Quoting
Use double quotes on [identifiers](#identifiers) to treat them as case-sensitive.
Use single quotes on string literals.
General quoting guidelines:
- Single quote RFC3339 and RFC3339-like time values.
- Do _not_ quote Unix epoch time values (integers cast to a timestamp).
- Double-quote mixed case, [camel case](https://en.wikipedia.org/wiki/Camel_case) or case-sensitive identifiers.
- Double-quote identifiers that contain special characters or whitespace characters.
##### Quoting examples
```sql
-- Double-quote identifiers that contain whitespace
SELECT "water temperature", "buoy location" FROM buoy
-- Double-quote measurement names with special characters
SELECT * FROM "h2o-temperature"
-- Double-quote identifiers that should be treated as case-sensitive
SELECT "pH" FROM "Water"
```
{{% note %}}
**Note:** We recommend always double-quoting identifiers, regardless of case-sensitivity.
{{% /note %}}
Unquoted identifiers **are not** case-sensitive and match any measurement, tag key, or field key with the same characters, despite case.
For example, if you have two fields in a measurement named `ph` and `pH`, the unquoted identifier, `pH` will match both.
To query in a case-sensitive manner, double-quote identifiers.
## Literals
A literal is an explicit value not represented by an identifier.
### String literals
String literals are surrounded by single quotes.
```sql
'santa_monica'
'pH'
'average temperature'
```
### Numeric literals
Number literals are positive or negative numbers that are either exact numbers or floats.
```sql
-- Integers
10
+10
-10
-- Unsigned integers
10::BIGINT UNSIGNED
+10::BIGINT UNSIGNED
-- Floats
10.78654
-100.56
```
### Date and time literals
The following date and time literals are supported:
```sql
'2022-01-31T06:30:30.123Z' -- (RFC3339)
'2022-01-31T06:30:30.123' -- (RFC3339-like)
'2022-01-31 06:30:30.123' -- (RFC3339-like)
'2022-01-31 06:30:30' -- ((RFC3339-like, no fractional seconds)
1643610630123000000::TIMESTAMP -- (Unix epoch nanosecond cast to a timestamp)
```
### Boolean literals
Boolean literals are either `TRUE` or `FALSE`.
## Duration units
Interval literals specify a length or unit of time.
```sql
INTERVAL '4 minutes'
INTERVAL '12 days 6 hours 30 minutes'
```
The following units of time are supported:
- nanoseconds
- microseconds
- milliseconds
- seconds
- minutes
- hours
- days
- weeks
- months
- years
- century
## Operators
Operators are reserved words or characters which perform certain operations, including comparisons and arithmetic.
### Arithmetic operators
Arithmetic operators take two numeric values (either literals or variables) and
perform a calculation that returns a single numeric value.
| Operator | Description | Example | Result |
| :------: | :------------- | ------- | -----: |
| `+` | Addition | `2 + 2` | `4` |
| `-` | Subtraction | `4 - 2` | `2` |
| `*` | Multiplication | `2 * 3` | `6` |
| `/` | Division | `6 / 3` | `2` |
| `%` | Modulo | `7 % 2` | `1` |
### Comparison operators
Comparison operators evaluate the relationship between the left and right operands and `TRUE` or `FALSE`.
| Operator | Meaning | Example |
| :------: | :------------------------------------------------------- | :----------------- |
| `=` | Equal to | `123 = 123` |
| `<>` | Not equal to | `123 <> 456` |
| `!=` | Not equal to | `123 != 456` |
| `>` | Greater than | `3 > 2` |
| `>=` | Greater than or equal to | `3 >= 2` |
| `<` | Less than | `1 < 2` |
| `<=` | Less than or equal to | `1 <= 2` |
| `~` | Matches a regular expression | `'abc' ~ 'a.*'` |
| `~\*` | Matches a regular expression _(case-insensitive)_ | `'Abc' ~\* 'A.*'` |
| `!~` | Does not match a regular expression | `'abc' !~ 'd.*'` |
| `!~\*` | Does not match a regular expression _(case-insensitive)_ | `'Abc' !~\* 'a.*'` |
### Logical operators
| Operator | Meaning |
| :-------: | :------------------------------------------------------------------------- |
| `AND` | Returns true if both operands are true. Otherwise, returns false. |
| `BETWEEN` | Returns true if the left operand is within the range of the right operand. |
| `EXISTS` | Returns true if the operand is not null. |
| `IN` | Returns true if the left operand is in the right operand list. |
| `LIKE` | Returns true if the left operand matches the right operand pattern string. |
| `NOT` | Negates the subsequent expression. |
| `OR` | Returns true if any operand is true. Otherwise, returns false. |
### Bitwise operators
Bitwise operators perform bitwise operations on bit patterns or binary numerals.
| Operator | Meaning | Example | Result |
| :------: | :------------------ | :------- | -----: |
| `&` | Bitwise and | `5 & 3` | `1` |
| `\|` | Bitwise or | `5 \| 3` | `7` |
| `^` | Bitwise xor | `5 ^ 3` | `6` |
| `>>` | Bitwise shift right | `5 >> 3` | `0` |
| `<<` | Bitwise shift left | `5 << 3` | `40` |
### Other operators
| Operator | Meaning | Example | Result |
| :------------: | :----------------------- | :-------------------------------------------------------------------------------------- | :------------ |
| `\|\|` | Concatenates strings | `'Hello' \|\| ' world'` | `Hello world` |
| `AT TIME ZONE` | Apply a time zone offset | _[View example](/influxdb/cloud-dedicated/reference/sql/operators/other/#at-time-zone)_ | |
## Keywords
The following reserved keywords cannot be used as identifiers.
```sql
AND
ALL
ANALYZE
AS
ASC
AT TIME ZONE
BETWEEN
BOTTOM
CASE
DESC
DISTINCT
EXISTS
EXPLAIN
FROM
GROUP BY
HAVING
IN
INNER JOIN
JOIN
LEFT JOIN
LIKE
LIMIT
NOT
EXISTS
NOT IN
OR
ORDER BY
FULL OUTER JOIN
RIGHT JOIN
SELECT
TOP
TYPE
UNION
UNION ALL
WHERE
WITH
```
## Conditional expressions
Conditional expressions evaluate conditions based on input values.
The following conditional expressions are supported:
| Expression | Description |
| :--------- | :----------------------------------------------------------------- |
| CASE | Allows for use of WHEN-THEN-ELSE statements. |
| COALESCE | Returns the first non-NULL expression in a specified list. |
| NULLIF | Returns a NULL value if value1 = value2. Otherwise returns value1. |
## Statements and clauses
InfluxDB SQL supports the following basic syntax for queries:
```sql
[ WITH with_query [, …] ]
SELECT [ ALL | DISTINCT ] select_expr [, …]
[ FROM from_item [, …] ]
[ JOIN join_item [, …] ]
[ WHERE condition ]
[ GROUP BY grouping_element [, …] ]
[ HAVING condition]
[ UNION [ ALL ] ]
[ ORDER BY expression [ ASC | DESC ][, …] ]
[ LIMIT count ]
```
### SELECT statement and FROM clause
Use the SQL `SELECT` statement to query data from a specific measurement or measurements. The `FROM` clause always accompanies the `SELECT` statement.
#### Examples
```sql
SELECT * FROM "h2o_feet"
```
### WHERE clause
Use the `WHERE` clause to filter results based on `fields`, `tags`, and `timestamps`.
Use predicates to evaluate each row.
Rows that evaluate as `TRUE` are returned in the result set.
Rows that evaluate as `FALSE` are omitted from the result set.
#### Examples
```sql
SELECT * FROM "h2o_feet" WHERE "water_level" <= 9
```
```sql
SELECT
*
FROM
"h2o_feet"
WHERE
"location" = 'santa_monica'
AND "level description" = 'below 3 feet'
```
### JOIN clause
Use the `JOIN` clause to join data from multiple measurements (tables).
For more information about joins, see
[JOIN clause](/influxdb/cloud-dedicated/reference/sql/join/).
The following join types are supported:
{{< flex >}}
{{< flex-content "quarter" >}}
<a href="#inner-join">
<p style="text-align:center"><strong>INNER JOIN</strong></p>
{{< svg svg="static/svgs/join-diagram.svg" class="inner small center" >}}
</a>
{{< /flex-content >}}
{{< flex-content "quarter" >}}
<a href="#left-outer-join">
<p style="text-align:center"><strong>LEFT [OUTER] JOIN</strong></p>
{{< svg svg="static/svgs/join-diagram.svg" class="left small center" >}}
</a>
{{< /flex-content >}}
{{< flex-content "quarter" >}}
<a href="#right-outer-join">
<p style="text-align:center"><strong>RIGHT [OUTER] JOIN</strong></p>
{{< svg svg="static/svgs/join-diagram.svg" class="right small center" >}}
</a>
{{< /flex-content >}}
{{< flex-content "quarter" >}}
<a href="#full-outer-join">
<p style="text-align:center"><strong>FULL [OUTER] JOIN</strong></p>
{{< svg svg="static/svgs/join-diagram.svg" class="full small center" >}}
</a>
{{< /flex-content >}}
{{< /flex >}}
{{< expand-wrapper >}}
{{% expand "INNER JOIN" %}}
Inner joins combine rows from tables on the left and right side of the join
based on common column values defined in the `ON` clause. Rows that don't have
matching column values are not included in the output table.
```sql
SELECT
*
FROM
home
INNER JOIN home_actions ON
home.room = home_actions.room
AND home.time = home_actions.time;
```
{{% /expand %}}
{{% expand "LEFT [OUTER] JOIN" %}}
A left outer join returns all rows from the left side of the join and only
returns data from the right side of the join in rows with matching column values
defined in the `ON` clause.
```sql
SELECT
*
FROM
home
LEFT OUTER JOIN home_actions ON
home.room = home_actions.room
AND home.time = home_actions.time;
```
{{% /expand %}}
{{% expand "RIGHT [OUTER] JOIN" %}}
A right outer join returns all rows from the right side of the join and only
returns data from the left side of the join in rows with matching column values
defined in the `ON` clause.
```sql
SELECT
*
FROM
home
RIGHT OUTER JOIN home_actions ON
home.room = home_actions.room
AND home.time = home_actions.time;
```
{{% /expand %}}
{{% expand "FULL [OUTER] JOIN" %}}
A full outer join returns all data from the left and right sides of the join and
combines rows with matching column values defined in the `ON` clause.
```sql
SELECT
*
FROM
home
FULL OUTER JOIN home_actions ON
home.room = home_actions.room
AND home.time = home_actions.time;
```
{{% /expand %}}
{{< /expand-wrapper >}}
### GROUP BY clause
Use the `GROUP BY` clause to group query results based on specified column values. `GROUP BY` **requires** an aggregate or selector function in the `SELECT` statement.
#### Examples
```sql
SELECT
MEAN("water_level"),
"location"
FROM
"h2o_feet"
GROUP BY
"location"
```
### HAVING clause
Use the `HAVING` clause to filter query results based on a specified condition.
The `HAVING` clause must _follow_ the `GROUP BY` clause, but _precede_ the `ORDER BY` clause.
#### Examples
```sql
SELECT
MEAN("water_level"),
"location"
FROM
"h2o_feet"
GROUP BY
"location"
HAVING
MEAN("water_level") > 4
ORDER BY
"location"
```
### UNION clause
The `UNION` clause combines the results of two or more `SELECT` statements without returning any duplicate rows. `UNION ALL` returns all results, including duplicates.
#### Examples
```sql
SELECT
'pH'
FROM
"h2o_pH"
UNION ALL
SELECT
"location"
FROM
"h2o_quality"
```
### ORDER BY clause
The `ORDER BY` clause orders results by specified columns and order.
Sort data based on fields, tags, and timestamps.
The following orders are supported:
- `ASC`: ascending _(default)_
- `DESC`: descending
#### Examples
```sql
SELECT
"water_level",
"location"
FROM
"h2o_feet"
ORDER BY
"location",
"time" DESC
```
### LIMIT clause
The `LIMIT` clause limits the number of rows to return.
The defined limit should be a non-negative integer.
#### Examples
```sql
SELECT
"water_level",
"location"
FROM
"h2o_feet"
LIMIT
10
```
### WITH clause
The `WITH` clause provides a way to write auxiliary statements for use in a larger query.
It can help break down large, complicated queries into simpler forms.
```sql
WITH summary_data as
(SELECT degrees, location, time
FROM average_temperature)
SELECT * FROM summary_data
```
### OVER clause
The `OVER` clause is used with SQL window functions.
A **window function** performs a calculation across a set of table rows that are related in some way to the current row.
While similar to aggregate functions, window functions output results into rows retaining their separate identities.
```sql
SELECT
time,
water_level
FROM
(
SELECT
time,
"water_level",
row_number() OVER (
order by
water_level desc
) as rn
FROM
h2o_feet
)
WHERE
rn <= 3;
```
## Comments
Use comments to describe and add detail or notes to your queries.
- Single line comments use the double hyphen `--` symbol. Single line comments end with a line break.
- Multi-line comments begin with `/*` and end with ` */`.
```sql
-- Single-line comment
/*
* Multi-line comment
*/
```
## Schema information
{{% product-name %}} supports the following metadata schema queries:
```sql
SHOW tables
SHOW columns FROM <measurement>
```
## Functions
Following is a list of supported functions by type.
### Aggregate functions
An aggregate function performs a calculation or computation on a set of data values in a column and returns a single value.
| Function | Description |
| :------- | :--------------------------------------------------------- |
| COUNT() | Returns returns the number of rows from a field or tag key |
| AVG() | Returns the average value of a column |
| SUM() | Returns the summed value of a column |
| MEAN() | Returns the mean value of a column |
| MIN() | Returns the smallest value of the selected column |
| MAX() | Returns the largest value of the selected column |
#### Examples
```sql
SELECT COUNT("water_level")
FROM "h2o_feet"
SELECT AVG("water_level"), "location"
FROM "h2o_feet"
GROUP BY "location"
SELECT SUM("water_level"), "location"
FROM "h2o_feet"
GROUP BY "location"
```
### Selector functions
Selector functions are unique to InfluxDB. They behave like aggregate functions in that they take a row of data and compute it down to a single value. However, selectors are unique in that they return a **time value** in addition to the computed value. In short, selectors return an aggregated value along with a timestamp.
| Function | Description |
| :--------------- | :-------------------------------------------------------------- |
| SELECTOR_FIRST() | Returns the first value of a selected column and timestamp. |
| SELECTOR_LAST() | Returns the last value of a selected column and timestamp. |
| SELECTOR_MIN() | Returns the smallest value of a selected column and timestamp. |
| SELECTOR_MAX() | Returns the largest value of a selected column and timestamp. |
#### Examples
```sql
SELECT
SELECTOR_MAX("pH", time)['value'],
SELECTOR_MAX("pH", time)['time']
FROM "h2o_pH"
SELECT
SELECTOR_LAST("water_level", time)['value'],
SELECTOR_LAST("water_level", time)['time']
FROM "h2o_feet"
WHERE time >= timestamp '2019-09-10T00:00:00Z' AND time <= timestamp '2019-09-19T00:00:00Z'
```
### Date and time functions
| Function | Description |
| :----------- | :---------------------------------------------------------------------------------------------- |
| DATE_BIN() | Bins the input timestamp into a specified interval. |
| DATE_TRUNC() | Truncates a timestamp expression based on the date part specified, such as hour, day, or month. |
| DATE_PART() | Returns the specified part of a date. |
| NOW() | Returns the current time (UTC). |
#### Examples
```sql
SELECT DATE_BIN(INTERVAL '1 hour', time, '2019-09-18T00:00:00Z') AS "_time",
SUM(water_level)
FROM "h2o_feet"
GROUP BY "_time"
```
```sql
SELECT DATE_TRUNC('month',time) AS "date",
SUM(water_level)
FROM "h2o_feet"
GROUP BY time
```
### Approximate functions
| Function | Description |
| :--------------------------------- | :-------------------------------------------------------------------------------------------- |
| APPROX_MEDIAN | Returns the approximate median of input values. |
| APPROX_DISTINCT | Returns the approximate count of the number of distinct values. Implemented only for strings. |
| APPROX_PERCENTILE_CONT | Returns the approximate percentile of input values. |
| APPROX_PERCENTILE_CONT_WITH_WEIGHT | Returns the approximate percentile of input values with weight. |
### Math functions
| Function | Description |
| :------- | :------------------------------------------------------------------------------- |
| ABS() | Absolute value |
| ACOS() | Inverse cosine |
| ASIN() | Inverse sine |
| ATAN() | Inverse tangent |
| ATAN2() | Inverse tangent of y / x |
| CEIL() | Returns the smallest integer value greater than or equal to the specified number |
| COS() | Cosine |
| EXP() | Exponential |
| FLOOR() | Nearest integer less than or equal to the specified number |
| LN() | Natural logarithm |
| LOG10() | Base 10 logarithm |
| LOG2() | Base 2 logarithm |
| POWER() | Returns the value of a number raised to the power of the number |
| ROUND() | Round to the nearest integer |
| SIGNUM() | Sign of the argument (-1, 0, +1) |
| SINE() | Sine |
| SQRT() | Returns the square root of a number |
| TAN() | Tangent |
| TRUNC() | Truncates a number to the specified number of decimal places |
### Conditional functions
| Function | Description |
| :------- | :--------------------------------------------------------------------------------------------------------- |
| COALESCE | Returns the first argument that is not null. If all arguments are null, then `COALESCE` will return nulls. |
| NULLIF | Returns a null value if value1 equals value2, otherwise returns value1. |
### Regular expression functions
| Function | Description |
| :------------- | :---------------------------------------------------------------------------- |
| REGEXP_MATCH | Matches a regular expression against a string and returns matched substrings. |
| REGEXP_REPLACE | Replaces substrings that match a regular expression by a new substring. |
<!--
The content of this page is at /content/shared/sql-reference/_index.md
-->

View File

@ -11,217 +11,10 @@ menu:
weight: 200
related:
- /influxdb/cloud-dedicated/query-data/sql/cast-types/
source: /content/shared/sql-reference/data-types.md
---
{{< product-name >}} uses the [Apache Arrow DataFusion](https://arrow.apache.org/datafusion/)
implementation of SQL.
Data types define the type of values that can be stored in table columns.
In InfluxDB's SQL implementation, a **measurement** is structured as a table,
and **tags**, **fields** and **timestamps** are exposed as columns.
## SQL and Arrow data types
In SQL, each column, expression, and parameter has a data type.
A data type is an attribute that specifies the type of data that the object can hold.
DataFusion uses the [Arrow](https://arrow.apache.org/) type system for query execution.
All SQL types are mapped to [Arrow data types](https://docs.rs/arrow/latest/arrow/datatypes/enum.DataType.html).
Both SQL and Arrow data types play an important role in how data is operated on
during query execution and returned in query results.
{{% note %}}
When performing casting operations, cast to the SQL data type unless you use
[`arrow_cast()`](/influxdb/cloud-dedicated/reference/sql/functions/misc/#arrow_cast)
to cast to a specific Arrow type.
Names and identifiers in SQL are _case-insensitive_ by default. For example:
```sql
SELECT
'99'::BIGINT,
'2019-09-18T00:00:00Z'::timestamp
```
{{% /note %}}
- [String types](#string-types)
- [Numeric types](#numeric-types)
- [Integers](#integers)
- [Unsigned integers](#unsigned-integers)
- [Floats](#floats)
- [Date and time data types](#date-and-time-data-types)
- [Timestamp](#timestamp)
- [Interval](#interval)
- [Boolean types](#boolean-types)
- [Unsupported SQL types](#unsupported-sql-types)
- [Data types compatible with parameters](#data-types-compatible-with-parameters)
## String types
| SQL data type | Arrow data type | Description |
| :------------ | :-------------- | --------------------------------- |
| STRING | UTF8 | Character string, variable-length |
| CHAR | UTF8 | Character string, fixed-length |
| VARCHAR | UTF8 | Character string, variable-length |
| TEXT | UTF8 | Variable unlimited length |
##### Example string literals
```sql
'abcdefghijk'
'time'
'h2o_temperature'
```
## Numeric types
The following numeric types are supported:
| SQL data type | Arrow data type | Description |
| :-------------- | :-------------- | :--------------------------- |
| BIGINT | INT64 | 64-bit signed integer |
| BIGINT UNSIGNED | UINT64 | 64-bit unsigned integer |
| DOUBLE | FLOAT64 | 64-bit floating-point number |
### Integers
InfluxDB SQL supports the 64-bit signed integers:
**Minimum signed integer**: `-9223372036854775808`
**Maximum signed integer**: `9223372036854775807`
##### Example integer literals
```sql
234
-446
5
```
### Unsigned integers
InfluxDB SQL supports the 64-bit unsigned integers:
**Minimum unsigned integer**: `0`
**Maximum unsigned integer**: `18446744073709551615`
##### Example unsigned integer literals
Unsigned integer literals are comprised of an integer cast to the `BIGINT UNSIGNED` type:
```sql
234::BIGINT UNSIGNED
458374893::BIGINT UNSIGNED
5::BIGINT UNSIGNED
```
### Floats
InfluxDB SQL supports the 64-bit double floating point values.
Floats can be a decimal point, decimal integer, or decimal fraction.
##### Example float literals
```sql
23.8
-446.89
5.00
0.033
```
## Date and time data types
InfluxDB SQL supports the following DATE/TIME data types:
| SQL data type | Arrow data type | Description |
| :------------ | :--------------------------------- | :-------------------------------------------- |
| TIMESTAMP | Timestamp(Nanosecond, None) | Nanosecond timestamp with no time zone offset |
| INTERVAL | Interval(IntervalMonthDayNano) | Interval of time with a specified duration |
### Timestamp
A time type is a single point in time using nanosecond precision.
The following date and time formats are supported:
```sql
YYYY-MM-DDT00:00:00.000Z
YYYY-MM-DDT00:00:00.000-00:00
YYYY-MM-DD 00:00:00.000-00:00
YYYY-MM-DDT00:00:00Z
YYYY-MM-DD 00:00:00.000
YYYY-MM-DD 00:00:00
```
##### Example timestamp literals
```sql
'2023-01-02T03:04:06.000Z'
'2023-01-02T03:04:06.000-00:00'
'2023-01-02 03:04:06.000-00:00'
'2023-01-02T03:04:06Z'
'2023-01-02 03:04:06.000'
'2023-01-02 03:04:06'
```
### Interval
The INTERVAL data type can be used with the following precision:
- nanosecond
- microsecond
- millisecond
- second
- minute
- hour
- day
- week
- month
- year
- century
##### Example interval literals
```sql
INTERVAL '10 minutes'
INTERVAL '1 year'
INTERVAL '2 days 1 hour 31 minutes'
```
## Boolean types
Booleans store TRUE or FALSE values.
| SQL data type | Arrow data type | Description |
| :------------ | :-------------- | :------------------- |
| BOOLEAN | Boolean | True or false values |
##### Example boolean literals
```sql
true
TRUE
false
FALSE
```
## Unsupported SQL types
The following SQL types are not currently supported:
- UUID
- BLOB
- CLOB
- BINARY
- VARBINARY
- REGCLASS
- NVARCHAR
- CUSTOM
- ARRAY
- ENUM
- SET
- DATETIME
- BYTEA
## Data types compatible with parameters
For information about data types that can be substituted by parameters,
see how to [use parameterized queries with SQL](/influxdb/cloud-dedicated/query-data/sql/parameterized-queries/).
<!--
The content of this page is at /content/shared/sql-reference/data-types.md
-->

View File

@ -11,113 +11,10 @@ related:
- /influxdb/cloud-dedicated/reference/internals/query-plan/
- /influxdb/cloud-dedicated/query-data/execute-queries/analyze-query-plan/
- /influxdb/cloud-dedicated/query-data/execute-queries/troubleshoot/
source: /content/shared/sql-reference/explain.md
---
The `EXPLAIN` command returns the [logical plan](/influxdb/cloud-dedicated/reference/internals/query-plan/#logical-plan) and the [physical plan](/influxdb/cloud-dedicated/reference/internals/query-plan/#physical-plan) for the
specified SQL statement.
```sql
EXPLAIN [ANALYZE] [VERBOSE] statement
```
- [`EXPLAIN`](#explain)
- [Example `EXPLAIN`](#example-explain)
- [`EXPLAIN ANALYZE`](#explain-analyze)
- [Example `EXPLAIN ANALYZE`](#example-explain-analyze)
- [`EXPLAIN ANALYZE VERBOSE`](#explain-analyze-verbose)
- [Example `EXPLAIN ANALYZE VERBOSE`](#example-explain-analyze-verbose)
## `EXPLAIN`
Returns the logical plan and physical (execution) plan of a statement.
To output more details, use `EXPLAIN VERBOSE`.
`EXPLAIN` doesn't execute the statement.
To execute the statement and view runtime metrics, use [`EXPLAIN ANALYZE`](#explain-analyze).
### Example `EXPLAIN`
```sql
EXPLAIN
SELECT
room,
avg(temp) AS temp
FROM home
GROUP BY room
```
{{< expand-wrapper >}}
{{% expand "View `EXPLAIN` example output" %}}
| | plan_type | plan |
|---:|:--------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 0 | logical_plan |<span style="white-space:pre-wrap;"> Projection: home.room, AVG(home.temp) AS temp </span>|
| | |<span style="white-space:pre-wrap;"> Aggregate: groupBy=[[home.room]], aggr=[[AVG(home.temp)]] </span>|
| | |<span style="white-space:pre-wrap;"> TableScan: home projection=[room, temp] </span>|
| 1 | physical_plan |<span style="white-space:pre-wrap;"> ProjectionExec: expr=[room@0 as room, AVG(home.temp)@1 as temp] </span>|
| | |<span style="white-space:pre-wrap;"> AggregateExec: mode=FinalPartitioned, gby=[room@0 as room], aggr=[AVG(home.temp)] </span>|
| | |<span style="white-space:pre-wrap;"> CoalesceBatchesExec: target_batch_size=8192 </span>|
| | |<span style="white-space:pre-wrap;"> RepartitionExec: partitioning=Hash([room@0], 8), input_partitions=8 </span>|
| | |<span style="white-space:pre-wrap;"> AggregateExec: mode=Partial, gby=[room@0 as room], aggr=[AVG(home.temp)] </span>|
| | |<span style="white-space:pre-wrap;"> ParquetExec: file_groups={8 groups: [[70434/116281/404d73cea0236530ea94f5470701eb814a8f0565c0e4bef5a2d2e33dfbfc3567/1be334e8-0af8-00da-2615-f67cd4be90f7.parquet, 70434/116281/b7a9e7c57fbfc3bba9427e4b3e35c89e001e2e618b0c7eb9feb4d50a3932f4db/d29370d4-262f-0d32-2459-fe7b099f682f.parquet], [70434/116281/c14418ba28a22a3abb693a1cb326a63b62dc611aec58c9bed438fdafd3bc5882/8b29ae98-761f-0550-2fe4-ee77503658e9.parquet], [70434/116281/fa677477eed622ae8123da1251aa7c351f801e2ee2f0bc28c0fe3002a30b3563/65bb4dc3-04e1-0e02-107a-90cee83c51b0.parquet], [70434/116281/db162bdd30261019960dd70da182e6ebd270284569ecfb5deffea7e65baa0df9/2505e079-67c5-06d9-3ede-89aca542dd18.parquet], [70434/116281/0c025dcccae8691f5fd70b0f131eea4ca6fafb95a02f90a3dc7bb015efd3ab4f/3f3e44c3-b71e-0ca4-3dc7-8b2f75b9ff86.parquet], ...]}, projection=[room, temp] </span>|
{{% /expand %}}
{{< /expand-wrapper >}}
## `EXPLAIN ANALYZE`
Executes a statement and returns the execution plan and runtime metrics of the statement.
The report includes the [logical plan](/influxdb/cloud-dedicated/reference/internals/query-plan/#logical-plan) and the [physical plan](/influxdb/cloud-dedicated/reference/internals/query-plan/#physical-plan) annotated with execution counters, number of rows produced, and runtime metrics sampled during the query execution.
If the plan requires reading lots of data files, `EXPLAIN` and `EXPLAIN ANALYZE` may truncate the list of files in the report.
To output more information, including intermediate plans and paths for all scanned Parquet files, use [`EXPLAIN ANALYZE VERBOSE`](#explain-analyze-verbose).
### Example `EXPLAIN ANALYZE`
```sql
EXPLAIN ANALYZE
SELECT
room,
avg(temp) AS temp
FROM home
WHERE time >= '2023-01-01' AND time <= '2023-12-31'
GROUP BY room
```
{{< expand-wrapper >}}
{{% expand "View `EXPLAIN ANALYZE` example output" %}}
| | plan_type | plan |
|---:|:------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 0 | Plan with Metrics |<span style="white-space:pre-wrap;"> ProjectionExec: expr=[room@0 as room, AVG(home.temp)@1 as temp], metrics=[output_rows=2, elapsed_compute=4.768µs] </span>|
| | |<span style="white-space:pre-wrap;"> AggregateExec: mode=FinalPartitioned, gby=[room@0 as room], aggr=[AVG(home.temp)], ordering_mode=Sorted, metrics=[output_rows=2, elapsed_compute=140.405µs] </span>|
| | |<span style="white-space:pre-wrap;"> CoalesceBatchesExec: target_batch_size=8192, metrics=[output_rows=2, elapsed_compute=6.821µs] </span>|
| | |<span style="white-space:pre-wrap;"> RepartitionExec: partitioning=Hash([room@0], 8), input_partitions=8, preserve_order=true, sort_exprs=room@0 ASC, metrics=[output_rows=2, elapsed_compute=18.408µs, repart_time=59.698µs, fetch_time=1.057882762s, send_time=5.83µs] </span>|
| | |<span style="white-space:pre-wrap;"> AggregateExec: mode=Partial, gby=[room@0 as room], aggr=[AVG(home.temp)], ordering_mode=Sorted, metrics=[output_rows=2, elapsed_compute=137.577µs] </span>|
| | |<span style="white-space:pre-wrap;"> RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=6, preserve_order=true, sort_exprs=room@0 ASC, metrics=[output_rows=46, elapsed_compute=26.637µs, repart_time=6ns, fetch_time=399.971411ms, send_time=6.658µs] </span>|
| | |<span style="white-space:pre-wrap;"> ProjectionExec: expr=[room@0 as room, temp@2 as temp], metrics=[output_rows=46, elapsed_compute=3.102µs] </span>|
| | |<span style="white-space:pre-wrap;"> CoalesceBatchesExec: target_batch_size=8192, metrics=[output_rows=46, elapsed_compute=25.585µs] </span>|
| | |<span style="white-space:pre-wrap;"> FilterExec: time@1 >= 1672531200000000000 AND time@1 <= 1703980800000000000, metrics=[output_rows=46, elapsed_compute=26.51µs] </span>|
| | |<span style="white-space:pre-wrap;"> ParquetExec: file_groups={6 groups: [[70434/116281/404d73cea0236530ea94f5470701eb814a8f0565c0e4bef5a2d2e33dfbfc3567/1be334e8-0af8-00da-2615-f67cd4be90f7.parquet], [70434/116281/c14418ba28a22a3abb693a1cb326a63b62dc611aec58c9bed438fdafd3bc5882/8b29ae98-761f-0550-2fe4-ee77503658e9.parquet], [70434/116281/fa677477eed622ae8123da1251aa7c351f801e2ee2f0bc28c0fe3002a30b3563/65bb4dc3-04e1-0e02-107a-90cee83c51b0.parquet], [70434/116281/db162bdd30261019960dd70da182e6ebd270284569ecfb5deffea7e65baa0df9/2505e079-67c5-06d9-3ede-89aca542dd18.parquet], [70434/116281/0c025dcccae8691f5fd70b0f131eea4ca6fafb95a02f90a3dc7bb015efd3ab4f/3f3e44c3-b71e-0ca4-3dc7-8b2f75b9ff86.parquet], ...]}, projection=[room, time, temp], output_ordering=[room@0 ASC, time@1 ASC], predicate=time@6 >= 1672531200000000000 AND time@6 <= 1703980800000000000, pruning_predicate=time_max@0 >= 1672531200000000000 AND time_min@1 <= 1703980800000000000, required_guarantees=[], metrics=[output_rows=46, elapsed_compute=6ns, predicate_evaluation_errors=0, bytes_scanned=3279, row_groups_pruned_statistics=0, file_open_errors=0, file_scan_errors=0, pushdown_rows_filtered=0, num_predicate_creation_errors=0, row_groups_pruned_bloom_filter=0, page_index_rows_filtered=0, time_elapsed_opening=398.462968ms, time_elapsed_processing=1.626106ms, time_elapsed_scanning_total=1.36822ms, page_index_eval_time=33.474µs, pushdown_eval_time=14.267µs, time_elapsed_scanning_until_data=1.27694ms] </span>|
{{% /expand %}}
{{< /expand-wrapper >}}
## `EXPLAIN ANALYZE VERBOSE`
Executes a statement and returns the execution plan, runtime metrics, and additional details helpful for debugging the statement.
The report includes the following:
- the [logical plan](/influxdb/cloud-dedicated/reference/internals/query-plan/#logical-plan)
- the [physical plan](/influxdb/cloud-dedicated/reference/internals/query-plan/#physical-plan) annotated with execution counters, number of rows produced, and runtime metrics sampled during the query execution
- Information truncated in the `EXPLAIN` report--for example, the paths for all [Parquet files retrieved for the query](/influxdb/cloud-dedicated/reference/internals/query-plan/#file_groups).
- All intermediate physical plans that DataFusion and the [Querier](/influxdb/cloud-dedicated/reference/internals/storage-engine/#querier) generate before generating the final physical plan--helpful in debugging to see when an [`ExecutionPlan` node](/influxdb/cloud-dedicated/reference/internals/query-plan/#executionplan-nodes) is added or removed, and how InfluxDB optimizes the query.
### Example `EXPLAIN ANALYZE VERBOSE`
```SQL
EXPLAIN ANALYZE VERBOSE SELECT temp FROM home
WHERE time >= now() - INTERVAL '7 days' AND room = 'Kitchen'
ORDER BY time
```
<!--
The content of this page is at /content/shared/sql-reference/explain.md
-->

View File

@ -9,6 +9,10 @@ menu:
parent: SQL reference
identifier: sql-functions
weight: 220
source: /content/shared/sql-reference/functions/_index.md
---
{{< children >}}
<!--
The content of this page is at /content/shared/sql-reference/functions/_index.md
-->

View File

@ -8,137 +8,10 @@ menu:
name: Conditional
parent: sql-functions
weight: 306
source: /content/shared/sql-reference/functions/conditional.md
---
The InfluxDB SQL implementation supports the following conditional functions for
conditionally handling _null_ values:
- [coalesce](#coalesce)
- [ifnull](#ifnull)
- [nullif](#nullif)
- [nvl](#nvl)
## coalesce
Returns the first of its arguments that is not _null_.
Returns _null_ if all arguments are _null_.
This function is often used to substitute a default value for _null_ values.
```sql
coalesce(expression1[, ..., expression_n])
```
##### Arguments
- **expression1, expression_n**:
Expression to use if previous expressions are _null_.
Can be a constant, column, or function, and any combination of arithmetic operators.
Pass as many expression arguments as necessary.
{{< expand-wrapper >}}
{{% expand "View `coalesce` query example" %}}
```sql
SELECT
val1,
val2,
val3,
coalesce(val1, val2, val3, 'quz') AS coalesce
FROM
(values ('foo', 'bar', 'baz'),
(NULL, 'bar', 'baz'),
(NULL, NULL, 'baz'),
(NULL, NULL, NULL)
) data(val1, val2, val3)
```
| val1 | val2 | val3 | coalesce |
| :--: | :--: | :--: | :------: |
| foo | bar | baz | foo |
| | bar | baz | bar |
| | | baz | baz |
| | | | quz |
{{% /expand %}}
{{< /expand-wrapper >}}
## ifnull
_Alias of [nvl](#nvl)._
## nullif
Returns _null_ if _expression1_ equals _expression2_; otherwise it returns _expression1_.
This can be used to perform the inverse operation of [`coalesce`](#coalesce).
```sql
nullif(expression1, expression2)
```
##### Arguments
- **expression1**: Expression to compare and return if equal to expression2.
Can be a constant, column, or function, and any combination of arithmetic operators.
- **expression2**: Expression to compare to expression1.
Can be a constant, column, or function, and any combination of arithmetic operators.
{{< expand-wrapper >}}
{{% expand "View `nullif` query example" %}}
```sql
SELECT
value,
nullif(value, 'baz') AS nullif
FROM
(values ('foo'),
('bar'),
('baz')
) data(value)
```
| value | nullif |
| :---- | :----- |
| foo | foo |
| bar | bar |
| baz | |
{{% /expand %}}
{{< /expand-wrapper >}}
## nvl
Returns _expression2_ if _expression1_ is _null_; otherwise it returns _expression1_.
```sql
nvl(expression1, expression2)
```
##### Arguments
- **expression1**: Return this expression if not _null_.
Can be a constant, column, or function, and any combination of arithmetic operators.
- **expression2**: Return this expression if _expression1_ is _null_.
Can be a constant, column, or function, and any combination of arithmetic operators.
{{< expand-wrapper >}}
{{% expand "View `nvl` query example" %}}
```sql
SELECT
value,
nvl(value, 'baz') AS nvl
FROM
(values ('foo'),
('bar'),
(NULL)
) data(value)
```
| value | nvl |
| :---- | :-- |
| foo | foo |
| bar | bar |
| | baz |
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
The content of this page is at /content/shared/sql-reference/functions/conditional.md
-->

View File

@ -8,239 +8,10 @@ menu:
name: Miscellaneous
parent: sql-functions
weight: 310
source: /content/shared/sql-reference/functions/misc.md
---
The InfluxDB SQL implementation supports the following miscellaneous functions
for performing a variety of operations:
- [arrow_cast](#arrow_cast)
- [arrow_typeof](#arrow_typeof)
- [interpolate](#interpolate)
- [locf](#locf)
<!-- - [struct](#struct) -->
## arrow_cast
Casts a value to a specific Arrow data type.
```sql
arrow_cast(expression, datatype)
```
#### Arguments
- **expression**: Expression to cast.
Can be a constant, column, or function, and any combination of arithmetic or
string operators.
- **datatype**: [Arrow data type](/influxdb/cloud-dedicated/reference/sql/data-types/#sql-and-arrow-data-types)
to cast to.
{{< expand-wrapper >}}
{{% expand "View `arrow_cast` query example" %}}
_The following example uses the sample data set provided in
[Get started with InfluxDB tutorial](/influxdb/cloud-dedicated/get-started/write/#construct-line-protocol)._
```sql
SELECT
arrow_cast(time, 'Int64') AS time,
arrow_cast(temp, 'Utf8') AS temp,
arrow_cast(co, 'Float64')AS co
FROM home
LIMIT 1
```
| time | temp | co |
| :------------------ | ---: | --: |
| 1641024000000000000 | 21.0 | 0 |
{{% /expand %}}
{{< /expand-wrapper >}}
## arrow_typeof
Returns the underlying [Arrow data type](https://arrow.apache.org/datafusion/user-guide/sql/data_types.html)
of the expression:
```sql
arrow_typeof(expression)
```
##### Arguments
- **expression**: Expression to evaluate.
Can be a constant, column, or function, and any combination of arithmetic or
string operators.
{{< expand-wrapper >}}
{{% expand "View `arrow_typeof` query example" %}}
_The following example uses the sample data set provided in
[Get started with InfluxDB tutorial](/influxdb/cloud-dedicated/get-started/write/#construct-line-protocol)._
```sql
SELECT
arrow_typeof(time) AS time,
arrow_typeof(room) AS room,
arrow_typeof(temp) AS temp,
arrow_typeof(co) AS co
FROM home
LIMIT 1
```
| time | room | temp | co |
| :-------------------------- | :---------------------- | :------ | :---- |
| Timestamp(Nanosecond, None) | Dictionary(Int32, Utf8) | Float64 | Int64 |
{{% /expand %}}
{{< /expand-wrapper >}}
## interpolate
Fills null values in a specified aggregated column by interpolating values
from existing values.
Must be used with [`date_bin_gapfill`](/influxdb/cloud-dedicated/reference/sql/functions/time-and-date/#date_bin_gapfill).
```sql
interpolate(aggregate_expression)
```
##### Arguments
- **aggregate_expression**: Aggregate operation on a specified expression.
The operation can use any [aggregate function](/influxdb/cloud-dedicated/reference/sql/functions/aggregate/).
The expression can be a constant, column, or function, and any combination of
arithmetic operators supported by the aggregate function.
##### Related functions
[date_bin_gapfill](/influxdb/cloud-dedicated/reference/sql/functions/time-and-date/#date_bin_gapfill),
[locf](#locf)
{{< expand-wrapper >}}
{{% expand "View `interpolate` query example" %}}
_The following example uses the sample data set provided in the
[Get started with InfluxDB tutorial](/influxdb/cloud-dedicated/get-started/write/#construct-line-protocol)._
{{% influxdb/custom-timestamps %}}
```sql
SELECT
date_bin_gapfill(INTERVAL '30 minutes', time) as _time,
room,
interpolate(avg(temp))
FROM home
WHERE
time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T10:00:00Z'
GROUP BY _time, room
```
| _time | room | AVG(home.temp) |
| :------------------- | :---------- | -------------: |
| 2022-01-01T08:00:00Z | Kitchen | 21 |
| 2022-01-01T08:30:00Z | Kitchen | 22 |
| 2022-01-01T09:00:00Z | Kitchen | 23 |
| 2022-01-01T09:30:00Z | Kitchen | 22.85 |
| 2022-01-01T10:00:00Z | Kitchen | 22.7 |
| 2022-01-01T08:00:00Z | Living Room | 21.1 |
| 2022-01-01T08:30:00Z | Living Room | 21.25 |
| 2022-01-01T09:00:00Z | Living Room | 21.4 |
| 2022-01-01T09:30:00Z | Living Room | 21.6 |
| 2022-01-01T10:00:00Z | Living Room | 21.8 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## locf
Fills null values in a specified aggregated column by carrying the last observed
value forward.
Must be used with [`date_bin_gapfill`](/influxdb/cloud-dedicated/reference/sql/functions/time-and-date/#date_bin_gapfill).
_LOCF is an initialism of "last observation carried forward."_
```sql
locf(aggregate_expression)
```
##### Arguments
- **aggregate_expression**: Aggregate operation on a specified expression.
The operation can use any [aggregate function](/influxdb/cloud-dedicated/reference/sql/functions/aggregate/).
The expression can be a constant, column, or function, and any combination of
arithmetic operators supported by the aggregate function.
##### Related functions
[date_bin_gapfill](/influxdb/cloud-dedicated/reference/sql/functions/time-and-date/#date_bin_gapfill),
[interpolate](#interpolate)
{{< expand-wrapper >}}
{{% expand "View `locf` query example" %}}
_The following example uses the sample data set provided in the
[Get started with InfluxDB tutorial](/influxdb/cloud-dedicated/get-started/write/#construct-line-protocol)._
{{% influxdb/custom-timestamps %}}
```sql
SELECT
date_bin_gapfill(INTERVAL '30 minutes', time) as _time,
room,
locf(avg(temp))
FROM home
WHERE
time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T10:00:00Z'
GROUP BY _time, room
```
| _time | room | AVG(home.temp) |
| :------------------- | :---------- | -------------: |
| 2022-01-01T08:00:00Z | Kitchen | 21 |
| 2022-01-01T08:30:00Z | Kitchen | 21 |
| 2022-01-01T09:00:00Z | Kitchen | 23 |
| 2022-01-01T09:30:00Z | Kitchen | 23 |
| 2022-01-01T10:00:00Z | Kitchen | 22.7 |
| 2022-01-01T08:00:00Z | Living Room | 21.1 |
| 2022-01-01T08:30:00Z | Living Room | 21.1 |
| 2022-01-01T09:00:00Z | Living Room | 21.4 |
| 2022-01-01T09:30:00Z | Living Room | 21.4 |
| 2022-01-01T10:00:00Z | Living Room | 21.8 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
## struct
Returns an Arrow struct using the specified input expressions.
Fields in the returned struct use the `cN` naming convention.
For example: `c0`, `c1`, `c2`, etc.
```sql
struct(expression1[, ..., expression_n])
```
##### Arguments
- **expression_n**: Expression to include in the output struct.
Can be a constant, column, or function, and any combination of arithmetic or
string operators.
{{< expand-wrapper >}}
{{% expand "View `struct` example" %}}
```sql
struct('A', 'B', 3, 4)
-- Returns {c0: A, c1: B, c3: 3, c4: 4}
```
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
The content of this page is at /content/shared/sql-reference/functions/misc.md
-->

View File

@ -9,145 +9,10 @@ menu:
parent: sql-functions
weight: 308
influxdb/cloud-dedicated/tags: [regular expressions, sql]
source: /content/shared/sql-reference/functions/regular-expression.md
---
The InfluxDB SQL implementation uses the
[PCRE-like](https://en.wikibooks.org/wiki/Regular_Expressions/Perl-Compatible_Regular_Expressions)
regular expression [syntax](https://docs.rs/regex/latest/regex/#syntax)
(excluding some features such as look-around and back-references) and supports
the following regular expression functions:
- [regexp_like](#regexp_like)
- [regexp_match](#regexp_match)
- [regexp_replace](#regexp_replace)
## regexp_like
True if a regular expression has at least one match in a string;
false otherwise.
```sql
regexp_like(str, regexp[, flags])
```
##### Arguments
- **str**: String expression to operate on.
Can be a constant, column, or function, and any combination of string operators.
- **regexp**: Regular expression to test against the string expression.
Can be a constant, column, or function.
- **flags**: Optional regular expression flags that control the behavior of the
regular expression. The following flags are supported:
- **i**: (insensitive) Ignore case when matching.
- **m**: (multi-line) `^` and `$` match the beginning and end of a line, respectively.
- **s**: (single-line) `.` matches newline (`\n`).
- **R**: (CRLF) When multi-line mode is enabled, `\r\n` is used to delimit lines.
- **U**: (ungreedy) Swap the meaning of `x*` and `x*?`.
{{< expand-wrapper >}}
{{% expand "View `regexp_replace` query example" %}}
_The following example uses the sample data set provided in
[Get started with InfluxDB tutorial](/influxdb/cloud-dedicated/get-started/write/#construct-line-protocol)._
```sql
SELECT DISTINCT
room,
regexp_like(room::STRING, 'R', 'i') AS regexp_like
FROM home
```
| room | regexp_like |
| :---------- | :---------- |
| Kitchen | false |
| Living Room | true |
{{% /expand %}}
{{< /expand-wrapper >}}
## regexp_match
Returns a list of regular expression matches in a string.
```sql
regexp_match(str, regexp, flags)
```
##### Arguments
- **str**: String expression to operate on.
Can be a constant, column, or function, and any combination of string operators.
- **regexp**: Regular expression to match against.
Can be a constant, column, or function.
- **flags**: Regular expression flags that control the behavior of the
regular expression. The following flags are supported.
- **i**: (insensitive) Ignore case when matching.
{{< expand-wrapper >}}
{{% expand "View `regexp_replace` query example" %}}
_The following example uses the sample data set provided in
[Get started with InfluxDB tutorial](/influxdb/cloud-dedicated/get-started/write/#construct-line-protocol)._
{{% note %}}
`regexp_match` returns a _list_ Arrow type, which is not supported by InfluxDB.
Use _bracket notation_ to reference a value in the list.
Lists use 1-based indexing.
{{% /note %}}
```sql
SELECT DISTINCT
room,
regexp_match(room::STRING, '.{3}')[1] AS regexp_match
FROM home
```
| room | regexp_match |
| :---------- | :----------- |
| Kitchen | Kit |
| Living Room | Liv |
{{% /expand %}}
{{< /expand-wrapper >}}
## regexp_replace
Replaces substrings in a string that match a regular expression.
```sql
regexp_replace(str, regexp, replacement, flags)
```
##### Arguments
- **str**: String expression to operate on.
Can be a constant, column, or function, and any combination of string operators.
- **regexp**: Regular expression to match against.
Can be a constant, column, or function.
- **replacement**: Replacement string expression.
Can be a constant, column, or function, and any combination of string operators.
- **flags**: Regular expression flags that control the behavior of the
regular expression. The following flags are supported.
- **g**: (global) Search globally and don't return after the first match.
- **i**: (insensitive) Ignore case when matching.
{{< expand-wrapper >}}
{{% expand "View `regexp_replace` query example" %}}
_The following example uses the sample data set provided in
[Get started with InfluxDB tutorial](/influxdb/cloud-dedicated/get-started/write/#construct-line-protocol)._
```sql
SELECT DISTINCT
room,
regexp_replace(room::STRING, '\sRoom', '', 'gi') AS regexp_replace
FROM home
```
| room | regexp_replace |
| :---------- | :------------- |
| Kitchen | Kitchen |
| Living Room | Living |
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
The content of this page is at /content/shared/sql-reference/functions/regular-expression.md
-->

View File

@ -10,191 +10,10 @@ menu:
weight: 302
related:
- /influxdb/cloud-dedicated/query-data/sql/aggregate-select/
source: /content/shared/sql-reference/functions/selector.md
---
SQL selector functions are designed to work with time series data.
They behave similarly to aggregate functions in that they take a collection of
data and return a single value.
However, selectors are unique in that they return a _struct_ that contains
a **time value** in addition to the computed value.
- [How do selector functions work?](#how-do-selector-functions-work)
- [Selector functions](#selector-functions)
- [selector_min](#selector_min)
- [selector_max](#selector_max)
- [selector_first](#selector_first)
- [selector_last](#selector_last)
## How do selector functions work?
Each selector function returns an [Arrow _struct_](https://arrow.apache.org/docs/format/Columnar.html#struct-layout)
(similar to a JSON object) representing a single time and value from the
specified column in the each group.
What time and value get returned depend on the logic in the selector function.
For example, `selector_first` returns the value of specified column in the first row of the group.
`selector_max` returns the maximum value of the specified column in the group.
### Selector struct schema
The struct returned from a selector function has two properties:
- **time**: `time` value in the selected row
- **value**: value of the specified column in the selected row
```js
{time: 2023-01-01T00:00:00Z, value: 72.1}
```
### Selector functions in use
In your `SELECT` statement, execute a selector function and use bracket notation
to reference properties of the [returned struct](#selector-struct-schema) to
populate the column value:
```sql
SELECT
selector_first(temp, time)['time'] AS time,
selector_first(temp, time)['value'] AS temp,
room
FROM home
GROUP BY room
```
## Selector functions
- [selector_min](#selector_min)
- [selector_max](#selector_max)
- [selector_first](#selector_first)
- [selector_last](#selector_last)
### selector_min
Returns the smallest value of a selected column and a timestamp.
```sql
selector_min(expression, timestamp)
```
##### Arguments
- **expression**: Expression to operate on.
Can be a constant, column, or function, and any combination of string or
arithmetic operators.
- **timestamp**: Time expression.
Can be a constant, column, or function.
{{< expand-wrapper >}}
{{% expand "View `selector_min` query example" %}}
```sql
SELECT
selector_min(water_level, time)['time'] AS time,
selector_min(water_level, time)['value'] AS water_level
FROM h2o_feet
```
| time | water_level |
| :------------------- | ----------: |
| 2019-08-28T14:30:00Z | -0.61 |
{{% /expand %}}
{{< /expand-wrapper >}}
### selector_max
Returns the largest value of a selected column and a timestamp.
```sql
selector_max(expression, timestamp)
```
##### Arguments
- **expression**: Expression to operate on.
Can be a constant, column, or function, and any combination of string or
arithmetic operators.
- **timestamp**: Time expression.
Can be a constant, column, or function.
{{< expand-wrapper >}}
{{% expand "View `selector_max` query example" %}}
```sql
SELECT
selector_max(water_level, time)['time'] AS time,
selector_max(water_level, time)['value'] AS water_level
FROM h2o_feet
```
| time | water_level |
| :------------------- | ----------: |
| 2019-08-28T07:24:00Z | 9.964 |
{{% /expand %}}
{{< /expand-wrapper >}}
### selector_first
Returns the first value ordered by time ascending.
```sql
selector_first(expression, timestamp)
```
##### Arguments
- **expression**: Expression to operate on.
Can be a constant, column, or function, and any combination of string or
arithmetic operators.
- **timestamp**: Time expression.
Can be a constant, column, or function.
{{< expand-wrapper >}}
{{% expand "View `selector_first` query example" %}}
```sql
SELECT
selector_first(water_level, time)['time'] AS time,
selector_first(water_level, time)['value'] AS water_level
FROM h2o_feet
```
| time | water_level |
| :------------------- | ----------: |
| 2019-08-28T07:24:00Z | 9.964 |
{{% /expand %}}
{{< /expand-wrapper >}}
### selector_last
Returns the last value ordered by time ascending.
```sql
selector_last(expression, timestamp)
```
##### Arguments
- **expression**: Expression to operate on.
Can be a constant, column, or function, and any combination of string or
arithmetic operators.
- **timestamp**: Time expression.
Can be a constant, column, or function.
{{< expand-wrapper >}}
{{% expand "View `selector_last` query example" %}}
```sql
SELECT
selector_last(water_level, time)['time'] AS time,
selector_last(water_level, time)['value'] AS water_level
FROM h2o_feet
```
| time | water_level |
| :------------------- | ----------: |
| 2019-09-17T21:42:00Z | 4.938 |
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
The content of this page is at /content/shared/sql-reference/functions/selector.md
-->

View File

@ -7,92 +7,10 @@ menu:
name: GROUP BY clause
parent: SQL reference
weight: 203
source: /content/shared/sql-reference/group-by.md
---
Use the `GROUP BY` clause to group data by values.
`GROUP BY` is an optional clause used to group rows that have the same values for all columns and expressions in the list.
To output an aggregation for each group, include an aggregate or selector function in the `SELECT` statement.
When `GROUP BY` appears in a query, the `SELECT` list can only use columns that appear in the `GROUP BY` list
or in aggregate expressions.
`GROUP BY` can use column aliases that are defined in the `SELECT` clause.
`GROUP BY` can't use an alias named `time`.
In a `GROUP BY` list, `time` always refers to the measurement `time` column.
- [Syntax](#syntax)
- [Examples](#examples)
## Syntax
```sql
SELECT
AGGREGATE_FN(field1),
tag1
FROM measurement
GROUP BY tag1
```
## Examples
### Group data by tag values
```sql
SELECT
AVG("water_level") AS "avg_water_level",
"location"
FROM "h2o_feet"
GROUP BY "location"
```
{{< expand-wrapper >}}}
{{% expand "View example results" %}}
| avg_water_level | location |
| ----------------: | ------------ |
| 5.359142420303919 | coyote_creek |
| 3.530712094245885 | santa_monica |
{{% /expand %}}
{{< /expand-wrapper >}}
Group results in 15 minute time intervals by tag:
```sql
SELECT
"location",
DATE_BIN(INTERVAL '15 minutes', time, TIMESTAMP '2022-01-01 00:00:00Z') AS _time,
COUNT("water_level") AS count
FROM "h2o_feet"
WHERE
time >= timestamp '2019-09-17T00:00:00Z'
AND time <= timestamp '2019-09-17T01:00:00Z'
GROUP BY
_time,
location
ORDER BY
location,
_time
```
{{< expand-wrapper >}}}
{{% expand "View example results" %}}
The query uses the `COUNT()` function to count the number of `water_level` points per 15 minute interval.
Results are then ordered by location and time.
| location | _time | count |
| :----------- | :-------------------- | ----: |
| coyote_creek | 2019-09-16T23:45:00Z | 1 |
| coyote_creek | 2019-09-17T00:00:00Z | 2 |
| coyote_creek | 2019-09-17T00:15:00Z | 3 |
| coyote_creek | 2019-09-17T00:30:00Z | 2 |
| coyote_creek | 2019-09-17T00:45:00Z | 3 |
| santa_monica | 2019-09-16T23:45:00Z | 1 |
| santa_monica | 2019-09-17T00:00:00Z | 2 |
| santa_monica | 2019-09-17T00:15:00Z | 3 |
| santa_monica | 2019-09-17T00:30:00Z | 2 |
| santa_monica | 2019-09-17T00:45:00Z | 3 |
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
The content of this page is at /content/shared/sql-reference/group-by.md
-->

View File

@ -10,78 +10,10 @@ menu:
weight: 205
related:
- /influxdb/cloud-dedicated/reference/sql/subqueries/
source: /content/shared/sql-reference/having.md
---
The `HAVING` clause places conditions on results created by an aggregate operation on groups.
The `HAVING` clause must follow the `GROUP BY` clause and precede the `ORDER BY` clause.
{{% note %}}
The `WHERE` clause filters rows based on specified conditions _before_ the aggregate operation.
The `HAVING` clause filters rows based on specified conditions _after_ the aggregate operation has taken place.
{{% /note %}}
- [Syntax](#syntax)
- [Examples](#examples)
## Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [HAVING_clause] [ORDER_BY_clause]
```
## Examples
### Return rows with an aggregate value greater than a specified number
```sql
SELECT
MEAN("water_level") AS "mean_water_level", "location"
FROM
"h2o_feet"
GROUP BY
"location"
HAVING
"mean_water_level" > 5
```
{{< expand-wrapper >}}
{{% expand "View example results" %}}
The query returns on rows with values in the `mean_water_level` greater than 5 _after_ the aggregate operation.
| location | mean_water_level |
| :----------- | :---------------- |
| coyote_creek | 5.359142420303919 |
{{% /expand %}}
{{< /expand-wrapper >}}
### Return the average result greater than a specified number from a specific time range
```sql
SELECT
AVG("water_level") AS "avg_water_level",
"time"
FROM
"h2o_feet"
WHERE
time >= '2019-09-01T00:00:00Z' AND time <= '2019-09-02T00:00:00Z'
GROUP BY
"time"
HAVING
"avg_water_level" > 6.82
ORDER BY
"time"
```
{{< expand-wrapper >}}
{{% expand "View example results" %}}
The query calculates the average water level per time and only returns rows with an average greater than 6.82 during the specified time range.
| time | avg_water_level |
| :------------------- | -----------------: |
| 2019-09-01T22:06:00Z | 6.8225 |
| 2019-09-01T22:12:00Z | 6.8405000000000005 |
| 2019-09-01T22:30:00Z | 6.8505 |
| 2019-09-01T22:36:00Z | 6.8325 |
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
The content of this page is at /content/shared/sql-reference/having.md
-->

View File

@ -7,140 +7,10 @@ menu:
influxdb_cloud_dedicated:
parent: SQL reference
weight: 210
source: /content/shared/sql-reference/information-schema.md
---
The underlying query engine for the InfluxDB SQL implementation,
[DataFusion](https://arrow.apache.org/datafusion/index.html), provides commands
that return metadata related to your data schema.
To access this information, use the `SHOW TABLES`, `SHOW COLUMNS`, and
`SHOW ALL` commands or query views in the [ISO](https://www.iso.org/) SQL
`information_schema` schema.
In the context of InfluxDB, a [measurement](/influxdb/cloud-dedicated/reference/glossary/#measurement)
is represented as a table. Time, [tags](/influxdb/cloud-dedicated/reference/glossary/#tag),
and [fields](/influxdb/cloud-dedicated/reference/glossary/#field) are each represented
by columns in a table.
- [SHOW TABLES](#show-tables)
- [Example SHOW TABLES output](#example-show-tables-output)
- [SHOW COLUMNS](#show-columns)
- [Example SHOW COLUMNS output](#example-show-columns-output)
- [SHOW ALL](#show-all)
- [Example SHOW ALL output](#view-show-all-example-output)
## SHOW TABLES
Returns information about tables (measurements) in an InfluxDB bucket.
```sql
SHOW TABLES
```
You can also query the `information_schema.tables` view:
```sql
SELECT * FROM information_schema.tables
```
#### Example SHOW TABLES output
_Measurements are those that use the **`iox` table schema**._
| table_catalog | table_schema | table_name | table_type |
| :------------ | :----------------- | :---------- | :--------- |
| public | iox | home | BASE TABLE |
| public | system | queries | BASE TABLE |
| public | information_schema | tables | VIEW |
| public | information_schema | views | VIEW |
| public | information_schema | columns | VIEW |
| public | information_schema | df_settings | VIEW |
## SHOW COLUMNS
Returns information about the schema of a table (measurement) in an InfluxDB bucket.
```sql
SHOW COLUMNS FROM example_table
```
You can also query the `information_schema.columns` view:
```sql
SELECT
table_catalog,
table_schema,
table_name,
column_name,
data_type,
is_nullable
FROM information_schema.columns
WHERE table_name = 'example_table'
```
#### Example SHOW COLUMNS output
| table_catalog | table_schema | table_name | column_name | data_type | is_nullable |
| :------------ | :----------- | :--------- | :---------- | :-------------------------- | :---------- |
| public | iox | home | co | Int64 | YES |
| public | iox | home | hum | Float64 | YES |
| public | iox | home | room | Dictionary(Int32, Utf8) | YES |
| public | iox | home | temp | Float64 | YES |
| public | iox | home | time | Timestamp(Nanosecond, None) | NO |
## SHOW ALL
Returns the configuration options of the current session.
```sql
SHOW ALL
```
You can also query the `information_schema.df_settings` view:
```sql
SELECT * FROM information_schema.df_settings
```
{{< expand-wrapper >}}
{{% expand "View `SHOW ALL` example output" %}}
| name | setting |
| :-------------------------------------------------------- | :------- |
| datafusion.catalog.create_default_catalog_and_schema | true |
| datafusion.catalog.default_catalog | public |
| datafusion.catalog.default_schema | iox |
| datafusion.catalog.format | |
| datafusion.catalog.has_header | false |
| datafusion.catalog.information_schema | true |
| datafusion.catalog.location | |
| datafusion.execution.batch_size | 8192 |
| datafusion.execution.coalesce_batches | true |
| datafusion.execution.collect_statistics | false |
| datafusion.execution.parquet.enable_page_index | false |
| datafusion.execution.parquet.metadata_size_hint | |
| datafusion.execution.parquet.pruning | true |
| datafusion.execution.parquet.pushdown_filters | true |
| datafusion.execution.parquet.reorder_filters | true |
| datafusion.execution.parquet.skip_metadata | true |
| datafusion.execution.target_partitions | 4 |
| datafusion.execution.time_zone | +00:00 |
| datafusion.explain.logical_plan_only | false |
| datafusion.explain.physical_plan_only | false |
| datafusion.optimizer.enable_round_robin_repartition | true |
| datafusion.optimizer.filter_null_join_keys | false |
| datafusion.optimizer.hash_join_single_partition_threshold | 1048576 |
| datafusion.optimizer.max_passes | 3 |
| datafusion.optimizer.prefer_hash_join | true |
| datafusion.optimizer.repartition_aggregations | true |
| datafusion.optimizer.repartition_file_min_size | 10485760 |
| datafusion.optimizer.repartition_file_scans | true |
| datafusion.optimizer.repartition_joins | true |
| datafusion.optimizer.repartition_sorts | false |
| datafusion.optimizer.repartition_windows | true |
| datafusion.optimizer.skip_failed_rules | true |
| datafusion.optimizer.top_down_join_key_reordering | true |
| datafusion.sql_parser.enable_ident_normalization | true |
| datafusion.sql_parser.parse_float_as_decimal | false |
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
The content of this page is at /content/shared/sql-reference/information-schema.md
-->

View File

@ -7,267 +7,10 @@ menu:
name: JOIN clause
parent: SQL reference
weight: 202
source: /content/shared/sql-reference/join.md
---
Use the `JOIN` clause to join data from different tables together based on
logical relationships.
- [Syntax](#syntax)
- [Join types](#join-types)
- [INNER JOIN](#inner-join)
- [LEFT [OUTER] JOIN](#left-outer-join)
- [RIGHT [OUTER] JOIN](#right-outer-join)
- [FULL [OUTER] JOIN](#full-outer-join)
- [Troubleshoot joins](#troubleshoot-joins)
## Syntax
```sql
SELECT_clause
FROM <left_join_items>
[INNER | LEFT [OUTER] | RIGHT [OUTER] | FULL [OUTER]] JOIN <right_join_items>
ON <join_condition>
[WHERE_clause]
[GROUP_BY_clause]
[HAVING_clause]
[ORDER_BY_clause]
```
### Arguments
- **left_join_items**: One or more tables specified in the `FROM` clause that
represent the left side of the join.
- **right_join_items**: One or more tables specified in the `JOIN` clause that
represent the right side of the join.
- **join_condition**: A predicate expression in the `ON` clause that uses the
`=` (equal to) comparison operator to compare column values from the left side
of the join to column values on the right side of the join. Rows with values
that match the defined predicate are joined using the specified
[join type](#join-types).
<!-- Link anchor for fully-qualified references -->
<div id="fully-qualified-reference"></div>
{{% note %}}
If both sides of the join include columns with the same name, you need to
use the fully-qualified reference to prevent ambiguity.
A _fully-qualified reference_ uses dot notation to reference both the table name
and the column name--for example: `table_name.column_name`
{{% /note %}}
## Join types
The following joins types are supported:
{{< flex >}}
{{< flex-content "quarter" >}}
<a href="#inner-join">
<p style="text-align:center"><strong>INNER JOIN</strong></p>
{{< svg svg="static/svgs/join-diagram.svg" class="inner small center" >}}
</a>
{{< /flex-content >}}
{{< flex-content "quarter" >}}
<a href="#left-outer-join">
<p style="text-align:center"><strong>LEFT [OUTER] JOIN</strong></p>
{{< svg svg="static/svgs/join-diagram.svg" class="left small center" >}}
</a>
{{< /flex-content >}}
{{< flex-content "quarter" >}}
<a href="#right-outer-join">
<p style="text-align:center"><strong>RIGHT [OUTER] JOIN</strong></p>
{{< svg svg="static/svgs/join-diagram.svg" class="right small center" >}}
</a>
{{< /flex-content >}}
{{< flex-content "quarter" >}}
<a href="#full-outer-join">
<p style="text-align:center"><strong>FULL [OUTER] JOIN</strong></p>
{{< svg svg="static/svgs/join-diagram.svg" class="full small center" >}}
</a>
{{< /flex-content >}}
{{< /flex >}}
#### Join sample tables
The examples below illustrate join methods using the following tables:
{{% influxdb/custom-timestamps %}}
##### prod_line
| time | station | produced |
| :------------------- | :-----: | -------: |
| 2022-01-01T08:00:00Z | B1 | 26 |
| 2022-01-01T09:00:00Z | B1 | 54 |
| 2022-01-01T10:00:00Z | B1 | 56 |
| 2022-01-01T11:00:00Z | B1 | |
| 2022-01-01T12:00:00Z | B1 | 82 |
##### errors
| time | station | level | message |
| :------------------- | :-----: | :---: | :------------------- |
| 2022-01-01T10:00:00Z | B1 | warn | Maintenance required |
| 2022-01-01T11:00:00Z | B1 | crit | Station offline |
{{% /influxdb/custom-timestamps %}}
### INNER JOIN
Inner joins combine rows from tables on the left and right side of the join
based on common column values defined in the `ON` clause. Rows that don't have
matching column values are not included in the output table.
{{% influxdb/custom-timestamps %}}
#### Inner join example
{{% caption %}}[View sample tables](#join-sample-tables){{% /caption %}}
```sql
SELECT
*
FROM
prod_line
RIGHT JOIN errors ON
prod_line.time = errors.time
AND prod_line.station = errors.station
ORDER BY
prod_line.time
```
##### Inner join results
| time | station | produced | time | station | level | message |
| :------------------- | :-----: | -------: | :------------------- | :-----: | :---: | :------------------- |
| 2022-01-01T10:00:00Z | B1 | 56 | 2022-01-01T10:00:00Z | B1 | warn | Maintenance required |
| 2022-01-01T11:00:00Z | B1 | | 2022-01-01T11:00:00Z | B1 | crit | Station offline |
{{% /influxdb/custom-timestamps %}}
### LEFT [OUTER] JOIN
A left outer join returns all rows from the left side of the join and only
returns data from the right side of the join in rows with matching column values
defined in the `ON` clause.
{{% influxdb/custom-timestamps %}}
#### Left outer join example
{{% caption %}}[View sample tables](#join-sample-tables){{% /caption %}}
```sql
SELECT
*
FROM
prod_line
LEFT JOIN errors ON
prod_line.time = errors.time
AND prod_line.station = errors.station
ORDER BY
prod_line.time
```
##### Left outer join results
| time | station | produced | time | station | level | message |
| -------------------- | ------- | -------- | -------------------- | ------- | ----- | -------------------- |
| 2022-01-01T08:00:00Z | B1 | 26 | | | | |
| 2022-01-01T09:00:00Z | B1 | 54 | | | | |
| 2022-01-01T10:00:00Z | B1 | 56 | 2022-01-01T10:00:00Z | B1 | warn | Maintenance required |
| 2022-01-01T11:00:00Z | B1 | | 2022-01-01T11:00:00Z | B1 | crit | Station offline |
| 2022-01-01T12:00:00Z | B1 | 82 | | | | |
{{% /influxdb/custom-timestamps %}}
### RIGHT [OUTER] JOIN
A right outer join returns all rows from the right side of the join and only
returns data from the left side of the join in rows with matching column values
defined in the `ON` clause.
{{% influxdb/custom-timestamps %}}
#### Right outer join example
{{% caption %}}[View sample tables](#join-sample-tables){{% /caption %}}
```sql
SELECT
*
FROM
prod_line
RIGHT JOIN errors ON
prod_line.time = errors.time
AND prod_line.station = errors.station
ORDER BY
prod_line.time
```
##### Right outer join results
| time | station | produced | time | station | level | message |
| :------------------- | :-----: | -------: | :------------------- | :-----: | :---: | :------------------- |
| 2022-01-01T10:00:00Z | B1 | 56 | 2022-01-01T10:00:00Z | B1 | warn | Maintenance required |
| 2022-01-01T11:00:00Z | B1 | | 2022-01-01T11:00:00Z | B1 | crit | Station offline |
{{% /influxdb/custom-timestamps %}}
### FULL [OUTER] JOIN
A full outer join returns all data from the left and right sides of the join and
combines rows with matching column values defined in the `ON` clause.
Data that is not available on each respective side of the join is NULL.
{{% influxdb/custom-timestamps %}}
#### Full outer join example
{{% caption %}}[View sample tables](#join-sample-tables){{% /caption %}}
```sql
SELECT
*
FROM
prod_line
FULL JOIN errors ON
prod_line.time = errors.time
AND prod_line.station = errors.station
ORDER BY
time
```
##### Full outer join results
| time | station | produced | time | station | level | message |
| -------------------- | ------- | -------- | -------------------- | ------- | ----- | -------------------- |
| 2022-01-01T08:00:00Z | B1 | 26 | | | | |
| 2022-01-01T09:00:00Z | B1 | 54 | | | | |
| 2022-01-01T10:00:00Z | B1 | 56 | 2022-01-01T10:00:00Z | B1 | warn | Maintenance required |
| 2022-01-01T11:00:00Z | B1 | | 2022-01-01T11:00:00Z | B1 | crit | Station offline |
| 2022-01-01T12:00:00Z | B1 | 82 | | | | |
{{% /influxdb/custom-timestamps %}}
## Troubleshoot joins
### Ambiguous reference to unqualified field
If a column exists on both sides of the join and is used in in the `SELECT`,
`ON`, `WHERE`, `HAVING`, `GROUP BY`, or `ORDER BY` clause, you must use a
[fully-qualified reference](#fully-qualified-reference). For example, if both
sides of the join have a `time` column and you want to explicitly select a
time column, you must specifiy which side of the join to use the time column from:
{{% code-callout "prod_line.time" "green" %}}
```
SELECT
prod_line.time,
produced,
message,
FROM
prod_line
INNER JOIN errors ON
-- ...
```
{{% /code-callout %}}
<!--
The content of this page is at /content/shared/sql-reference/join.md
-->

View File

@ -7,70 +7,10 @@ menu:
name: LIMIT clause
parent: SQL reference
weight: 206
source: /content/shared/sql-reference/limit.md
---
The `LIMIT` clause limits the number of rows returned by a query to a specified non-negative integer.
- [Syntax](#syntax)
- [Examples](#examples)
## Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] LIMIT <N>
```
## Examples
### Limit results to a maximum of five rows
```sql
SELECT
"water_level","location", "time"
FROM
"h2o_feet"
LIMIT
5
```
{{< expand-wrapper >}}
{{% expand "View example results" %}}
The query returns a maximum of 5 results.
| location | time | water_level |
| :----------- | :----------------------- | ----------- |
| coyote_creek | 2019-08-28T00:00:00.000Z | 4.206 |
| coyote_creek | 2019-08-28T00:06:00.000Z | 4.052 |
| coyote_creek | 2019-08-28T00:12:00.000Z | 3.901 |
| coyote_creek | 2019-08-28T00:18:00.000Z | 3.773 |
| coyote_creek | 2019-08-28T00:24:00.000Z | 3.632 |
{{% /expand %}}
{{< /expand-wrapper >}}
### Sort and limit results
Use the `ORDER BY` and `LIMIT` clauses to first sort results by specified columns,
then limit the sorted results by a specified number.
```sql
SELECT
"water_level", "location", "time"
FROM
"h2o_feet"
ORDER BY
"water_level" DESC
LIMIT
3
```
{{< expand-wrapper >}}
{{% expand "View example results" %}}
The query returns the highest 3 `water_level` readings in the `h2o_feet` measurement.
| location | time | water_level |
| :----------- | :----------------------- | ----------- |
| coyote_creek | 2019-08-27T13:42:00.000Z | -0.561 |
| coyote_creek | 2019-08-29T15:24:00.000Z | -0.571 |
| coyote_creek | 2019-08-28T14:24:00.000Z | -0.587 |
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
The content of this page is at /content/shared/sql-reference/limit.md
-->

View File

@ -8,11 +8,10 @@ menu:
name: Operators
parent: SQL reference
weight: 211
source: /content/shared/sql-reference/operators/_index.md
---
SQL operators are reserved words or characters which perform certain operations,
including comparisons and arithmetic.
{{< children type="anchored-list" >}}
{{< children hlevel="h2" >}}
<!--
The content of this page is at /content/shared/sql-reference/operators/_index.md
-->

View File

@ -17,140 +17,10 @@ list_code_example: |
| `*` | Multiplication | `2 * 3` | `6` |
| `/` | Division | `6 / 3` | `2` |
| `%` | Modulo | `7 % 2` | `1` |
source: /content/shared/sql-reference/operators/arithmetic.md
---
Arithmetic operators take two numeric values (either literals or variables)
and perform a calculation that returns a single numeric value.
| Operator | Description | |
| :------: | :------------- | :------------------------------------- |
| `+` | Addition | [{{< icon "link" >}}](#addition) |
| `-` | Subtraction | [{{< icon "link" >}}](#subtraction) |
| `*` | Multiplication | [{{< icon "link" >}}](#multiplication) |
| `/` | Division | [{{< icon "link" >}}](#division) |
| `%` | Modulo | [{{< icon "link" >}}](#modulo) |
## + {#addition .monospace}
The `+` operator adds two operands together and returns the sum.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 1 + 2
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| int64(1) + int64(2) |
| ------------------: |
| 3 |
{{% /flex-content %}}
{{< /flex >}}
## - {#subtraction .monospace}
The `-` operator subtracts the right operand from the left operand and returns
the difference.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 4 - 2
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| int64(4) - int64(2) |
| ------------------: |
| 2 |
{{% /flex-content %}}
{{< /flex >}}
## * {#multiplication .monospace}
The `*` operator multiplies two operands together and returns the product.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 2 * 3
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| int64(2) * int64(3) |
| ------------------: |
| 6 |
{{% /flex-content %}}
{{< /flex >}}
## / {#division .monospace}
The `/` operator divides the left operand by the right operand and returns the quotient.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 6 / 3
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| int64(6) / int64(3) |
| ------------------: |
| 2 |
{{% /flex-content %}}
{{< /flex >}}
## % {#modulo .monospace}
The `%` (modulo) operator divides the left operand by the right operand and returns the
remainder. If the left operand is not divisible by the right operand, it returns
the left operand.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 8 % 3
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Int64(8) % Int64(3) |
| ------------------: |
| 2 |
{{% /flex-content %}}
{{< /flex >}}
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 3 % 8
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Int64(3) % Int64(8) |
| ------------------: |
| 3 |
{{% /flex-content %}}
{{< /flex >}}
<!--
The content of this page is at /content/shared/sql-reference/operators/arithmetic.md
-->

View File

@ -16,137 +16,10 @@ list_code_example: |
| `^` | Bitwise xor | `5 ^ 3` | `6` |
| `>>` | Bitwise shift right | `5 >> 3` | `0` |
| `<<` | Bitwise shift left | `5 << 3` | `40` |
source: /content/shared/sql-reference/operators/bitwise.md
---
Bitwise operators perform bitwise operations on bit patterns or binary numerals.
| Operator | Meaning | |
| :------: | :------------------ | :------------------------------------------ |
| `&` | Bitwise and | [{{< icon "link" >}}](#bitwise-and) |
| `\|` | Bitwise or | [{{< icon "link" >}}](#bitwise-or) |
| `^` | Bitwise xor | [{{< icon "link" >}}](#bitwise-xor) |
| `>>` | Bitwise shift right | [{{< icon "link" >}}](#bitwise-shift-right) |
| `<<` | Bitwise shift left | [{{< icon "link" >}}](#bitwise-shift-left) |
## & {#bitwise-and .monospace}
The `&` (bitwise AND) operator compares each bit of the left operand to the
corresponding bit of the right operand.
If both bits are 1, the corresponding result bit is set to 1.
Otherwise, the corresponding result bit is set to 0.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 5 & 3
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Int64(5) & Int64(3) |
| ------------------: |
| 1 |
{{% /flex-content %}}
{{< /flex >}}
## \| {#bitwise-or .monospace}
The `|` (bitwise OR or inclusive OR) operator compares each bit of the left
operand to the corresponding bit of the right operand.
If either bit is 1, the corresponding result bit is set to 1.
Otherwise, the corresponding result bit is set to 0.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 5 | 3
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Int64(5) \| Int64(3) |
| -------------------: |
| 7 |
{{% /flex-content %}}
{{< /flex >}}
## ^ {#bitwise-xor .monospace}
The `^` (bitwise XOR or exclusive OR) operator compares each bit of the left
operand to the corresponding bit of the right operand.
If the bit in one of the operands is 0 and the bit in the other operand is 1,
the corresponding result bit is set to 1.
Otherwise, the corresponding result bit is set to 0.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 5 ^ 3
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Int64(5) BIT_XOR Int64(3) |
| ------------------------: |
| 6 |
{{% /flex-content %}}
{{< /flex >}}
## \>\> {#bitwise-shift-right .monospace}
The `>>` (bitwise shift right) operator shifts the bits in the left operand to
the right by the number of positions specified in the right operand.
For unsigned numbers, bit positions vacated by the shift operation are filled with 0.
For signed numbers, the sign bit is used to fill the vacated bit positions.
If the number is positive, the bit position is filled with 0.
If the number is negative, the bit position is filled with 1.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 5 >> 3
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Int64(5) \>\> Int64(3) |
| ---------------------: |
| 0 |
{{% /flex-content %}}
{{< /flex >}}
## \<\< {#bitwise-shift-left .monospace}
The `<<` (bitwise shift left) operator shifts the bits in the left operand to
the left by the number of positions specified in the right operand.
Bit positions vacated by the shift operation are filled with 0.
Bits that shift off the end are discarded, including the sign bit.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 5 << 3
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Int64(5) \<\< Int64(3) |
| ---------------------: |
| 40 |
{{% /flex-content %}}
{{< /flex >}}
<!--
The content of this page is at /content/shared/sql-reference/operators/bitwise.md
-->

View File

@ -23,267 +23,10 @@ list_code_example: |
| `~*` | Matches a regular expression _(case-insensitive)_ | `'Abc' ~* 'A.*'` |
| `!~` | Does not match a regular expression | `'abc' !~ 'd.*'` |
| `!~*` | Does not match a regular expression _(case-insensitive)_ | `'Abc' !~* 'a.*'` |
source: /content/shared/sql-reference/operators/comparison.md
---
Comparison operators evaluate the relationship between the left and right
operands and returns `true` or `false`.
| Operator | Meaning | |
| :------: | :------------------------------------------------------- | :------------------------------------------------------ |
| `=` | Equal to | [{{< icon "link" >}}](#equal-to) |
| `<>` | Not equal to | [{{< icon "link" >}}](#not-equal-to) |
| `!=` | Not equal to | [{{< icon "link" >}}](#not-equal-to) |
| `>` | Greater than | [{{< icon "link" >}}](#greater-than) |
| `>=` | Greater than or equal to | [{{< icon "link" >}}](#greater-than-or-equal) |
| `<` | Less than | [{{< icon "link" >}}](#less-than) |
| `<=` | Less than or equal to | [{{< icon "link" >}}](#less-than-or-equal) |
| `~` | Matches a regular expression | [{{< icon "link" >}}](#regexp-match) |
| `~*` | Matches a regular expression _(case-insensitive)_ | [{{< icon "link" >}}](#regexp-match-case-insensitive) |
| `!~` | Does not match a regular expression | [{{< icon "link" >}}](#regexp-nomatch) |
| `!~*` | Does not match a regular expression _(case-insensitive)_ | [{{< icon "link" >}}](#regexp-nomatch-case-insensitive) |
## = {#equal-to .monospace}
The `=` operator compares the left and right operands and, if equal, returns `true`.
Otherwise returns `false`.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 123 = 123
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Int64(123) = Int64(123) |
| :---------------------- |
| true |
{{% /flex-content %}}
{{< /flex >}}
## !=, <> {#not-equal-to .monospace}
The `!=` and `<>` operators compare the left and right operands and, if not equal,
returns `true`. Otherwise returns `false`.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 123 != 456
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Int64(123) != Int64(456) |
| :----------------------- |
| true |
{{% /flex-content %}}
{{< /flex >}}
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 123 <> 456
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Int64(123) != Int64(456) |
| :----------------------- |
| true |
{{% /flex-content %}}
{{< /flex >}}
## > {#greater-than .monospace}
The `>` operator compares the left and right operands and, if the left operand
is greater than the right operand, returns `true`.
Otherwise returns `false`.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 3 > 2
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Int64(3) > Int64(2) |
| :------------------ |
| true |
{{% /flex-content %}}
{{< /flex >}}
## >= {#greater-than-or-equal .monospace}
The `>=` operator compares the left and right operands and, if the left operand
is greater than or equal to the right operand, returns `true`.
Otherwise returns `false`.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 3 >= 2
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Int64(3) >= Int64(2) |
| :------------------- |
| true |
{{% /flex-content %}}
{{< /flex >}}
## < {#less-than .monospace}
The `<` operator compares the left and right operands and, if the left operand
is less than the right operand, returns `true`.
Otherwise returns `false`.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 1 < 2
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Int641(1) < Int64(2) |
| :------------------- |
| true |
{{% /flex-content %}}
{{< /flex >}}
## <= {#less-than-or-equal .monospace}
The `<=` operator compares the left and right operands and, if the left operand
is less than or equal to the right operand, returns `true`.
Otherwise returns `false`.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 1 <= 2
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Int641(1) <= Int64(2) |
| :-------------------- |
| true |
{{% /flex-content %}}
{{< /flex >}}
## ~ {#regexp-match .monospace}
The `~` operator compares the left string operand to the right regular expression
operand and, if it matches (case-sensitive), returns `true`.
Otherwise returns `false`.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 'abc' ~ 'a.*'
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Utf8("abc") ~ Utf8("a.*") |
| :------------------------ |
| true |
{{% /flex-content %}}
{{< /flex >}}
## ~* {#regexp-match-case-insensitive .monospace}
The `~*` operator compares the left string operand to the right regular expression
operand and, if it matches (case-insensitive), returns `true`.
Otherwise returns `false`.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 'Abc' ~* 'A.*'
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Utf8("Abc") ~* Utf8("A.*") |
| :------------------------- |
| true |
{{% /flex-content %}}
{{< /flex >}}
## !~ {#regexp-nomatch .monospace}
The `!~` operator compares the left string operand to the right regular expression
operand and, if it does not match (case-sensitive), returns `true`.
Otherwise returns `false`.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 'abc' !~ 'd.*'
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Utf8("abc") !~ Utf8("d.*") |
| :------------------------- |
| true |
{{% /flex-content %}}
{{< /flex >}}
## !~* {#regexp-nomatch-case-insensitive .monospace}
The `!~*` operator compares the left string operand to the right regular expression
operand and, if it does not match (case-insensitive), returns `true`.
Otherwise returns `false`.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 'Abc' !~* 'a.*'
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Utf8("Abc") !~* Utf8("a.*") |
| :-------------------------- |
| false |
{{% /flex-content %}}
{{< /flex >}}
<!--
The content of this page is at /content/shared/sql-reference/operators/comparison.md
-->

View File

@ -21,443 +21,10 @@ list_code_example: |
| `LIKE` | Returns true if the left operand matches the right operand pattern string. |
| `NOT` | Negates the subsequent expression. |
| `OR` | Returns true if any operand is true. Otherwise, returns false. |
source: /content/shared/sql-reference/operators/logical.md
---
Logical operators combine or manipulate conditions in a SQL query.
| Operator | Meaning | |
| :-------: | :------------------------------------------------------------------------- | :------------------------------ |
| `AND` | Returns true if both operands are true. Otherwise, returns false. | [{{< icon "link" >}}](#and) |
| `BETWEEN` | Returns true if the left operand is within the range of the right operand. | [{{< icon "link" >}}](#between) |
| `EXISTS` | Returns true if the results of a subquery are not empty. | [{{< icon "link" >}}](#exists) |
| `IN` | Returns true if the left operand is in the right operand list. | [{{< icon "link" >}}](#in) |
| `LIKE` | Returns true if the left operand matches the right operand pattern string. | [{{< icon "link" >}}](#like) |
| `NOT` | Negates the subsequent expression. | [{{< icon "link" >}}](#not) |
| `OR` | Returns true if any operand is true. Otherwise, returns false. | [{{< icon "link" >}}](#or) |
{{% note %}}
#### Sample data
Query examples on this page use the following sample data sets:
- [Get started home sensor sample data](/influxdb/cloud-dedicated/reference/sample-data/#get-started-home-sensor-data)
- [Home sensor actions sample data](/influxdb/cloud-dedicated/reference/sample-data/#home-sensor-actions-data)
{{% /note %}}
## AND {.monospace}
The `AND` operand returns `true` if both operands are `true`. Otherwise, it returns false.
This operator is typically used in the [`WHERE` clause](/influxdb/cloud-dedicated/reference/sql/where/)
to combine multiple conditions.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT true AND false AS "AND condition"
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| AND condition |
| :------------ |
| false |
{{% /flex-content %}}
{{< /flex >}}
##### Examples
{{< expand-wrapper >}}
{{% expand "`AND` operator in the `WHERE` clause" %}}
```sql
SELECT *
FROM home
WHERE
co > 10
AND room = 'Kitchen'
```
{{% influxdb/custom-timestamps %}}
| co | hum | room | temp | time |
| --: | ---: | :------ | ---: | :------------------- |
| 18 | 36.9 | Kitchen | 23.3 | 2022-01-01T18:00:00Z |
| 22 | 36.6 | Kitchen | 23.1 | 2022-01-01T19:00:00Z |
| 26 | 36.5 | Kitchen | 22.7 | 2022-01-01T20:00:00Z |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## BETWEEN {.monospace}
The `BETWEEN` operator returns `true` if the left numeric operand is within the
range specified in the right operand. Otherwise, it returns `false`
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 6 BETWEEN 5 AND 8 AS "BETWEEN condition"
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| BETWEEN condition |
| :---------------- |
| true |
{{% /flex-content %}}
{{< /flex >}}
##### Examples
{{< expand-wrapper >}}
{{% expand "`BETWEEN` operator in the `WHERE` clause" %}}
```sql
SELECT *
FROM home
WHERE
co BETWEEN 5 AND 10
```
{{% influxdb/custom-timestamps %}}
| co | hum | room | temp | time |
| --: | ---: | :---------- | ---: | :------------------- |
| 7 | 36 | Kitchen | 22.4 | 2022-01-01T16:00:00Z |
| 9 | 36 | Kitchen | 22.7 | 2022-01-01T17:00:00Z |
| 5 | 35.9 | Living Room | 22.6 | 2022-01-01T17:00:00Z |
| 9 | 36.2 | Living Room | 22.8 | 2022-01-01T18:00:00Z |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## EXISTS {.monospace}
The `EXISTS` operator returns `true` if result of a
[correlated subquery](/influxdb/cloud-dedicated/reference/sql/subqueries/#correlated-subqueries)
is not empty. Otherwise it returns `false`.
_See [SQL subquery operators](/influxdb/cloud-dedicated/reference/sql/subqueries/#subquery-operators)._
##### Examples
{{< expand-wrapper >}}
{{% expand "`EXISTS` operator with a subquery in the `WHERE` clause" %}}
```sql
SELECT *
FROM
home home_actions
WHERE EXISTS (
SELECT *
FROM home
WHERE
home.co = home_actions.co - 1
)
ORDER BY time
```
{{% influxdb/custom-timestamps %}}
| co | hum | room | temp | time |
| --: | ---: | :---------- | ---: | :------------------- |
| 1 | 36.5 | Kitchen | 22.8 | 2022-01-01T13:00:00Z |
| 1 | 36.3 | Kitchen | 22.8 | 2022-01-01T14:00:00Z |
| 1 | 36.1 | Living Room | 22.3 | 2022-01-01T15:00:00Z |
| 4 | 36 | Living Room | 22.4 | 2022-01-01T16:00:00Z |
| 5 | 35.9 | Living Room | 22.6 | 2022-01-01T17:00:00Z |
| 18 | 36.9 | Kitchen | 23.3 | 2022-01-01T18:00:00Z |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## IN {.monospace}
The `IN` operator returns `true` if the left operand is in the right operand
list or subquery result. Otherwise, it returns `false`.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 'John' IN ('Jane', 'John') AS "IN condition"
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| IN condition |
| :----------- |
| true |
{{% /flex-content %}}
{{< /flex >}}
_See [SQL subquery operators](/influxdb/cloud-dedicated/reference/sql/subqueries/#subquery-operators)._
##### Examples
{{< expand-wrapper >}}
{{% expand "`IN` operator with a list in the `WHERE` clause" %}}
```sql
SELECT *
FROM home
WHERE
room IN ('Bathroom', 'Bedroom', 'Kitchen')
LIMIT 4
```
{{% influxdb/custom-timestamps %}}
| co | hum | room | temp | time |
| --: | ---: | :------ | ---: | :------------------- |
| 0 | 35.9 | Kitchen | 21 | 2022-01-01T08:00:00Z |
| 0 | 36.2 | Kitchen | 23 | 2022-01-01T09:00:00Z |
| 0 | 36.1 | Kitchen | 22.7 | 2022-01-01T10:00:00Z |
| 0 | 36 | Kitchen | 22.4 | 2022-01-01T11:00:00Z |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "`IN` operator with a subquery in the `WHERE` clause" %}}
```sql
SELECT *
FROM home
WHERE
room IN (
SELECT DISTINCT room
FROM home_actions
)
ORDER BY time
LIMIT 4
```
{{% influxdb/custom-timestamps %}}
| co | hum | room | temp | time |
| --: | ---: | :---------- | ---: | :------------------- |
| 0 | 35.9 | Living Room | 21.1 | 2022-01-01T08:00:00Z |
| 0 | 35.9 | Kitchen | 21 | 2022-01-01T08:00:00Z |
| 0 | 35.9 | Living Room | 21.4 | 2022-01-01T09:00:00Z |
| 0 | 36.2 | Kitchen | 23 | 2022-01-01T09:00:00Z |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## LIKE {.monospace}
The `LIKE` operator returns `true` if the left operand matches the string pattern
specified in the right operand.
`LIKE` expressions support [SQL wildcard characters](#sql-wildcard-characters).
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 'John' LIKE 'J_%n' AS "LIKE condition"
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| LIKE condition |
| :------------- |
| true |
{{% /flex-content %}}
{{< /flex >}}
{{< expand-wrapper >}}
{{% expand "`LIKE` operator in the `WHERE` clause" %}}
```sql
SELECT *
FROM home
WHERE
room LIKE '%Room'
LIMIT 4
```
{{% influxdb/custom-timestamps %}}
| co | hum | room | temp | time |
| --: | ---: | :---------- | ---: | :------------------- |
| 0 | 35.9 | Living Room | 21.1 | 2022-01-01T08:00:00Z |
| 0 | 35.9 | Living Room | 21.4 | 2022-01-01T09:00:00Z |
| 0 | 36 | Living Room | 21.8 | 2022-01-01T10:00:00Z |
| 0 | 36 | Living Room | 22.2 | 2022-01-01T11:00:00Z |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
### SQL wildcard characters
The InfluxDB SQL implementation supports the following wildcard characters when
using the `LIKE` operator to match strings to a pattern.
| Character | Description |
| :-------: | :--------------------------------- |
| `%` | Represents zero or more characters |
| `_` | Represents any single character |
## NOT {.monospace}
The `NOT` operator negates the subsequent expression.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT NOT true AS "NOT condition"
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| NOT condition |
| :------------ |
| false |
{{% /flex-content %}}
{{< /flex >}}
##### Examples
{{< expand-wrapper >}}
{{% expand "`NOT IN`" %}}
```sql
SELECT *
FROM home
WHERE
room NOT IN ('Kitchen', 'Bathroom')
LIMIT 4
```
{{% influxdb/custom-timestamps %}}
| co | hum | room | temp | time |
| --: | ---: | :---------- | ---: | :------------------- |
| 0 | 35.9 | Living Room | 21.1 | 2022-01-01T08:00:00Z |
| 0 | 35.9 | Living Room | 21.4 | 2022-01-01T09:00:00Z |
| 0 | 36 | Living Room | 21.8 | 2022-01-01T10:00:00Z |
| 0 | 36 | Living Room | 22.2 | 2022-01-01T11:00:00Z |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "`NOT EXISTS`" %}}
```sql
SELECT *
FROM
home home_actions
WHERE NOT EXISTS (
SELECT *
FROM home
WHERE
home.co = home_actions.co + 4
)
ORDER BY time
```
{{% influxdb/custom-timestamps %}}
| co | hum | room | temp | time |
| --: | ---: | :---------- | ---: | :------------------- |
| 7 | 36 | Kitchen | 22.4 | 2022-01-01T16:00:00Z |
| 4 | 36 | Living Room | 22.4 | 2022-01-01T16:00:00Z |
| 9 | 36 | Kitchen | 22.7 | 2022-01-01T17:00:00Z |
| 9 | 36.2 | Living Room | 22.8 | 2022-01-01T18:00:00Z |
| 17 | 36.4 | Living Room | 22.2 | 2022-01-01T20:00:00Z |
| 26 | 36.5 | Kitchen | 22.7 | 2022-01-01T20:00:00Z |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "`NOT BETWEEN`" %}}
```sql
SELECT *
FROM home
WHERE
co NOT BETWEEN 1 AND 22
AND room = 'Kitchen'
```
{{% influxdb/custom-timestamps %}}
| co | hum | room | temp | time |
| --: | ---: | :------ | ---: | :------------------- |
| 0 | 35.9 | Kitchen | 21 | 2022-01-01T08:00:00Z |
| 0 | 36.2 | Kitchen | 23 | 2022-01-01T09:00:00Z |
| 0 | 36.1 | Kitchen | 22.7 | 2022-01-01T10:00:00Z |
| 0 | 36 | Kitchen | 22.4 | 2022-01-01T11:00:00Z |
| 0 | 36 | Kitchen | 22.5 | 2022-01-01T12:00:00Z |
| 26 | 36.5 | Kitchen | 22.7 | 2022-01-01T20:00:00Z |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## OR {.monospace}
The `OR` operator returns `true` if any operand is `true`.
Otherwise, it returns `false`.
This operator is typically used in the [`WHERE` clause](/influxdb/cloud-dedicated/reference/sql/where/)
to combine multiple conditions.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT true OR false AS "OR condition"
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| OR condition |
| :----------- |
| true |
{{% /flex-content %}}
{{< /flex >}}
##### Examples
{{< expand-wrapper >}}
{{% expand "`OR` in the `WHERE` clause" %}}
```sql
SELECT *
FROM home
WHERE
co > 20
OR temp > 23
```
{{% influxdb/custom-timestamps %}}
| co | hum | room | temp | time |
| --: | ---: | :------ | ---: | :------------------- |
| 18 | 36.9 | Kitchen | 23.3 | 2022-01-01T18:00:00Z |
| 22 | 36.6 | Kitchen | 23.1 | 2022-01-01T19:00:00Z |
| 26 | 36.5 | Kitchen | 22.7 | 2022-01-01T20:00:00Z |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
The content of this page is at /content/shared/sql-reference/operators/logical.md
-->

View File

@ -13,74 +13,10 @@ list_code_example: |
| :------------: | :----------------------- | :-------------------------------------- | :------------ |
| `\|\|` | Concatenate strings | `'Hello' \|\| ' world'` | `Hello world` |
| `AT TIME ZONE` | Apply a time zone offset | _[View example](/influxdb/cloud-dedicated/reference/sql/operators/other/#at-time-zone)_ | |
source: /content/shared/sql-reference/operators/other.md
---
SQL supports miscellaneous operators that perform various operations.
| Operator | Meaning | |
| :------------: | :----------------------- | :------------------------------------------ |
| `\|\|` | Concatenate strings | [{{< icon "link" >}}](#concatenate-strings) |
| `AT TIME ZONE` | Apply a time zone offset | [{{< icon "link" >}}](#at-time-zone) |
## || {#concatenate-strings}
The `||` operator concatenates two string operands into a single string.
{{< flex >}}
{{% flex-content "two-thirds operator-example" %}}
```sql
SELECT 'Hello' || ' world' AS "Concatenated"
```
{{% /flex-content %}}
{{% flex-content "third operator-example" %}}
| Concatenated |
| :----------- |
| Hello world |
{{% /flex-content %}}
{{< /flex >}}
## AT TIME ZONE
The `AT TIME ZONE` operator takes the timestamp in the left operand and returns
an equivalent timestamp with the updated time and offset of the time zone
specified in the right operand.
If no time zone is included in the input timestamp's
[Arrow data type](/influxdb/cloud-dedicated/reference/sql/data-types/#sql-and-arrow-data-types),
the operator assumes the time is in the time zone specified.
Time zone offsets are provided by the operating system time zone database.
```sql
SELECT time AT TIME ZONE 'America/Los_Angeles' FROM home
```
{{< expand-wrapper >}}
{{% expand "Convert a UTC timestamp to a specified timezone" %}}
```sql
SELECT
arrow_cast('2024-01-01 00:00:00', 'Timestamp(Nanosecond, Some("UTC"))')
AT TIME ZONE 'America/Los_Angeles' AS 'Time with TZ offset'
```
| Time with TZ offset |
| :------------------------ |
| 2023-12-31T16:00:00-08:00 |
{{% /expand %}}
{{% expand "Add a time zone offset to a timestamp without a specified timezone" %}}
```sql
SELECT
'2024-01-01 00:00:00' AT TIME ZONE 'America/Los_Angeles' AS 'Local time with TZ offset'
```
| Local time with TZ offset |
| :------------------------ |
| 2024-01-01T00:00:00-08:00 |
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
The content of this page is at /content/shared/sql-reference/operators/other.md
-->

View File

@ -8,91 +8,10 @@ menu:
name: ORDER BY clause
parent: SQL reference
weight: 204
source: /content/shared/sql-reference/order-by.md
---
The `ORDER BY` clause sort results by specified columns and order.
Sort data based on fields, tags, and timestamps.
The following orders are supported:
- `ASC`: ascending _(default)_
- `DESC`: descending
- [Syntax](#syntax)
- [Examples](#examples)
## Syntax
```sql
[SELECT CLAUSE] [FROM CLAUSE] [ ORDER BY expression [ ASC | DESC ][, …] ]
```
{{% note %}}
**Note:** If your query includes a `GROUP BY` clause, the `ORDER BY` clause must appear **after** the `GROUP BY` clause.
{{% /note %}}
## Examples
### Sort data by time with the most recent first
```sql
SELECT
"water_level", "time"
FROM
"h2o_feet"
WHERE
"location" = 'coyote_creek'
ORDER BY
time DESC
```
{{< expand-wrapper >}}
{{% expand "View example results" %}}
| time | water_level |
| :----------------------- | :----------- |
| 2019-09-17T16:24:00.000Z | 3.235 |
| 2019-09-17T16:18:00.000Z | 3.314 |
| 2019-09-17T16:12:00.000Z | 3.402 |
| 2019-09-17T16:06:00.000Z | 3.497 |
| 2019-09-17T16:00:00.000Z | 3.599 |
| 2019-09-17T15:54:00.000Z | 3.704 |
{{% /expand %}}
{{< /expand-wrapper >}}
### Sort data by tag or field values
```sql
SELECT
"water_level", "time", "location"
FROM
"h2o_feet"
ORDER BY
"location", "water_level" DESC
```
### Sort data by selection order
```sql
SELECT
"location","water_level", "time"
FROM
"h2o_feet"
ORDER BY
1, 2
```
{{< expand-wrapper >}}
{{% expand "View example results" %}}
The query sorts results the location of a column in the `SELECT` statement:
first by `location` (1), and second by `water_level` (2).
| location | time | water_level |
| :----------- | :----------------------- | :---------- |
| coyote_creek | 2019-08-28T14:30:00.000Z | -0.61 |
| coyote_creek | 2019-08-29T15:18:00.000Z | -0.594 |
| coyote_creek | 2019-08-28T14:36:00.000Z | -0.591 |
| coyote_creek | 2019-08-28T14:24:00.000Z | -0.587 |
| coyote_creek | 2019-08-29T15:24:00.000Z | -0.571 |
| coyote_creek | 2019-08-27T13:42:00.000Z | -0.561 |
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
The content of this page is at /content/shared/sql-reference/order-by.md
-->

View File

@ -9,106 +9,10 @@ menu:
weight: 201
related:
- /influxdb/cloud-dedicated/reference/sql/subqueries/
source: /content/shared/sql-reference/select.md
---
Use the `SELECT` statement to query data from an InfluxDB measurement.
The `SELECT` clause is required when querying data in SQL.
- [Syntax](#syntax)
- [Examples](#examples)
### Syntax
```sql
SELECT a, b, "time" FROM <measurement>
```
{{% note %}}
**Note:** When querying InfluxDB, the `SELECT` statement **always requires** a `FROM` clause.
{{% /note %}}
The SELECT clause supports the following:
- `SELECT *` - return all tags, fields and timestamps.
- `SELECT DISTINCT` to return all distinct (different) values.
- `SELECT <"field" or "tag">` - returns a specified field or tag.
- `SELECT <"field" or "tag">, <"field" or "tag">` - returns more than one tag or field.
- `SELECT <"field"> AS a `- return the field as the alias.
## Examples
The following examples use data from the NOAA database.
To download the NOAA test data see [NOAA water sample data](/influxdb/v2/reference/sample-data/#noaa-water-sample-data).
### Select all fields and tags from a measurement
```sql
SELECT * FROM h2o_feet LIMIT 10
```
{{< expand-wrapper >}}
{{% expand "View example results" %}}
| level description | location | time | water_level |
| :------------------------ | :----------- | :----------------------- | :---------- |
| at or greater than 9 feet | coyote_creek | 2019-09-01T00:00:00.000Z | 9.126144144 |
| at or greater than 9 feet | coyote_creek | 2019-09-01T00:06:00.000Z | 9.009 |
| between 6 and 9 feet | coyote_creek | 2019-09-01T00:12:00.000Z | 8.862 |
| between 6 and 9 feet | coyote_creek | 2019-09-01T00:18:00.000Z | 8.714 |
{{% /expand %}}
{{< /expand-wrapper >}}
### Select specific tags and fields from a measurement
```sql
SELECT "location", "water_level" FROM "h2o_feet"
```
{{< expand-wrapper >}}
{{% expand "View example results" "1" %}}
| location | water_level |
| :----------- | :---------- |
| coyote_creek | 9.126144144 |
| coyote_creek | 9.009 |
| coyote_creek | 8.862 |
| coyote_creek | 8.714 |
| coyote_creek | 8.547 |
{{% /expand %}}
{{< /expand-wrapper >}}
### Select a field, tag and timestamp from a measurement
```sql
SELECT "water_level", "location", "time" FROM "h2o_feet"
```
{{< expand-wrapper >}}
{{% expand "View example results" "2" %}}
| location | time | water_level |
| :----------- | :----------------------- | :---------- |
| coyote_creek | 2019-08-20T00:00:00.000Z | 8.638 |
| coyote_creek | 2019-08-20T00:06:00.000Z | 8.658 |
| coyote_creek | 2019-08-20T00:12:00.000Z | 8.678 |
{{% /expand %}}
{{< /expand-wrapper >}}
### Select a field and perform basic arithmetic
The following query takes the value of water_level, multiplies it by 3 and adds 5 to the result.
```sql
SELECT ("water_level" * 3) + 5 FROM "h2o_feet"
```
{{< expand-wrapper >}}
{{% expand "View example results" "3" %}}
| water_level |
| :----------------- |
| 30.128 |
| 30.641000000000002 |
| 31.142000000000003 |
| 31.586 |
| 32.027 |
| 32.378432432 |
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
The content of this page is at /content/shared/sql-reference/select.md
-->

View File

@ -13,744 +13,10 @@ related:
- /influxdb/cloud-dedicated/reference/sql/select/
- /influxdb/cloud-dedicated/reference/sql/where/
- /influxdb/cloud-dedicated/reference/sql/having/
source: /content/shared/sql-reference/subqueries.md
---
Subqueries (also known as inner queries or nested queries) are queries within
a query.
Subqueries can be used in `SELECT`, `FROM`, `WHERE`, and `HAVING` clauses.
- [Subquery operators](#subquery-operators)
- [[ NOT ] EXISTS](#-not--exists)
- [[ NOT ] IN](#-not--in)
- [SELECT clause subqueries](#select-clause-subqueries)
- [FROM clause subqueries](#from-clause-subqueries)
- [WHERE clause subqueries](#where-clause-subqueries)
- [HAVING clause subqueries](#having-clause-subqueries)
- [Subquery categories](#subquery-categories)
- [Correlated subqueries](#correlated-subqueries)
- [Non-correlated subqueries](#non-correlated-subqueries)
- [Scalar subqueries](#scalar-subqueries)
- [Non-scalar subqueries](#non-scalar-subqueries)
{{% note %}}
#### Sample data
Query examples on this page use the following sample data sets:
- [Get started home sensor sample data](/influxdb/cloud-dedicated/reference/sample-data/#get-started-home-sensor-data)
- [Home sensor actions sample data](/influxdb/cloud-dedicated/reference/sample-data/#home-sensor-actions-data)
- [NOAA Bay Area weather sample data](/influxdb/cloud-dedicated/reference/sample-data/#noaa-bay-area-weather-data)
{{% /note %}}
## Subquery operators
- [[ NOT ] EXISTS](#-not--exists)
- [[ NOT ] IN](#-not--in)
### [ NOT ] EXISTS
The `EXISTS` operator returns all rows where a
_[correlated subquery](#correlated-subqueries)_ produces one or more matches for
that row. `NOT EXISTS` returns all rows where a _correlated subquery_ produces
zero matches for that row. Only _correlated subqueries_ are supported.
#### Syntax {#-not-exists-syntax}
```sql
[NOT] EXISTS (subquery)
```
### [ NOT ] IN
The `IN` operator returns all rows where a given expressions value can be found
in the results of a _[correlated subquery](#correlated-subqueries)_.
`NOT IN` returns all rows where a given expressions value cannot be found in
the results of a subquery or list of values.
#### Syntax {#-not-in-syntax}
```sql
expression [NOT] IN (subquery|list-literal)
```
#### Examples {#-not-in-examples}
{{< expand-wrapper >}}
{{% expand "View `IN` examples using a query" %}}
{{< code-tabs-wrapper >}}
{{% code-tabs %}}
[IN](#)
[NOT IN](#)
{{% /code-tabs %}}
{{% code-tab-content %}}
```sql
SELECT
time,
room,
temp
FROM
home
WHERE
room IN (
SELECT
DISTINCT room
FROM
home_actions
)
```
{{% /code-tab-content %}}
{{% code-tab-content %}}
```sql
SELECT
time,
room,
temp
FROM
home
WHERE
room NOT IN (
SELECT
DISTINCT room
FROM
home_actions
)
```
{{% /code-tab-content %}}
{{< /code-tabs-wrapper >}}
{{% /expand %}}
{{% expand "View `IN` examples using a list literal" %}}
{{< code-tabs-wrapper >}}
{{% code-tabs %}}
[IN](#)
[NOT IN](#)
{{% /code-tabs %}}
{{% code-tab-content %}}
```sql
SELECT
time,
room,
temp
FROM home
WHERE room IN ('Bathroom', 'Bedroom', 'Kitchen')
```
{{% /code-tab-content %}}
{{% code-tab-content %}}
```sql
SELECT
time,
room,
temp
FROM home
WHERE room NOT IN ('Bathroom', 'Bedroom', 'Kitchen')
```
{{% /code-tab-content %}}
{{< /code-tabs-wrapper >}}
{{% /expand %}}
{{< /expand-wrapper >}}
## SELECT clause subqueries
`SELECT` clause subqueries use values returned from the inner query as part
of the outer query's `SELECT` list.
The `SELECT` clause only supports [scalar subqueries](#scalar-subqueries) that
return a single value per execution of the inner query.
The returned value can be unique per row.
### Syntax {#select-subquery-syntax}
```sql
SELECT [expression1[, expression2, ..., expressionN],] (<subquery>)
```
{{% note %}}
`SELECT` clause subqueries can be used as an alternative to `JOIN` operations.
{{% /note %}}
### Examples {#select-subquery-examples}
{{< expand-wrapper >}}
{{% expand "`SELECT` clause with correlated subquery" %}}
```sql
SELECT
time,
room,
co,
(
SELECT
MAX(description)
FROM
home_actions
WHERE
time = home.time
AND room = home.room
AND level != 'ok'
) AS "Alert Description"
FROM
home
ORDER BY
room,
time
```
#### Inner query results
Because the inner query is a [correlated subquery](#correlated-subqueries),
the result depends on the values of `room` and `time` columns in the outer query.
The results below represent the action description for each `room` and `time`
combination with a `level` value that does not equal `ok`.
{{% influxdb/custom-timestamps %}}
| time | room | MAX(home_actions.description) |
| :------------------- | :---------- | :------------------------------------------ |
| 2022-01-01T18:00:00Z | Kitchen | Carbon monoxide level above normal: 18 ppm. |
| 2022-01-01T19:00:00Z | Kitchen | Carbon monoxide level above normal: 22 ppm. |
| 2022-01-01T20:00:00Z | Kitchen | Carbon monoxide level above normal: 26 ppm. |
| 2022-01-01T19:00:00Z | Living Room | Carbon monoxide level above normal: 14 ppm. |
| 2022-01-01T20:00:00Z | Living Room | Carbon monoxide level above normal: 17 ppm. |
{{% /influxdb/custom-timestamps %}}
#### Outer query results
{{% influxdb/custom-timestamps %}}
| time | room | co | Alert Description |
| :------------------- | :---------- | --: | :------------------------------------------ |
| 2022-01-01T08:00:00Z | Kitchen | 0 | |
| 2022-01-01T09:00:00Z | Kitchen | 0 | |
| 2022-01-01T10:00:00Z | Kitchen | 0 | |
| 2022-01-01T11:00:00Z | Kitchen | 0 | |
| 2022-01-01T12:00:00Z | Kitchen | 0 | |
| 2022-01-01T13:00:00Z | Kitchen | 1 | |
| 2022-01-01T14:00:00Z | Kitchen | 1 | |
| 2022-01-01T15:00:00Z | Kitchen | 3 | |
| 2022-01-01T16:00:00Z | Kitchen | 7 | |
| 2022-01-01T17:00:00Z | Kitchen | 9 | |
| 2022-01-01T18:00:00Z | Kitchen | 18 | Carbon monoxide level above normal: 18 ppm. |
| 2022-01-01T19:00:00Z | Kitchen | 22 | Carbon monoxide level above normal: 22 ppm. |
| 2022-01-01T20:00:00Z | Kitchen | 26 | Carbon monoxide level above normal: 26 ppm. |
| 2022-01-01T08:00:00Z | Living Room | 0 | |
| 2022-01-01T09:00:00Z | Living Room | 0 | |
| 2022-01-01T10:00:00Z | Living Room | 0 | |
| 2022-01-01T11:00:00Z | Living Room | 0 | |
| 2022-01-01T12:00:00Z | Living Room | 0 | |
| 2022-01-01T13:00:00Z | Living Room | 0 | |
| 2022-01-01T14:00:00Z | Living Room | 0 | |
| 2022-01-01T15:00:00Z | Living Room | 1 | |
| 2022-01-01T16:00:00Z | Living Room | 4 | |
| 2022-01-01T17:00:00Z | Living Room | 5 | |
| 2022-01-01T18:00:00Z | Living Room | 9 | |
| 2022-01-01T19:00:00Z | Living Room | 14 | Carbon monoxide level above normal: 14 ppm. |
| 2022-01-01T20:00:00Z | Living Room | 17 | Carbon monoxide level above normal: 17 ppm. |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## FROM clause subqueries
`FROM` clause subqueries return a set of results that is then queried and
operated on by the outer query.
### Syntax {#from-subquery-syntax}
```sql
SELECT expression1[, expression2, ..., expressionN] FROM (<subquery>)
```
### Examples {#from-subquery-examples}
{{< expand-wrapper >}}
{{% expand "View `FROM` clause subquery example" %}}
The following query returns the average of maximum values per room.
The inner query returns the maximum value for each field from each room.
The outer query uses the results of the inner query and returns the average
maximum value for each field.
```sql
SELECT
AVG(max_co) AS avg_max_co,
AVG(max_hum) AS avg_max_hum,
AVG(max_temp) AS avg_max_temp
FROM
(
SELECT
room,
MAX(co) AS max_co,
MAX(hum) AS max_hum,
MAX(temp) AS max_temp
FROM
home
GROUP BY
room
)
```
#### Inner query results
| room | max_co | max_hum | max_temp |
| :---------- | -----: | ------: | -------: |
| Living Room | 17 | 36.4 | 22.8 |
| Kitchen | 26 | 36.9 | 23.3 |
#### Outer query results
| avg_max_co | avg_max_hum | avg_max_temp |
| ---------: | ----------: | -----------: |
| 21.5 | 36.7 | 23.1 |
{{% /expand %}}
{{< /expand-wrapper >}}
## WHERE clause subqueries
[`WHERE` clause](/influxdb/cloud-dedicated/reference/sql/where/) subqueries
compare an expression to the result of the subquery and return _true_ or _false_.
Rows that evaluate to _false_ or NULL are filtered from results.
The `WHERE` clause supports correlated and non-correlated subqueries
as well as scalar and non-scalar subqueries (depending on the the operator used
in the predicate expression).
### Syntax {#where-subquery-syntax}
```sql
SELECT
expression1[, expression2, ..., expressionN]
FROM
<measurement>
WHERE
expression operator (<subquery>)
```
{{% note %}}
`WHERE` clause subqueries can be used as an alternative to `JOIN` operations.
{{% /note %}}
### Examples {#where-subquery-examples}
{{< expand-wrapper >}}
{{% expand "`WHERE` clause with scalar subquery" %}}
The following query returns all points with `temp` values above the average
of all `temp` values. The subquery returns the average `temp` value.
```sql
SELECT
*
FROM
home
WHERE
temp > (
SELECT
AVG(temp)
FROM
home
)
```
#### Inner query result
| AVG(home.temp) |
| :----------------- |
| 22.396153846153844 |
#### Outer query result
{{% influxdb/custom-timestamps %}}
| co | hum | room | temp | time |
| --: | ---: | :---------- | ---: | :------------------- |
| 0 | 36.2 | Kitchen | 23 | 2022-01-01T09:00:00Z |
| 0 | 36.1 | Kitchen | 22.7 | 2022-01-01T10:00:00Z |
| 0 | 36 | Kitchen | 22.4 | 2022-01-01T11:00:00Z |
| 0 | 36 | Kitchen | 22.5 | 2022-01-01T12:00:00Z |
| 1 | 36.5 | Kitchen | 22.8 | 2022-01-01T13:00:00Z |
| 1 | 36.3 | Kitchen | 22.8 | 2022-01-01T14:00:00Z |
| 3 | 36.2 | Kitchen | 22.7 | 2022-01-01T15:00:00Z |
| 7 | 36 | Kitchen | 22.4 | 2022-01-01T16:00:00Z |
| 9 | 36 | Kitchen | 22.7 | 2022-01-01T17:00:00Z |
| 18 | 36.9 | Kitchen | 23.3 | 2022-01-01T18:00:00Z |
| 22 | 36.6 | Kitchen | 23.1 | 2022-01-01T19:00:00Z |
| 26 | 36.5 | Kitchen | 22.7 | 2022-01-01T20:00:00Z |
| 0 | 36 | Living Room | 22.4 | 2022-01-01T13:00:00Z |
| 4 | 36 | Living Room | 22.4 | 2022-01-01T16:00:00Z |
| 5 | 35.9 | Living Room | 22.6 | 2022-01-01T17:00:00Z |
| 9 | 36.2 | Living Room | 22.8 | 2022-01-01T18:00:00Z |
| 14 | 36.3 | Living Room | 22.5 | 2022-01-01T19:00:00Z |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "`WHERE` clause with non-scalar subquery" %}}
Non-scalar subqueries must use the `[NOT] IN` or `[NOT] EXISTS` operators and
can only return a single column.
The values in the returned column are evaluated as a list.
The following query returns all points in the `home` measurement associated with
the same timestamps as `warn` level alerts in the `home_actions` measurement.
```sql
SELECT
*
FROM
home
WHERE
time IN (
SELECT
DISTINCT time
FROM
home_actions
WHERE
level = 'warn'
)
```
#### Inner query result
{{% influxdb/custom-timestamps %}}
| time |
| :------------------- |
| 2022-01-01T18:00:00Z |
| 2022-01-01T19:00:00Z |
| 2022-01-01T20:00:00Z |
{{% /influxdb/custom-timestamps %}}
#### Outer query result
{{% influxdb/custom-timestamps %}}
| co | hum | room | temp | time |
| --: | ---: | :---------- | ---: | :------------------- |
| 18 | 36.9 | Kitchen | 23.3 | 2022-01-01T18:00:00Z |
| 9 | 36.2 | Living Room | 22.8 | 2022-01-01T18:00:00Z |
| 26 | 36.5 | Kitchen | 22.7 | 2022-01-01T20:00:00Z |
| 17 | 36.4 | Living Room | 22.2 | 2022-01-01T20:00:00Z |
| 22 | 36.6 | Kitchen | 23.1 | 2022-01-01T19:00:00Z |
| 14 | 36.3 | Living Room | 22.5 | 2022-01-01T19:00:00Z |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "`WHERE` clause with correlated subquery" %}}
The following query returns rows with temperature values greater than the median
temperature value for each room. The subquery in the `WHERE` clause uses the
`room` value from the outer query to return the median `temp` value for that
specific room.
```sql
SELECT
time,
room,
temp
FROM
home outer_query
WHERE
temp > (
SELECT
median(temp) AS temp
FROM
home
WHERE
room = outer_query.room
GROUP BY
room
)
ORDER BY room, time
```
#### Inner query result
The result of the inner query depends on the value of `room` in the outer query,
but the following table contains the median `temp` value for each room.
| room | temp |
| :---------- | ---: |
| Living Room | 22.3 |
| Kitchen | 22.7 |
#### Outer query result
{{% influxdb/custom-timestamps %}}
| time | room | temp |
| :------------------- | :---------- | ---: |
| 2022-01-01T09:00:00Z | Kitchen | 23 |
| 2022-01-01T13:00:00Z | Kitchen | 22.8 |
| 2022-01-01T14:00:00Z | Kitchen | 22.8 |
| 2022-01-01T18:00:00Z | Kitchen | 23.3 |
| 2022-01-01T19:00:00Z | Kitchen | 23.1 |
| 2022-01-01T13:00:00Z | Living Room | 22.4 |
| 2022-01-01T16:00:00Z | Living Room | 22.4 |
| 2022-01-01T17:00:00Z | Living Room | 22.6 |
| 2022-01-01T18:00:00Z | Living Room | 22.8 |
| 2022-01-01T19:00:00Z | Living Room | 22.5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## HAVING clause subqueries
[`HAVING` clause](/influxdb/cloud-dedicated/reference/sql/having/) subqueries
compare an expression that uses aggregate values returned by aggregate functions
in the `SELECT` clause to the result of the subquery and return _true_ or _false_.
Rows that evaluate to _false_ or NULL are filtered from results.
The `HAVING` clause supports correlated and non-correlated subqueries
as well as scalar and non-scalar subqueries (depending on the the operator used
in the predicate expression).
### Syntax {#having-subquery-syntax}
```sql
SELECT
aggregate_expression1[, aggregate_expression2, ..., aggregate_expressionN]
FROM
<measurement>
WHERE
<conditional_expression>
GROUP BY
column_expression1[, column_expression2, ..., column_expressionN]
HAVING
expression operator (<subquery>)
```
### Examples {#having-subquery-examples}
{{< expand-wrapper >}}
{{% expand "`HAVING` clause with scalar subquery" %}}
The following query returns all two hour blocks of time with average `temp` values
greater then the median `temp` value.
```sql
SELECT
DATE_BIN(INTERVAL '2 hours', time) AS "2-hour block",
AVG(temp) AS avg_temp
FROM
home
GROUP BY
1
HAVING
avg_temp > (
SELECT
MEDIAN(temp)
FROM
home
)
```
#### Inner query result
| MEDIAN(home.temp) |
| :---------------- |
| 22.45 |
#### Outer query result
{{% influxdb/custom-timestamps %}}
| 2-hour block | avg_temp |
| :------------------- | -------: |
| 2022-01-01T12:00:00Z | 22.475 |
| 2022-01-01T16:00:00Z | 22.525 |
| 2022-01-01T18:00:00Z | 22.925 |
| 2022-01-01T14:00:00Z | 22.525 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "`HAVING` clause with non-scalar subquery" %}}
Non-scalar subqueries must use the `[NOT] IN` or `[NOT] EXISTS` operators and
can only return a single column.
The values in the returned column are evaluated as a list.
The following query returns the maximum `co` and `temp` values within 2-hour
windows of time where the `time` value associated with time window is also
associated with a warning in the `home_actions` measurement.
```sql
SELECT
date_bin(INTERVAL '2 hours', time) AS "2-hour block",
max(co) AS max_co,
max(temp) as max_temp
FROM
home
GROUP BY
1,
room
HAVING
"2-hour block" IN (
SELECT
DISTINCT time
FROM
home_actions
WHERE
level = 'warn'
)
```
#### Inner query result
{{% influxdb/custom-timestamps %}}
| time |
| :------------------- |
| 2022-01-01T18:00:00Z |
| 2022-01-01T19:00:00Z |
| 2022-01-01T20:00:00Z |
{{% /influxdb/custom-timestamps %}}
#### Outer query result
{{% influxdb/custom-timestamps %}}
| 2-hour block | max_co | max_temp |
| :------------------- | -----: | -------: |
| 2022-01-01T18:00:00Z | 14 | 22.8 |
| 2022-01-01T18:00:00Z | 22 | 23.3 |
| 2022-01-01T20:00:00Z | 17 | 22.2 |
| 2022-01-01T20:00:00Z | 26 | 22.7 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "`HAVING` clause with correlated subquery" %}}
The following query returns 2-hour windows of time with average `temp` values
greater than the median `temp` value for each room. The subquery in the `HAVING`
clause uses the `room` value from the outer query to return the median `temp` value
for that specific room.
```sql
SELECT
time,
room,
temp
FROM
home outer_query
WHERE
temp > (
SELECT
median(temp) AS temp
FROM
home
WHERE
room = outer_query.room
GROUP BY
room
)
ORDER BY room, time
```
#### Inner query result
The result of the inner query depends on the value of `room` in the outer query,
but the following table contains the median `temp` value for each room.
| room | temp |
| :---------- | ---: |
| Living Room | 22.3 |
| Kitchen | 22.7 |
#### Outer query result
{{% influxdb/custom-timestamps %}}
| 2-hour block | room | avg_temp |
| :------------------- | :---------- | -----------------: |
| 2022-01-01T14:00:00Z | Kitchen | 22.75 |
| 2022-01-01T18:00:00Z | Kitchen | 23.200000000000003 |
| 2022-01-01T16:00:00Z | Living Room | 22.5 |
| 2022-01-01T18:00:00Z | Living Room | 22.65 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## Subquery categories
SQL subqueries can be categorized as one or more of the following based on the
behavior of the subquery:
- [correlated](#correlated-subqueries) or [non-correlated](#non-correlated-subqueries) <!-- GET MORE INFO -->
- [scalar](#scalar-subqueries) or [non-scalar](#non-scalar-subqueries)
### Correlated subqueries
In a **correlated** subquery, the inner query depends on the values of the
current row being processed.
In the query below, the inner query (`SELECT temp_avg FROM weather WHERE location = home.room`)
depends on data (`home.room`) from the outer query
(`SELECT time, room, temp FROM home`) and is therefore a _correlated_ subquery.
```sql
SELECT
time,
room,
temp
FROM
home
WHERE
temp = (
SELECT
temp_avg
FROM
weather
WHERE
location = home.room
)
```
{{% note %}}
#### Correlated subquery performance
Because correlated subqueries depend on the outer query and typically must
execute for each row returned by the outer query, correlated subqueries are
**less performant** than non-correlated subqueries.
{{% /note %}}
### Non-correlated subqueries
In a **non-correlated** subquery, the inner query _doesn't_ depend on the outer
query and executes independently.
The inner query executes first, and then passes the results to the outer query.
In the query below, the inner query (`SELECT MIN(temp_avg) FROM weather`) can
run independently from the outer query (`SELECT time, temp FROM home`) and is
therefore a _non-correlated_ subquery.
```sql
SELECT
time,
temp
FROM
home
WHERE
temp < (
SELECT
MIN(temp_avg)
FROM
weather
)
```
### Scalar subqueries
A **scalar** subquery returns a single value (one column of one row).
If no rows are returned, the subquery returns NULL.
The example subquery below returns the average value of a specified column.
This value is a single scalar value.
```sql
SELECT * FROM home WHERE co > (SELECT avg(co) FROM home)
```
### Non-scalar subqueries
A **non-scalar** subquery returns 0, 1, or multiple rows, each of which may
contain 1 or multiple columns. For each column, if there is no value to return,
the subquery returns NULL. If no rows qualify to be returned, the subquery
returns 0 rows.
The example subquery below returns all distinct values in a column.
Multiple values are returned.
```sql
SELECT * FROM home WHERE room IN (SELECT DISTINCT room FROM home_actions)
```
<!--
The content of this page is at /content/shared/sql-reference/subqueries.md
-->

View File

@ -7,115 +7,10 @@ menu:
influxdb_cloud_dedicated:
parent: SQL reference
weight: 220
source: /content/shared/sql-reference/table-value-constructor.md
---
The table value constructor (TVC) uses the `VALUES` keyword to specify a set of
row value expressions to construct into a table.
The TVC can be used in the `FROM` clause <!-- or `JOIN` clauses -->
to build an ad hoc table at query time.
```sql
VALUES (row_value_list)[,...n]
```
##### Arguments
- **row_value_list**:
Comma-delimited list of column values.
Enclose each list in parentheses and separate multiple lists with commas.
Each list must have the same number of values and values must be in the same
order as columns in the table.
Each list must contain a value for each column.
## Usage
```sql
SELECT
expression[,...n]
FROM
(VALUES (row_value_list)[,...n]) [AS] table_name(column_name[,...n])
```
{{% note %}}
When using the TVC, the `AS` keyword is optional and implied when naming the
table and providing column names.
{{% /note %}}
## Examples
- [Select data from an ad hoc table](#select-data-from-an-ad-hoc-table)
<!-- - [Join data with an ad hoc table](#join-data-with-an-ad-hoc-table) -->
### Select data from an ad hoc table
```sql
SELECT *
FROM
(VALUES ('2023-01-01 12:00:00'::TIMESTAMP, 1.23, 4.56),
('2023-01-01 13:00:00'::TIMESTAMP, 2.46, 8.1),
('2023-01-01 13:00:00'::TIMESTAMP, 4.81, 16.2)
) AS data(time, f1, f2)
```
| time | f1 | f2 |
| :------------------- | ---: | ---: |
| 2023-01-01T12:00:00Z | 1.23 | 4.56 |
| 2023-01-01T13:00:00Z | 2.46 | 8.1 |
| 2023-01-01T13:00:00Z | 4.81 | 16.2 |
<!-- ### Join data with an ad hoc table
_The following example uses the sample data set provided in
[Get started with InfluxDB tutorial](/influxdb/cloud-dedicated/get-started/write/#construct-line-protocol)._
```sql
SELECT
home.time AS time,
home.room AS room,
roomData.id AS room_id
FROM
home
INNER JOIN
(VALUES ('Kitchen', 'abc123'),
('Living Room', 'def456'),
('Bedroom', 'ghi789')
) AS roomData(room,id)
ON home.room = roomData.room;
```
{{< expand-wrapper >}}
{{% expand "View example results" %}}
{{% influxdb/custom-timestamps %}}
| time | room | room_id |
| :------------------- | :---------- | :------ |
| 2022-01-01T08:00:00Z | Kitchen | abc123 |
| 2022-01-01T09:00:00Z | Kitchen | abc123 |
| 2022-01-01T10:00:00Z | Kitchen | abc123 |
| 2022-01-01T11:00:00Z | Kitchen | abc123 |
| 2022-01-01T12:00:00Z | Kitchen | abc123 |
| 2022-01-01T13:00:00Z | Kitchen | abc123 |
| 2022-01-01T14:00:00Z | Kitchen | abc123 |
| 2022-01-01T15:00:00Z | Kitchen | abc123 |
| 2022-01-01T16:00:00Z | Kitchen | abc123 |
| 2022-01-01T17:00:00Z | Kitchen | abc123 |
| 2022-01-01T18:00:00Z | Kitchen | abc123 |
| 2022-01-01T19:00:00Z | Kitchen | abc123 |
| 2022-01-01T20:00:00Z | Kitchen | abc123 |
| 2022-01-01T08:00:00Z | Living Room | def456 |
| 2022-01-01T09:00:00Z | Living Room | def456 |
| 2022-01-01T10:00:00Z | Living Room | def456 |
| 2022-01-01T11:00:00Z | Living Room | def456 |
| 2022-01-01T12:00:00Z | Living Room | def456 |
| 2022-01-01T13:00:00Z | Living Room | def456 |
| 2022-01-01T14:00:00Z | Living Room | def456 |
| 2022-01-01T15:00:00Z | Living Room | def456 |
| 2022-01-01T16:00:00Z | Living Room | def456 |
| 2022-01-01T17:00:00Z | Living Room | def456 |
| 2022-01-01T18:00:00Z | Living Room | def456 |
| 2022-01-01T19:00:00Z | Living Room | def456 |
| 2022-01-01T20:00:00Z | Living Room | def456 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}} -->
<!--
The content of this page is at /content/shared/sql-reference/table-value-constructor.md
-->

View File

@ -8,161 +8,10 @@ menu:
name: UNION clause
parent: SQL reference
weight: 206
source: /content/shared/sql-reference/union.md
---
The `UNION` clause combines the results of two or more `SELECT` statements into
a single result set.
By default, `UNION` only keeps unique rows.
To keep all rows, including duplicates, use `UNION ALL`.
- [Syntax](#syntax)
- [Examples](#examples)
**When using the `UNION` clause**:
- The number of columns in each result set must be the same.
- Columns must be in the same order and of the same or compatible data types.
## Syntax
```sql
SELECT expression[,...n]
FROM measurement_1
UNION [ALL]
SELECT expression[,...n]
FROM measurement_2
```
## Examples
- [Union results from different measurements](#union-results-from-different-measurements)
- [Return the highest and lowest three results in a single result set](#return-the-highest-and-lowest-three-results-in-a-single-result-set)
- [Union query results with custom data](#union-query-results-with-custom-data)
### Union results from different measurements
```sql
(
SELECT
'h2o_pH' AS measurement,
time,
"pH" AS "water_pH"
FROM "h2o_pH"
LIMIT 4
)
UNION
(
SELECT
'h2o_quality' AS measurement,
time,
index
FROM h2o_quality
LIMIT 4
)
```
{{< expand-wrapper >}}
{{% expand "View example results" %}}
| measurement | time | water_pH |
| :---------- | :------------------- | -------: |
| h2o_pH | 2019-08-27T00:12:00Z | 7 |
| h2o_pH | 2019-08-27T00:18:00Z | 8 |
| h2o_quality | 2019-09-11T01:06:00Z | 89 |
| h2o_pH | 2019-08-27T00:06:00Z | 7 |
| h2o_quality | 2019-09-11T00:00:00Z | 26 |
| h2o_quality | 2019-09-11T01:00:00Z | 19 |
| h2o_quality | 2019-09-11T00:48:00Z | 65 |
| h2o_pH | 2019-08-27T00:00:00Z | 8 |
{{% /expand %}}
{{< /expand-wrapper >}}
### Return the highest and lowest three results in a single result set
_The following example uses the sample data set provided in
[Get started with InfluxDB tutorial](/influxdb/cloud-dedicated/get-started/write/#construct-line-protocol)._
```sql
(
SELECT
'low' as type,
time,
co
FROM home
ORDER BY co ASC
LIMIT 3
)
UNION
(
SELECT
'high' as type,
time,
co
FROM home
ORDER BY co DESC
LIMIT 3
)
```
{{< expand-wrapper >}}
{{% expand "View example results" %}}
| type | time | co |
| :--- | :------------------- | --: |
| high | 2022-01-01T20:00:00Z | 26 |
| high | 2022-01-01T19:00:00Z | 22 |
| high | 2022-01-01T18:00:00Z | 18 |
| low | 2022-01-01T14:00:00Z | 0 |
| low | 2022-01-01T10:00:00Z | 0 |
| low | 2022-01-01T08:00:00Z | 0 |
{{% /expand %}}
{{< /expand-wrapper >}}
### Union query results with custom data
_The following example uses the sample data set provided in
[Get started with InfluxDB tutorial](/influxdb/cloud-dedicated/get-started/write/#construct-line-protocol).
It also uses the [table value constructor](/influxdb/cloud-dedicated/reference/sql/table-value-constructor/)
to build a table with custom data._
```sql
SELECT *
FROM home
WHERE
time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T12:00:00Z'
UNION
SELECT * FROM
(VALUES (0, 34.2, 'Bedroom', 21.1, '2022-01-01T08:00:00Z'::TIMESTAMP),
(0, 34.5, 'Bedroom', 21.2, '2022-01-01T09:00:00Z'::TIMESTAMP),
(0, 34.6, 'Bedroom', 21.5, '2022-01-01T10:00:00Z'::TIMESTAMP),
(0, 34.5, 'Bedroom', 21.8, '2022-01-01T11:00:00Z'::TIMESTAMP),
(0, 33.9, 'Bedroom', 22.0, '2022-01-01T12:00:00Z'::TIMESTAMP)
) newRoom(co, hum, room, temp, time)
ORDER BY room, time
```
{{< expand-wrapper >}}
{{% expand "View example results" %}}
| co | hum | room | temp | time |
| --: | ---: | :---------- | ---: | :------------------- |
| 0 | 34.2 | Bedroom | 21.1 | 2022-01-01T08:00:00Z |
| 0 | 34.5 | Bedroom | 21.2 | 2022-01-01T09:00:00Z |
| 0 | 34.6 | Bedroom | 21.5 | 2022-01-01T10:00:00Z |
| 0 | 34.5 | Bedroom | 21.8 | 2022-01-01T11:00:00Z |
| 0 | 33.9 | Bedroom | 22 | 2022-01-01T12:00:00Z |
| 0 | 35.9 | Kitchen | 21 | 2022-01-01T08:00:00Z |
| 0 | 36.2 | Kitchen | 23 | 2022-01-01T09:00:00Z |
| 0 | 36.1 | Kitchen | 22.7 | 2022-01-01T10:00:00Z |
| 0 | 36 | Kitchen | 22.4 | 2022-01-01T11:00:00Z |
| 0 | 36 | Kitchen | 22.5 | 2022-01-01T12:00:00Z |
| 0 | 35.9 | Living Room | 21.1 | 2022-01-01T08:00:00Z |
| 0 | 35.9 | Living Room | 21.4 | 2022-01-01T09:00:00Z |
| 0 | 36 | Living Room | 21.8 | 2022-01-01T10:00:00Z |
| 0 | 36 | Living Room | 22.2 | 2022-01-01T11:00:00Z |
| 0 | 35.9 | Living Room | 22.2 | 2022-01-01T12:00:00Z |
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
The content of this page is at /content/shared/sql-reference/union.md
-->

View File

@ -10,125 +10,10 @@ menu:
weight: 202
related:
- /influxdb/cloud-dedicated/reference/sql/subqueries/
source: /content/shared/sql-reference/where.md
---
Use the `WHERE` clause to filter results based on fields, tags, or timestamps.
- [Syntax](#syntax)
- [Examples](#examples)
## Syntax
```sql
SELECT_clause FROM_clause WHERE <conditional_expression> [(AND|OR) <conditional_expression> [...]]
```
{{% note %}}
**Note:** Unlike InfluxQL, SQL **supports** `OR` in the `WHERE` clause to specify multiple conditions, including time ranges.
{{% /note %}}
## Examples
Note that single quotes are required for string literals in the `WHERE` clause.
### Filter data based on field values
```sql
SELECT *
FROM "h2o_feet"
WHERE "water_level" >= 9.78
```
{{< expand-wrapper >}}
{{% expand "View example results" %}}
The query returns data from the `h2o_feet` measurement with `water_level` field values
that are greater than or equal to 9.78.
| level description | location | time | water_level |
| :------------------------ | :----------- | :----------------------- | :---------- |
| at or greater than 9 feet | coyote_creek | 2019-09-01T23:06:00.000Z | 9.8 |
| at or greater than 9 feet | coyote_creek | 2019-09-01T23:12:00.000Z | 9.829 |
| at or greater than 9 feet | coyote_creek | 2019-09-01T23:18:00.000Z | 9.862 |
| at or greater than 9 feet | coyote_creek | 2019-09-01T23:24:00.000Z | 9.892 |
| at or greater than 9 feet | coyote_creek | 2019-09-01T23:30:00.000Z | 9.902 |
| at or greater than 9 feet | coyote_creek | 2019-09-01T23:36:00.000Z | 9.898 |
{{% /expand %}}
{{< /expand-wrapper >}}
### Filter data based on specific tag and field values
```sql
SELECT *
FROM "h2o_feet"
WHERE "location" = 'santa_monica' and "level description" = 'below 3 feet'
```
{{< expand-wrapper >}}
{{% expand "View example results" %}}
The query returns all data from the `h2o_feet` measurement with the `location` tag key, `santa_monica`,
and a `level description` field value that equals `below 3 feet`.
| level description | location | time | water_level |
| :---------------- | :----------- | :----------------------- | :---------- |
| below 3 feet | santa_monica | 2019-09-01T00:00:00.000Z | 1.529 |
| below 3 feet | santa_monica | 2019-09-01T00:06:00.000Z | 1.444 |
| below 3 feet | santa_monica | 2019-09-01T00:12:00.000Z | 1.335 |
| below 3 feet | santa_monica | 2019-09-01T00:18:00.000Z | 1.345 |
| below 3 feet | santa_monica | 2019-09-01T00:24:00.000Z | 1.27 |
{{% /expand %}}
{{< /expand-wrapper >}}
### Filter data within a specific time period
```sql
SELECT *
FROM h2o_feet
WHERE "location" = 'santa_monica'
AND "time" >= '2019-08-19T12:00:00Z' AND "time" <= '2019-08-19T13:00:00Z'
```
{{< expand-wrapper >}}
{{% expand "View example results" %}}
The query returns results with timestamps greater than or equal to `08-19-2019T12:00:00Z` and
less than or equal to `08-19-2019T13:00:00Z`.
| level description | location | time | water_level |
| :---------------- | :----------- | :----------------------- | :---------- |
| below 3 feet | santa_monica | 2019-08-19T12:00:00.000Z | 2.533 |
| below 3 feet | santa_monica | 2019-08-19T12:06:00.000Z | 2.543 |
| below 3 feet | santa_monica | 2019-08-19T12:12:00.000Z | 2.385 |
| below 3 feet | santa_monica | 2019-08-19T12:18:00.000Z | 2.362 |
| below 3 feet | santa_monica | 2019-08-19T12:24:00.000Z | 2.405 |
| below 3 feet | santa_monica | 2019-08-19T12:30:00.000Z | 2.398 |
{{% /expand %}}
{{< /expand-wrapper >}}
### Filter data using the OR operator
```sql
SELECT *
FROM "h2o_feet"
WHERE "level description" = 'less than 3 feet' OR "water_level" < 2.5
```
{{< expand-wrapper >}}
{{% expand "View example results" %}}
The query returns results with a `level description` field value equal to `less than 3 feet` or a `water_level` field value less than 2.5.
| level description | location | time | water_level |
| :---------------- | :----------- | :----------------------- | :---------- |
| below 3 feet | coyote_creek | 2019-08-25T10:06:00.000Z | 2.398 |
| below 3 feet | coyote_creek | 2019-08-25T10:12:00.000Z | 2.234 |
| below 3 feet | coyote_creek | 2019-08-25T10:18:00.000Z | 2.064 |
| below 3 feet | coyote_creek | 2019-08-25T10:24:00.000Z | 1.893 |
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
The content of this page is at /content/shared/sql-reference/where.md
-->

View File

@ -119,7 +119,7 @@ The following steps set up a Go project using the
which provides the InfluxDB `influxdb3` Go client library module.
```sh
go get github.com/InfluxCommunity/influxdb3-go
go get github.com/InfluxCommunity/influxdb3-go/v2
```
<!-- END GO SETUP PROJECT -->
@ -228,7 +228,7 @@ points.
"os"
"fmt"
"time"
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
"github.com/influxdata/line-protocol/v2/lineprotocol"
)

View File

@ -538,7 +538,7 @@ _If your project's virtual environment is already running, skip to step 3._
"time"
"text/tabwriter"
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
func Query() error {
@ -604,7 +604,7 @@ _If your project's virtual environment is already running, skip to step 3._
- `io`
- `os`
- `text/tabwriter`
- `github.com/InfluxCommunity/influxdb3-go/influxdb3/v1`
- `github.com/InfluxCommunity/influxdb3-go/v2/influxdb3`
2. Defines a `Query()` function that does the following:

View File

@ -804,7 +804,7 @@ InfluxDB v3 [influxdb3-go client library package](https://github.com/InfluxCommu
"fmt"
"log"
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
// Write line protocol data to InfluxDB

View File

@ -21,7 +21,7 @@ list_code_example: |
```go
import (
"context"
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
func Query() error {
@ -94,7 +94,7 @@ to install a recent version of the Go programming language for your system.
In your terminal, enter the following command to download and install the client library:
```sh
go get github.com/InfluxCommunity/influxdb3-go
go get github.com/InfluxCommunity/influxdb3-go/v2
```
- [`influxdb3-go`](https://github.com/InfluxCommunity/influxdb3-go) {{< req text="\* " color="magenta" >}}: Provides the `influxdb3` package and also installs the [Apache `arrow` module](https://arrow.apache.org/docs/python/index.html) for working with Arrow data returned from queries.
@ -138,7 +138,7 @@ import (
"text/tabwriter"
"time"
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
func Query() error {
@ -233,7 +233,7 @@ import (
"text/tabwriter"
"time"
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
func InfluxQL() error {

View File

@ -257,7 +257,7 @@ import (
"os"
"text/tabwriter"
"time"
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
func Query(query string, parameters influxdb3.QueryParameters,

View File

@ -254,7 +254,7 @@ import (
"os"
"text/tabwriter"
"time"
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
func Query(query string, parameters influxdb3.QueryParameters) error {

View File

@ -20,7 +20,7 @@ to write and query data stored in an {{% product-name %}} bucket.
## Installation
```sh
go get github.com/InfluxCommunity/influxdb3-go
go get github.com/InfluxCommunity/influxdb3-go/v2
```
## Importing the package
@ -31,7 +31,7 @@ Import the package:
```go
import (
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
```
@ -75,7 +75,7 @@ Initializes and returns a `influxdb3.Client` instance with the following:
package main
import (
"github.com/InfluxCommunity/influxdb3-go/influxdb3/v1"
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
func Query() error {

View File

@ -379,7 +379,7 @@ Related entries:
A function is an operation that performs a specific task.
Functions take input, operate on that input, and then return output.
For a complete list of available SQL functions, see
[SQL functions](/inflxudb/cloud-serverless/reference/sql/functions/).
[SQL functions](/influxdb/cloud-serverless/reference/sql/functions/).
<!-- TODO: Add a link to InfluxQL aggregate functions -->

View File

@ -1,786 +1,13 @@
---
title: InfluxQL reference documentation
list_title: InfluxQL
description: InfluxQL is an SQL-like query language for interacting with data in InfluxDB.
description: >
InfluxQL is an SQL-like query language for interacting with data in InfluxDB.
menu:
influxdb_cloud_serverless:
parent: Reference
name: InfluxQL reference
identifier: influxql-reference
weight: 102
source: /shared/influxql-v3-reference/_index.md
---
InfluxQL (Influx Query Language) is an SQL-like query language used to interact
with InfluxDB and work with times series data.
{{% warn %}}
#### InfluxQL feature support
InfluxQL is being rearchitected to work with the InfluxDB 3.0 storage engine.
This process is ongoing and some InfluxQL features are still being implemented.
For information about the current implementation status of InfluxQL features,
see [InfluxQL feature support](/influxdb/cloud-serverless/reference/influxql/feature-support/).
{{% /warn %}}
- [Notation](#notation)
- [Query representation](#query-representation)
- [Characters](#characters)
- [Letters and digits](#letters-and-digits)
- [Identifiers](#identifiers)
- [Keywords](#keywords)
- [Literals](#literals)
- [Queries](#queries)
- [Statements](#statements)
- [Clauses](#clauses)
- [Expressions](#expressions)
- [Comments](#comments)
- [Other](#other)
- [Result set](#result-set)
<!-- To learn more about InfluxQL, browse the following topics:
- [Explore your data with InfluxQL](/influxdb/v2/query-data/influxql/explore-data/)
- [Explore your schema with InfluxQL](/influxdb/v2/query-data/influxql/explore-schema/)
- [Database management](/influxdb/v2/query-data/influxql/manage-database/)
- [Query engine internals](/influxdb/cloud-serverless/reference/influxql/internals/) -->
## Notation
The syntax is specified using Extended Backus-Naur Form ("EBNF").
EBNF is the same notation used in the [Go programming language specification](https://golang.org/ref/spec).
```go
Production = production_name "=" [ Expression ] "." .
Expression = Alternative { "|" Alternative } .
Alternative = Term { Term } .
Term = production_name | token [ "…" token ] | Group | Option | Repetition .
Group = "(" Expression ")" .
Option = "[" Expression "]" .
Repetition = "{" Expression "}" .
```
Notation operators in order of increasing precedence:
```
| alternation
() grouping
[] option (0 or 1 times)
{} repetition (0 to n times)
```
## Query representation
### Characters
InfluxQL is Unicode text encoded in [UTF-8](http://en.wikipedia.org/wiki/UTF-8).
```
newline = /* the Unicode code point U+000A */ .
unicode_char = /* an arbitrary Unicode code point except newline */ .
```
### Letters and digits
Letters are the set of ASCII letters and the underscore (`_`, U+005F).
Only decimal digits are supported.
```
letter = ascii_letter | "_" .
ascii_letter = "A" … "Z" | "a" … "z" .
digit = "0" … "9" .
```
### Identifiers
Identifiers are tokens that refer to
[database](/influxdb/cloud-serverless/reference/glossary/#database) names,
[retention policy](/influxdb/cloud-serverless/reference/glossary/#retention-policy-rp) names,
[measurement](/influxdb/cloud-serverless/reference/glossary/#measurement) names,
[tag keys](/influxdb/cloud-serverless/reference/glossary/#tag-key), and
[field keys](/influxdb/cloud-serverless/reference/glossary/#field-key).
The rules are as follows:
- Double-quoted identifiers can contain any Unicode character except for a new line.
- Double-quoted identifiers can also contain escaped `"` characters (that is, `\"`)
- Double-quoted identifiers can include InfluxQL [keywords](#keywords).
- Unquoted identifiers must start with an upper or lowercase ASCII character or "_".
- Unquoted identifiers may contain only ASCII letters, decimal digits, and "_".
```
identifier = unquoted_identifier | quoted_identifier .
unquoted_identifier = ( letter ) { letter | digit } .
quoted_identifier = `"` unicode_char { unicode_char } `"` .
```
#### Examples
```
cpu
_cpu_stats
"1h"
"anything really"
"1_Crazy-1337.identifier>NAME👍"
```
### Keywords
```
ALL ALTER ANY AS ASC BEGIN
BY CREATE CONTINUOUS DATABASE DATABASES DEFAULT
DELETE DESC DESTINATIONS DIAGNOSTICS DISTINCT DROP
DURATION END EVERY EXPLAIN FIELD FOR
FROM GRANT GRANTS GROUP GROUPS IN
INF INSERT INTO KEY KEYS KILL
LIMIT SHOW MEASUREMENT MEASUREMENTS NAME OFFSET
ON ORDER PASSWORD POLICY POLICIES PRIVILEGES
QUERIES QUERY READ REPLICATION RESAMPLE RETENTION
REVOKE SELECT SERIES SET SHARD SHARDS
SLIMIT SOFFSET STATS SUBSCRIPTION SUBSCRIPTIONS TAG
TO USER USERS VALUES WHERE WITH
WRITE
```
If you use an InfluxQL keyword as an
[identifier](/influxdb/cloud-serverless/reference/glossary/#identifier),
double-quote the identifier in every query.
The `time` keyword is a special case.
`time` can be a
database name,
[measurement](/influxdb/cloud-serverless/reference/glossary/#measurement) name,
[retention policy](/influxdb/cloud-serverless/reference/glossary/#retention-policy-rp) name, and
[user](/influxdb/cloud-serverless/reference/glossary/#user) name.
In those cases, you don't need to double-quote `time` in queries.
`time` can't be a [field key](/influxdb/cloud-serverless/reference/glossary/#field-key) or
[tag key](/influxdb/cloud-serverless/reference/glossary/#tag-key);
InfluxDB rejects writes with `time` as a field key or tag key and returns an error.
<!--
See [Frequently Asked Questions](/influxdb/v2/reference/faq/) for more information.
-->
### Literals
#### Integers
InfluxQL supports decimal integer literals.
Hexadecimal and octal literals aren't currently supported.
```
int_lit = ( "1" … "9" ) { digit } .
```
#### Floats
InfluxQL supports floating-point literals.
Exponents aren't currently supported.
```
float_lit = int_lit "." int_lit .
```
#### Strings
String literals must be surrounded by single quotes.
Strings may contain `'` characters as long as they are escaped (that is, , `\'`)
```
string_lit = `'` { unicode_char } `'` .
```
#### Durations
Duration literals specify a length of time.
An integer literal followed immediately (with no spaces) by one of the duration units listed below is interpreted as a duration literal.
Durations can be specified with mixed units.
##### Duration units
| Units | Meaning |
| ------ | --------------------------------------- |
| ns | nanoseconds (1 billionth of a second) |
| u or µ | microseconds (1 millionth of a second) |
| ms | milliseconds (1 thousandth of a second) |
| s | second |
| m | minute |
| h | hour |
| d | day |
| w | week |
```
duration_lit = int_lit duration_unit .
duration_unit = "ns" | "u" | "µ" | "ms" | "s" | "m" | "h" | "d" | "w" .
```
#### Dates & Times
Unlike other notations used in InfluxQL, the date and time literal format isn't specified by EBNF.
InfluxQL date and time is specified using Go's time parsing format and
[reference date](https://pkg.go.dev/time#pkg-constants) written in the format required by InfluxQL.
The reference date time is:
InfluxQL reference date time: January 2nd, 2006 at 3:04:05 PM
```
time_lit = "2006-01-02 15:04:05.999999" | "2006-01-02" .
```
#### Booleans
```
bool_lit = TRUE | FALSE .
```
#### Regular Expressions
```
regex_lit = "/" { unicode_char } "/" .
```
**Comparators:**
`=~` matches against
`!~` doesn't match against
{{% note %}}
InfluxQL supports using regular expressions when specifying:
- [field keys](/influxdb/cloud-serverless/reference/glossary/#field-key) and [tag keys](/influxdb/cloud-serverless/reference/glossary/#tag-key) in the [`SELECT` clause](/influxdb/cloud-serverless/reference/influxql/select/)
- [measurements](/influxdb/cloud-serverless/reference/glossary/#measurement) in the [`FROM` clause](/influxdb/cloud-serverless/reference/influxql/select/#from-clause)
- [tag values](/influxdb/cloud-serverless/reference/glossary/#tag-value) and
string [field values](/influxdb/cloud-serverless/reference/glossary/#field-value)
in the [`WHERE` clause](/influxdb/cloud-serverless/reference/influxql/where/)
- [tag keys](/influxdb/cloud-serverless/reference/glossary/#tag-key) in the
[`GROUP BY` clause](/influxdb/cloud-serverless/reference/influxql/group-by/)
Currently, InfluxQL doesn't support using regular expressions to match non-string
field values in the `WHERE` clause, [databases](/influxdb/cloud-serverless/reference/glossary/#database),
and [retention polices](/influxdb/cloud-serverless/reference/glossary/#retention-policy-rp).
{{% /note %}}
## Queries
A query is composed of one or more statements separated by a semicolon (`;`).
```
query = statement { ";" statement } .
statement = explain_stmt |
explain_analyze_stmt |
select_stmt |
show_field_keys_stmt |
show_measurements_stmt |
show_retention_policies_stmt |
show_tag_keys_stmt |
show_tag_values_with_key = stmt .
```
<!-- FULL TSM INFLUXQL STATEMENT LIST
```
query = statement { ";" statement } .
statement = explain_stmt |
explain_analyze_stmt |
select_stmt |
show_databases_stmt |
show_field_key_cardinality_stmt |
show_field_keys_stmt |
show_measurement_exact_cardinality_stmt |
show_measurements_stmt |
show_series_exact_cardinality_stmt |
show_series_stmt |
show_tag_key_cardinality_stmt |
show_tag_key_exact_cardinality_stmt |
show_tag_keys_stmt |
show_tag_values_with_key = stmt |
show_tag_values_cardinality_stmt .
``` -->
## Statements
### EXPLAIN
Parses and plans the query, and then prints a summary of estimated costs.
Many SQL engines use the `EXPLAIN` statement to show join order, join algorithms, and predicate and expression pushdown.
Since InfluxQL doesn't support joins, the cost of an InfluxQL query is typically a function of the total series accessed, the number of iterator accesses to a TSM file, and the number of TSM blocks that need to be scanned.
A query plan generated by `EXPLAIN` contains the following elements:
- expression
- auxiliary fields
- number of shards
- number of series
- cached values
- number of files
- number of blocks
- size of blocks
```
explain_stmt = "EXPLAIN" select_stmt .
```
#### Example
```sql
> explain select sum(pointReq) from "_internal"."monitor"."write" group by hostname;
> QUERY PLAN
------
EXPRESSION: sum(pointReq::integer)
NUMBER OF SHARDS: 2
NUMBER OF SERIES: 2
CACHED VALUES: 110
NUMBER OF FILES: 1
NUMBER OF BLOCKS: 1
SIZE OF BLOCKS: 931
```
### EXPLAIN ANALYZE
Executes the specified `SELECT` statement and returns data about the query performance and storage during runtime, visualized as a tree. Use this statement to analyze query performance and storage, including [execution time](#execution-time) and [planning time](#planning-time), and the [iterator type](#iterator-type) and [cursor type](#cursor-type).
For example, if you execute the following statement:
```sql
> explain analyze select mean(usage_steal) from cpu where time >= '2018-02-22T00:00:00Z' and time < '2018-02-22T12:00:00Z'
```
The output is similar to the following:
```sql
EXPLAIN ANALYZE
---------------
.
└── select
├── execution_time: 2.25823ms
├── planning_time: 18.381616ms
├── total_time: 20.639846ms
└── field_iterators
├── labels
│ └── statement: SELECT mean(usage_steal::float) FROM telegraf."default".cpu
└── expression
├── labels
│ └── expr: mean(usage_steal::float)
└── create_iterator
├── labels
│ ├── measurement: cpu
│ └── shard_id: 608
├── cursors_ref: 779
├── cursors_aux: 0
├── cursors_cond: 0
├── float_blocks_decoded: 431
├── float_blocks_size_bytes: 1003552
├── integer_blocks_decoded: 0
├── integer_blocks_size_bytes: 0
├── unsigned_blocks_decoded: 0
├── unsigned_blocks_size_bytes: 0
├── string_blocks_decoded: 0
├── string_blocks_size_bytes: 0
├── boolean_blocks_decoded: 0
├── boolean_blocks_size_bytes: 0
└── planning_time: 14.805277ms```
```
{{% note %}}
`EXPLAIN ANALYZE` ignores query output, so the cost of serialization to JSON or
CSV isn't accounted for.
{{% /note %}}
##### execution_time
Shows the amount of time the query took to execute, including reading the time series data, performing operations as data flows through iterators, and draining processed data from iterators. Execution time doesn't include the time taken to serialize the output into JSON or other formats.
##### planning_time
Shows the amount of time the query took to plan.
Planning a query in InfluxDB requires a number of steps. Depending on the complexity of the query, planning can require more work and consume more CPU and memory resources than executing the query. For example, the number of series keys required to execute a query affects how quickly the query is planned and how much memory the planning requires.
First, InfluxDB determines the effective time range of the query and selects the shards to access.
Next, for each shard and each measurement, InfluxDB performs the following steps:
1. Select matching series keys from the index, filtered by tag predicates in the `WHERE` clause.
2. Group filtered series keys into tag sets based on the `GROUP BY` dimensions.
3. Enumerate each tag set and create a cursor and iterator for each series key.
4. Merge iterators and return the merged result to the query executor.
##### iterator type
`EXPLAIN ANALYZE` supports the following iterator types:
- `create_iterator` node represents work done by the local influxd instance──a complex composition of nested iterators combined and merged to produce the final query output.
- (InfluxDB Enterprise only) `remote_iterator` node represents work done on remote machines.
For more information about iterators, see [Understanding iterators](#understanding-iterators).
##### cursor type
`EXPLAIN ANALYZE` distinguishes 3 cursor types. While the cursor types have the same data structures and equal CPU and I/O costs, each cursor type is constructed for a different reason and separated in the final output. Consider the following cursor types when tuning a statement:
- cursor_ref: Reference cursor created for `SELECT` projections that include a function, such as `last()` or `mean()`.
- cursor_aux: Auxiliary cursor created for simple expression projections (not selectors or an aggregation). For example, `SELECT foo FROM m` or `SELECT foo+bar FROM m`, where `foo` and `bar` are fields.
- cursor_cond: Condition cursor created for fields referenced in a `WHERE` clause.
For more information about cursors, see [Understanding cursors](#understanding-cursors).
##### block types
`EXPLAIN ANALYZE` separates storage block types, and reports the total number of
blocks decoded and their size (in bytes) on disk. The following block types are supported:
| Type | Description |
| :--------- | :------------------------------------ |
| `float` | 64-bit IEEE-754 floating-point number |
| `integer` | 64-bit signed integer |
| `unsigned` | 64-bit unsigned integer |
| `boolean` | 1-bit, LSB encoded |
| `string` | UTF-8 string |
### SELECT
```
select_stmt = "SELECT" fields from_clause [ where_clause ]
[ group_by_clause ] [ order_by_clause ] [ limit_clause ]
[ offset_clause ] [ slimit_clause ] [ soffset_clause ] [ timezone_clause ] .
```
#### Example
Select from measurements grouped by the day with a timezone
```sql
SELECT mean("value") FROM "cpu" GROUP BY region, time(1d) fill(0) tz('America/Chicago')
```
<!-- ### SHOW CARDINALITY
Refers to the group of commands used to estimate or count exactly the cardinality of measurements, series, tag keys, tag key values, and field keys.
The SHOW CARDINALITY commands are available in two variations: _estimated_ and _exact_. Estimated values are calculated using sketches and are a safe default for all cardinality sizes. Exact values are counts directly from TSM (Time-Structured Merge Tree) data, but are expensive to run for high cardinality data. Unless required, use the estimated variety.
Filtering by `time` is only supported when Time Series Index (TSI) is enabled on a database.
See the specific SHOW CARDINALITY commands for details:
- [SHOW FIELD KEY CARDINALITY](#show-field-key-cardinality)
- [SHOW SERIES CARDINALITY](#show-series-cardinality)
- [SHOW TAG KEY CARDINALITY](#show-tag-key-cardinality)
- [SHOW TAG VALUES CARDINALITY](#show-tag-values-cardinality) -->
<!-- ### SHOW DATABASES
```
show_databases_stmt = "SHOW DATABASES" .
```
#### Example
```sql
-- show all databases
SHOW DATABASES
``` -->
<!-- ### SHOW FIELD KEY CARDINALITY
Estimates or counts exactly the cardinality of the field key set for the current
database unless a database is specified using the `ON <database>` option.
{{% note %}}
**Note:** `ON <database>`, `FROM <sources>`, `WITH KEY = <key>`,
`WHERE <condition>`, `GROUP BY <dimensions>`, and `LIMIT/OFFSET` clauses are optional.
When using these query clauses, the query falls back to an exact count.
{{% /note %}}
```sql
show_field_key_cardinality_stmt = "SHOW FIELD KEY CARDINALITY" [ on_clause ] [ from_clause ] [ where_clause ] [ group_by_clause ] [ limit_clause ] [ offset_clause ]
show_field_key_exact_cardinality_stmt = "SHOW FIELD KEY EXACT CARDINALITY" [ on_clause ] [ from_clause ] [ where_clause ] [ group_by_clause ] [ limit_clause ] [ offset_clause ]
```
#### Examples
```sql
-- show estimated cardinality of the field key set of current database
SHOW FIELD KEY CARDINALITY
-- show exact cardinality on field key set of specified database
SHOW FIELD KEY EXACT CARDINALITY ON mydb
``` -->
### SHOW FIELD KEYS
```
show_field_keys_stmt = "SHOW FIELD KEYS" [on_clause] [ from_clause ] .
```
#### Examples
```sql
-- show field keys and field value data types from all measurements
SHOW FIELD KEYS
-- show field keys and field value data types from specified measurement
SHOW FIELD KEYS FROM "cpu"
```
### SHOW MEASUREMENTS
```
show_measurements_stmt = "SHOW MEASUREMENTS" [on_clause] [ with_measurement_clause ] [ where_clause ] [ limit_clause ] [ offset_clause ] .
```
#### Examples
```sql
-- show all measurements
SHOW MEASUREMENTS
-- show measurements where region tag = 'uswest' AND host tag = 'serverA'
SHOW MEASUREMENTS WHERE "region" = 'uswest' AND "host" = 'serverA'
-- show measurements that start with 'h2o'
SHOW MEASUREMENTS WITH MEASUREMENT =~ /h2o.*/
```
<!-- ### SHOW SERIES
```
show_series_stmt = "SHOW SERIES" [on_clause] [ from_clause ] [ where_clause ] [ limit_clause ] [ offset_clause ] .
```
#### Example
```sql
SHOW SERIES FROM "telegraf"."autogen"."cpu" WHERE cpu = 'cpu8'
``` -->
<!-- ### SHOW SERIES EXACT CARDINALITY
Estimates or counts exactly the cardinality of the series for the current
database unless a database is specified using the `ON database` option.
#### Example
SHOW SERIES EXACT CARDINALITY" [ on_clause ] [ from_clause ]
[ where_clause ] [ group_by_clause ] [ limit_clause ] [ offset_clause ]
```sql
SHOW SERIES EXACT CARDINALITY ON mydb
```
{{% note %}}
**NOTE:** `ON <database>`, `FROM <sources>`, `WITH KEY = <key>`,
`WHERE <condition>`, `GROUP BY <dimensions>`, and `LIMIT/OFFSET` clauses are optional.
When using these query clauses, the query falls back to an exact count.
Filtering by `time` is not supported in the `WHERE` clause.
{{% /note %}} -->
<!-- ### SHOW TAG KEY CARDINALITY
Estimates or counts exactly the cardinality of tag key set on the current
database unless a database is specified using the `ON <database>` option.
{{% note %}}
`ON <database>`, `FROM <sources>`, `WITH KEY = <key>`, `WHERE <condition>`,
`GROUP BY <dimensions>`, and `LIMIT/OFFSET` clauses are optional.
When using these query clauses, the query falls back to an exact count.
Filtering by `time` is only supported when TSI (Time Series Index) is enabled
and `time` is not supported in the `WHERE` clause.
{{% /note %}}
```
show_tag_key_cardinality_stmt = "SHOW TAG KEY CARDINALITY" [ on_clause ] [ from_clause ] [ where_clause ] [ group_by_clause ] [ limit_clause ] [ offset_clause ]
show_tag_key_exact_cardinality_stmt = "SHOW TAG KEY EXACT CARDINALITY" [ on_clause ] [ from_clause ] [ where_clause ] [ group_by_clause ] [ limit_clause ] [ offset_clause ]
```
#### Examples
```sql
-- show estimated tag key cardinality
SHOW TAG KEY CARDINALITY
-- show exact tag key cardinality
SHOW TAG KEY EXACT CARDINALITY
``` -->
### SHOW TAG KEYS
```
show_tag_keys_stmt = "SHOW TAG KEYS" [on_clause] [ from_clause ] [ where_clause ]
[ limit_clause ] [ offset_clause ] .
```
#### Examples
```sql
-- show all tag keys
SHOW TAG KEYS
-- show all tag keys from the cpu measurement
SHOW TAG KEYS FROM "cpu"
-- show all tag keys from the cpu measurement where the region key = 'uswest'
SHOW TAG KEYS FROM "cpu" WHERE "region" = 'uswest'
-- show all tag keys where the host key = 'serverA'
SHOW TAG KEYS WHERE "host" = 'serverA'
```
### SHOW TAG VALUES
```
show_tag_values_stmt = "SHOW TAG VALUES" [on_clause] [ from_clause ] with_tag_clause [ where_clause ]
[ limit_clause ] [ offset_clause ] .
```
#### Examples
```sql
-- show all tag values across all measurements for the region tag
SHOW TAG VALUES WITH KEY = "region"
-- show tag values from the cpu measurement for the region tag
SHOW TAG VALUES FROM "cpu" WITH KEY = "region"
-- show tag values across all measurements for all tag keys that do not include the letter c
SHOW TAG VALUES WITH KEY !~ /.*c.*/
-- show tag values from the cpu measurement for region & host tag keys where service = 'redis'
SHOW TAG VALUES FROM "cpu" WITH KEY IN ("region", "host") WHERE "service" = 'redis'
```
<!-- ### SHOW TAG VALUES CARDINALITY
Estimates or counts exactly the cardinality of tag key values for the specified
tag key on the current database unless a database is specified using the
`ON database` option.
{{% note %}}
**Note:** `ON <database>`, `FROM <sources>`, `WITH KEY = <key>`,
`WHERE <condition>`, `GROUP BY <dimensions>`, and `LIMIT/OFFSET` clauses are optional.
When using these query clauses, the query falls back to an exact count.
Filtering by `time` is only supported when TSI (Time Series Index) is enabled.
{{% /note %}}
```
show_tag_values_cardinality_stmt = "SHOW TAG VALUES CARDINALITY" [ on_clause ] [ from_clause ] [ where_clause ] [ group_by_clause ] [ limit_clause ] [ offset_clause ] with_key_clause
show_tag_values_exact_cardinality_stmt = "SHOW TAG VALUES EXACT CARDINALITY" [ on_clause ] [ from_clause ] [ where_clause ] [ group_by_clause ] [ limit_clause ] [ offset_clause ] with_key_clause
```
#### Examples
```sql
-- show estimated tag key values cardinality for a specified tag key
SHOW TAG VALUES CARDINALITY WITH KEY = "myTagKey"
-- show estimated tag key values cardinality for a specified tag key
SHOW TAG VALUES CARDINALITY WITH KEY = "myTagKey"
-- show exact tag key values cardinality for a specified tag key
SHOW TAG VALUES EXACT CARDINALITY WITH KEY = "myTagKey"
-- show exact tag key values cardinality for a specified tag key
SHOW TAG VALUES EXACT CARDINALITY WITH KEY = "myTagKey"
``` -->
## Clauses
```
from_clause = "FROM" measurements .
group_by_clause = "GROUP BY" dimensions fill(fill_option).
limit_clause = "LIMIT" int_lit .
offset_clause = "OFFSET" int_lit .
slimit_clause = "SLIMIT" int_lit .
soffset_clause = "SOFFSET" int_lit .
timezone_clause = tz(string_lit) .
on_clause = "ON" db_name .
order_by_clause = "ORDER BY" sort_fields .
where_clause = "WHERE" expr .
with_measurement_clause = "WITH MEASUREMENT" ( "=" measurement | "=~" regex_lit ) .
with_tag_clause = "WITH KEY" ( "=" tag_key | "!=" tag_key | "=~" regex_lit | "IN (" tag_keys ")" ) .
```
## Expressions
```
binary_op = "+" | "-" | "*" | "/" | "%" | "&" | "|" | "^" | "AND" |
"OR" | "=" | "!=" | "<>" | "<" | "<=" | ">" | ">=" .
expr = unary_expr { binary_op unary_expr } .
unary_expr = "(" expr ")" | var_ref | time_lit | string_lit | int_lit |
float_lit | bool_lit | duration_lit | regex_lit .
```
## Default time range
The default time range is the Unix epoch (`1970-01-01T00:00:00Z`) to _now_.
## Comments
Use comments with InfluxQL statements to describe your queries.
- A single line comment begins with two hyphens (`--`) and ends where InfluxDB detects a line break.
This comment type cannot span several lines.
- A multi-line comment begins with `/*` and ends with `*/`. This comment type can span several lines.
Multi-line comments do not support nested multi-line comments.
## Other
```
alias = "AS" identifier .
back_ref = ( policy_name ".:MEASUREMENT" ) |
( db_name "." [ policy_name ] ".:MEASUREMENT" ) .
db_name = identifier .
dimension = expr .
dimensions = dimension { "," dimension } .
field_key = identifier .
field = expr [ alias ] .
fields = field { "," field } .
fill_option = "null" | "none" | "previous" | int_lit | float_lit | "linear" .
host = string_lit .
measurement = measurement_name |
( policy_name "." measurement_name ) |
( db_name "." [ policy_name ] "." measurement_name ) .
measurements = measurement { "," measurement } .
measurement_name = identifier | regex_lit .
policy_name = identifier .
retention_policy = identifier .
retention_policy_name = "NAME" identifier .
series_id = int_lit .
sort_field = field_key [ ASC | DESC ] .
sort_fields = sort_field { "," sort_field } .
tag_key = identifier .
tag_keys = tag_key { "," tag_key } .
var_ref = measurement .
```

View File

@ -9,163 +9,6 @@ menu:
influxdb_cloud_serverless:
parent: influxql-reference
weight: 220
source: /shared/influxql-v3-reference/feature-support.md
---
InfluxQL is being rearchitected to work with the InfluxDB 3.0 storage engine.
This process is ongoing and some InfluxQL features are still being implemented.
This page provides information about the current implementation status of
InfluxQL features.
- [In-progress features](#in-progress-features)
- [SLIMIT clause](#slimit-clause)
- [SOFFSET clause](#soffset-clause)
- [Metaqueries](#metaqueries)
- [Function support](#function-support)
- [Aggregate functions](#aggregate-functions)
- [Selector functions](#selector-functions)
- [Transformations](#transformations)
- [Technical and predictive analysis](#technical-and-predictive-analysis)
## In-progress features
### SLIMIT clause
InfluxQL in {{< product-name >}} does not currently support the `SLIMIT` clause,
which limits the number of [series](/influxdb/cloud-serverless/reference/glossary/#series)
returned in query results.
<!-- **Tracking issue**: [influxdb_iox#6940](https://github.com/influxdata/influxdb_iox/issues/6940) -->
### SOFFSET clause
InfluxQL in {{< product-name >}} does not currently support the `SOFFSET` clause,
which specifies the number of [series](/influxdb/cloud-serverless/reference/glossary/#series)
to skip before returning results.
<!-- **Tracking issue**: [influxdb_iox#6940](https://github.com/influxdata/influxdb_iox/issues/6940) -->
### Metaqueries
InfluxQL metaqueries return information about the schema of time series data
stored in InfluxDB.
The following table provides information about what metaqueries are available in
{{< product-name >}}:
| Metaquery | Supported |
| :------------------------------------------------------------ | :----------------------: |
| <span style="opacity: .5;">SHOW DATABASES</span> | |
| **SHOW RETENTION POLICIES** | **{{< icon "check" >}}** |
| **SHOW MEASUREMENTS** | **{{< icon "check" >}}** |
| <span style="opacity: .5;">SHOW SERIES</span> | |
| <span style="opacity: .5;">SHOW SERIES CARDINALITY</span> | |
| **SHOW TAG KEYS** | **{{< icon "check" >}}** |
| <span style="opacity: .5;">SHOW TAG KEY CARDINALITY</span> | |
| **SHOW TAG VALUES** | **{{< icon "check" >}}** |
| <span style="opacity: .5;">SHOW TAG VALUES CARDINALITY</span> | |
| **SHOW FIELD KEYS** | **{{< icon "check" >}}** |
| <span style="opacity: .5;">SHOW FIELD KEYS CARDINALITY</span> | |
{{% note %}}
#### Cardinality metaqueries
With the InfluxDB 3.0 storage engine, series cardinality is no longer a limiting
factor for database performance.
Cardinality-related metaqueries will likely not be supported with the InfluxDB 3.0
storage engine.
{{% /note %}}
## Function support
### Aggregate functions
| Function | Supported |
| :----------------------------------------------------------------------------------------- | :----------------------: |
| [COUNT()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#count) | **{{< icon "check" >}}** |
| [DISTINCT()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#distinct) | **{{< icon "check" >}}** |
| <span style="opacity: .5;">INTEGRAL()</span> | |
| [MEAN()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#mean) | **{{< icon "check" >}}** |
| [MEDIAN()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#median) | **{{< icon "check" >}}** |
| [MODE()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#mode) | **{{< icon "check" >}}** |
| [SPREAD()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#spread) | **{{< icon "check" >}}** |
| [STDDEV()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#stddev) | **{{< icon "check" >}}** |
| [SUM()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#sum) | **{{< icon "check" >}}** |
<!--
INTEGRAL [influxdb_iox#6937](https://github.com/influxdata/influxdb_iox/issues/6937)
-->
### Selector functions
| Function | Supported |
| :-------------------------------------------------------------------------------------------- | :----------------------: |
| [BOTTOM()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#bottom) | **{{< icon "check" >}}** |
| [FIRST()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#first) | **{{< icon "check" >}}** |
| [LAST()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#last) | **{{< icon "check" >}}** |
| [MAX()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#max) | **{{< icon "check" >}}** |
| [MIN()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#min) | **{{< icon "check" >}}** |
| [PERCENTILE()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#percentile) | **{{< icon "check" >}}** |
| <span style="opacity: .5;">SAMPLE()</span> | |
| [TOP()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#top) | **{{< icon "check" >}}** |
<!-- SAMPLE() [influxdb_iox#6935](https://github.com/influxdata/influxdb_iox/issues/6935) -->
### Transformations
| Function | Supported |
| :---------------------------------------------------------------------------------------------------------------------------- | :----------------------: |
| [ABS()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#abs) | **{{< icon "check" >}}** |
| [ACOS()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#acos) | **{{< icon "check" >}}** |
| [ASIN()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#asin) | **{{< icon "check" >}}** |
| [ATAN()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#atan) | **{{< icon "check" >}}** |
| [ATAN2()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#atan2) | **{{< icon "check" >}}** |
| [CEIL()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#ceil) | **{{< icon "check" >}}** |
| [COS()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#cos) | **{{< icon "check" >}}** |
| [CUMULATIVE_SUM()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#cumulative_sum) | **{{< icon "check" >}}** |
| [DERIVATIVE()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#derivative) | **{{< icon "check" >}}** |
| [DIFFERENCE()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#difference) | **{{< icon "check" >}}** |
| [ELAPSED()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#elapsed) | **{{< icon "check" >}}** |
| [EXP()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#exp) | **{{< icon "check" >}}** |
| [FLOOR()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#floor) | **{{< icon "check" >}}** |
| [LN()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#ln) | **{{< icon "check" >}}** |
| [LOG()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#log) | **{{< icon "check" >}}** |
| [LOG2()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#log2) | **{{< icon "check" >}}** |
| [LOG10()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#log10) | **{{< icon "check" >}}** |
| [MOVING_AVERAGE()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#moving_average) | **{{< icon "check" >}}** |
| [NON_NEGATIVE_DERIVATIVE()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#non_negative_derivative) | **{{< icon "check" >}}** |
| [NON_NEGATIVE_DIFFERENCE()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#non_negative_difference) | **{{< icon "check" >}}** |
| [POW()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#pow) | **{{< icon "check" >}}** |
| [ROUND()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#round) | **{{< icon "check" >}}** |
| [SIN()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#sin) | **{{< icon "check" >}}** |
| [SQRT()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#sqrt) | **{{< icon "check" >}}** |
| [TAN()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#tan) | **{{< icon "check" >}}** |
### Technical and predictive analysis
| Function | Supported |
| :-------------------------------------------------------------------- | :-------: |
| <span style="opacity: .5;">CHANDE_MOMENTUM_OSCILLATOR()</span> | |
| <span style="opacity: .5;">DOUBLE_EXPONENTIAL_MOVING_AVERAGE()</span> | |
| <span style="opacity: .5;">EXPONENTIAL_MOVING_AVERAGE()</span> | |
| <span style="opacity: .5;">HOLT_WINTERS()</span> | |
| <span style="opacity: .5;">HOLT_WINTERS_WITH_FIT()</span> | |
| <span style="opacity: .5;">KAUFMANS_EFFICIENCY_RATIO()</span> | |
| <span style="opacity: .5;">KAUFMANS_ADAPTIVE_MOVING_AVERAGE()</span> | |
| <span style="opacity: .5;">RELATIVE_STRENGTH_INDEX()</span> | |
| <span style="opacity: .5;">TRIPLE_EXPONENTIAL_MOVING_AVERAGE()</span> | |
| <span style="opacity: .5;">TRIPLE_EXPONENTIAL_DERIVATIVE()</span> | |
<!-- All technical analysis functions [influxdb_iox#6939](https://github.com/influxdata/influxdb_iox/issues/6939) -->
### Date and time functions
| Function | Supported |
| :-------------------------------------------------------------------------------- | :----------------------: |
| [now()](/influxdb/cloud-serverless/reference/influxql/functions/date-time/#now) | **{{< icon "check" >}}** |
| [time()](/influxdb/cloud-serverless/reference/influxql/functions/date-time/#time) | **{{< icon "check" >}}** |
| [tz()](/influxdb/cloud-serverless/reference/influxql/functions/date-time/#tz) | **{{< icon "check" >}}** |
### Miscellaneous functions
| Function | Supported |
| :--------------------------------------------------------------------------- | :----------------------: |
| [fill()](/influxdb/cloud-serverless/reference/influxql/functions/misc/#fill) | **{{< icon "check" >}}** |

View File

@ -8,79 +8,6 @@ menu:
parent: influxql-reference
identifier: influxql-functions
weight: 208
source: /shared/influxql-v3-reference/functions/_index.md
---
Use InfluxQL functions to aggregate, select, transform, analyze, and predict data.
{{% note %}}
#### Missing InfluxQL functions
Some InfluxQL functions are in the process of being rearchitected to work with
the InfluxDB 3.0 storage engine. If a function you need is not here, check the
[InfluxQL feature support page](/influxdb/cloud-serverless/reference/influxql/feature-support/#function-support)
for more information.
{{% /note %}}
## InfluxQL functions (by type)
- [Aggregates](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/)
- [COUNT()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#count)
- [DISTINCT()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#distinct)
- [MEAN()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#mean)
- [MEDIAN()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#median)
- [STDDEV()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#stddev)
- [SUM()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#sum)
<!-- - [INTEGRAL()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#integral) -->
<!-- - [MODE()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#mode) -->
<!-- - [SPREAD()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#spread) -->
- [Selectors](/influxdb/cloud-serverless/reference/influxql/functions/selectors/)
- [BOTTOM()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#bottom)
- [FIRST()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#first)
- [LAST()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#last)
- [MAX()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#max)
- [MIN()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#min)
- [PERCENTILE()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#percentile)
- [TOP()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#top)
<!-- - [SAMPLE()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#sample) -->
- [Transformations](/influxdb/cloud-serverless/reference/influxql/functions/transformations/)
- [ABS()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#abs)
- [ACOS()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#acos)
- [ASIN()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#asin)
- [ATAN()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#atan)
- [ATAN2()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#atan2)
- [CEIL()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#ceil)
- [COS()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#cos)
- [CUMULATIVE_SUM()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#cumulative_sum)
- [DERIVATIVE()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#derivative)
- [DIFFERENCE()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#difference)
- [EXP()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#exp)
- [FLOOR()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#floor)
- [HISTOGRAM()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#histogram)
- [LN()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#ln)
- [LOG()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#log)
- [LOG2()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#log2)
- [LOG10()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#log10)
- [MOVING_AVERAGE()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#moving_average)
- [NON_NEGATIVE_DERIVATIVE()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#non_negative_derivative)
- [NON_NEGATIVE_DIFFERENCE()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#non_negative_difference)
- [POW()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#pow)
- [ROUND()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#round)
- [SIN()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#sin)
- [SQRT()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#sqrt)
- [TAN()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#tan)
<!-- - [ELAPSED()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#elapsed) -->
- [Date and time](/influxdb/cloud-serverless/reference/influxql/functions/date-time/)
- [now()](/influxdb/cloud-serverless/reference/influxql/functions/date-time/#now)
- [time()](/influxdb/cloud-serverless/reference/influxql/functions/date-time/#time)
- [Miscellaneous](/influxdb/cloud-serverless/reference/influxql/functions/misc/)
- [fill()](/influxdb/cloud-serverless/reference/influxql/functions/misc/#fill)
<!-- - [Technical analysis](/influxdb/cloud-serverless/reference/influxql/functions/technical-analysis/) -->
<!-- - (Predictive analysis) [HOLT_WINTERS()](/influxdb/cloud-serverless/reference/influxql/functions/technical-analysis/#holt_winters) -->
<!-- - [CHANDE_MOMENTUM_OSCILLATOR()](/influxdb/cloud-serverless/reference/influxql/functions/technical-analysis/#chande_momentum_oscillator) -->
<!-- - [DOUBLE_EXPONENTIAL_MOVING_AVERAGE()](/influxdb/cloud-serverless/reference/influxql/functions/technical-analysis/#double_exponential_moving_average) -->
<!-- - [EXPONENTIAL_MOVING_AVERAGE()](/influxdb/cloud-serverless/reference/influxql/functions/technical-analysis/#exponential_moving_average) -->
<!-- - [KAUFMANS_EFFICIENCY_RATIO()](/influxdb/cloud-serverless/reference/influxql/functions/technical-analysis/#kaufmans_adaptive_moving_average) -->
<!-- - [KAUFMANS_ADAPTIVE_MOVING_AVERAGE()](/influxdb/cloud-serverless/reference/influxql/functions/technical-analysis/#kaufmans_adaptive_moving_average) -->
<!-- - [RELATIVE_STRENGTH_INDEX()](/influxdb/cloud-serverless/reference/influxql/functions/technical-analysis/#relative_strength_index) -->
<!-- - [TRIPLE_EXPONENTIAL_MOVING_AVERAGE()](/influxdb/cloud-serverless/reference/influxql/functions/technical-analysis/#triple_exponential_moving_average) -->
<!-- - [TRIPLE_EXPONENTIAL_DERIVATIVE()](/influxdb/cloud-serverless/reference/influxql/functions/technical-analysis/#triple_exponential_derivative) -->

View File

@ -10,922 +10,6 @@ menu:
weight: 205
related:
- /influxdb/cloud-serverless/query-data/influxql/aggregate-select/
source: /shared/influxql-v3-reference/functions/aggregates.md
---
Use aggregate functions to assess, aggregate, and return values in your data.
Aggregate functions return one row containing the aggregate values from each InfluxQL group.
_Examples use the sample data set provided in the
[Get started with InfluxDB tutorial](/influxdb/cloud-serverless/get-started/write/#construct-line-protocol)._
- [COUNT()](#count)
- [DISTINCT()](#distinct)
- [MEAN()](#mean)
- [MEDIAN()](#median)
- [MODE()](#mode)
- [SPREAD()](#spread)
- [STDDEV()](#stddev)
- [SUM()](#sum)
<!-- When implemented, place back in alphabetical order -->
<!-- - [INTEGRAL()](#integral) -->
{{% note %}}
#### Missing InfluxQL functions
Some InfluxQL functions are in the process of being rearchitected to work with
the InfluxDB 3.0 storage engine. If a function you need is not here, check the
[InfluxQL feature support page](/influxdb/cloud-serverless/reference/influxql/feature-support/#function-support)
for more information.
{{% /note %}}
## COUNT()
Returns the number of non-null [field values](/influxdb/cloud-serverless/reference/glossary/#field-value).
```sql
COUNT(field_expression)
```
#### Arguments
- **field_expression**: Expression to identify one or more fields to operate on.
Can be a [field key](/influxdb/cloud-serverless/reference/glossary/#field-key),
constant, regular expression, or wildcard (`*`).
Supports all [field data types](/influxdb/cloud-serverless/reference/glossary/#field-value).
#### Examples
{{< expand-wrapper >}}
{{% expand "Count the number of non-null values in a field" %}}
```sql
SELECT COUNT(temp) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | count |
| :------------------- | ----: |
| 1970-01-01T00:00:00Z | 26 |
{{% /expand %}}
{{% expand "Count the number of non-null values in each field" %}}
```sql
SELECT COUNT(*) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | count_co | count_hum | count_temp |
| :------------------- | -------: | --------: | ---------: |
| 1970-01-01T00:00:00Z | 26 | 26 | 26 |
{{% /expand %}}
{{% expand "Count the number of non-null values in fields where the field key matches a regular expression" %}}
```sql
SELECT COUNT(/^[th]/) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | count_hum | count_temp |
| :------------------- | --------: | ---------: |
| 1970-01-01T00:00:00Z | 26 | 26 |
{{% /expand %}}
{{% expand "Count distinct values for a field" %}}
InfluxQL supports nesting [`DISTINCT()`](#distinct) in `COUNT()`.
```sql
SELECT COUNT(DISTINCT(co)) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | count |
| :------------------- | ----: |
| 1970-01-01T00:00:00Z | 12 |
{{% /expand %}}
{{% expand "Count the number of non-null field values within time windows (grouped by time)" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
COUNT(temp)
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY time(6h)
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | count |
| :------------------- | ----: |
| 2022-01-01T06:00:00Z | 4 |
| 2022-01-01T12:00:00Z | 6 |
| 2022-01-01T18:00:00Z | 3 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## DISTINCT()
Returns the list of unique [field values](/influxdb/cloud-serverless/reference/glossary/#field-value).
```sql
DISTINCT(field_key)
```
#### Arguments
- **field_key**: Field key to return distinct values from.
Supports all field types.
#### Notable behaviors
- InfluxQL supports nesting `DISTINCT()` with [`COUNT()`](#count-distinct-values-for-a-field).
#### Examples
{{< expand-wrapper >}}
{{% expand "List the distinct field values" %}}
```sql
SELECT DISTINCT(co) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | distinct |
| :------------------- | -------: |
| 1970-01-01T00:00:00Z | 0 |
| 1970-01-01T00:00:00Z | 1 |
| 1970-01-01T00:00:00Z | 3 |
| 1970-01-01T00:00:00Z | 4 |
| 1970-01-01T00:00:00Z | 7 |
| 1970-01-01T00:00:00Z | 5 |
| 1970-01-01T00:00:00Z | 9 |
| 1970-01-01T00:00:00Z | 18 |
| 1970-01-01T00:00:00Z | 14 |
| 1970-01-01T00:00:00Z | 22 |
| 1970-01-01T00:00:00Z | 17 |
| 1970-01-01T00:00:00Z | 26 |
{{% /expand %}}
{{< /expand-wrapper >}}
<!-- ## INTEGRAL()
Returns the area under the curve for queried [field values](/influxdb/cloud-serverless/reference/glossary/#field-value)
and converts those results into the summed area per **unit** of time.
{{% note %}}
`INTEGRAL()` does not support [`fill()`](/influxdb/cloud-serverless/query-data/influxql/explore-data/group-by/#group-by-time-intervals-and-fill).
`INTEGRAL()` supports int64 and float64 field value [data types](/influxdb/cloud-serverless/reference/glossary/#data-type).
{{% /note %}}
```sql
INTEGRAL(field_expression[, unit])
```
#### Arguments
- **field_expression**: Expression to identify one or more fields to operate on.
Can be a [field key](/influxdb/cloud-serverless/reference/glossary/#field-key),
constant, regular expression, or wildcard (`*`).
- **unit**: Unit of time to use when calculating the integral.
Default is `1s` (one second).
#### Examples
{{< expand-wrapper >}}
{{% expand "Calculate the integral for a field" %}}
```sql
SELECT
INTEGRAL(co)
FROM home
WHERE room = 'Kitchen'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | integral |
| :------------------- | -------: |
| 1970-01-01T00:00:00Z | 266400 |
{{% /expand %}}
{{% expand "Calculate the integral for a field and specify the unit option" %}}
```sql
SELECT
INTEGRAL(co, 1h)
FROM home
WHERE room = 'Kitchen'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | integral |
| :------------------- | -------: |
| 1970-01-01T00:00:00Z | 74 |
{{% /expand %}}
{{% expand "Calculate the integral for _each_ field and specify the unit option" %}}
Return the area under the curve (in minutes) for the field values associated
with each field key that stores numeric values in the `h2o_feet` measurement.
The `h2o_feet` measurement has on numeric field: `water_level`.
```sql
SELECT
INTEGRAL(*, 1h)
FROM home
WHERE room = 'Kitchen'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | integral_co | integral_hum | integral_temp |
| :------------------- | ----------: | -----------: | ------------: |
| 1970-01-01T00:00:00Z | 74 | 435 | 272.25 |
{{% /expand %}}
{{% expand "Calculate the integral for the field keys that matches a regular expression" %}}
```sql
SELECT
INTEGRAL(/^[th]/, 1h)
FROM home
WHERE room = 'Kitchen'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | integral_hum | integral_temp |
| :------------------- | -----------: | ------------: |
| 1970-01-01T00:00:00Z | 435 | 272.25 |
{{% /expand %}}
{{% expand "Calculate the integral for a field grouping by time" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
INTEGRAL(co, 1h)
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY time(6h)
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | integral |
| :------------------- | -------: |
| 2022-01-01T06:00:00Z | 0 |
| 2022-01-01T12:00:00Z | 30 |
| 2022-01-01T18:00:00Z | 44 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}} -->
## MEAN()
Returns the arithmetic mean (average) of [field values](/influxdb/cloud-serverless/reference/glossary/#field-value).
```sql
MEAN(field_expression)
```
#### Arguments
- **field_expression**: Expression to identify one or more fields to operate on.
Can be a [field key](/influxdb/cloud-serverless/reference/glossary/#field-key),
constant, regular expression, or wildcard (`*`).
Supports **numeric fields**.
#### Examples
{{< expand-wrapper >}}
{{% expand "Calculate the mean value of a field" %}}
```sql
SELECT MEAN(temp) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 22.396153846153844 |
{{% /expand %}}
{{% expand "Calculate the mean value of each field" %}}
```sql
SELECT MEAN(*) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | mean_co | mean_hum | mean_temp |
| :------------------- | ----------------: | -------: | -----------------: |
| 1970-01-01T00:00:00Z | 5.269230769230769 | 36.15 | 22.396153846153844 |
{{% /expand %}}
{{% expand "Calculate the mean value of fields where the field key matches a regular expression" %}}
```sql
SELECT MEAN(/^[th]/) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | mean_hum | mean_temp |
| :------------------- | -------: | -----------------: |
| 1970-01-01T00:00:00Z | 36.15 | 22.396153846153844 |
{{% /expand %}}
{{% expand "Calculate the mean value of a field within time windows (grouped by time)" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
MEAN(temp)
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY time(6h)
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 2022-01-01T06:00:00Z | 22.275 |
| 2022-01-01T12:00:00Z | 22.649999999999995 |
| 2022-01-01T18:00:00Z | 23.033333333333335 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## MEDIAN()
Returns the middle value from a sorted list of [field values](/influxdb/cloud-serverless/reference/glossary/#field-value).
```sql
MEDIAN(field_expression)
```
#### Arguments
- **field_expression**: Expression to identify one or more fields to operate on.
Can be a [field key](/influxdb/cloud-serverless/reference/glossary/#field-key),
constant, regular expression, or wildcard (`*`).
Supports **numeric fields**.
#### Notable behaviors
- `MEDIAN()` is nearly equivalent to
[`PERCENTILE(field_key, 50)`](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#percentile),
except `MEDIAN()` returns the average of the two middle field values if the
field contains an even number of values.
#### Examples
{{< expand-wrapper >}}
{{% expand "Calculate the median value of a field" %}}
```sql
SELECT MEDIAN(temp) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | median |
| :------------------- | -----: |
| 1970-01-01T00:00:00Z | 22.45 |
{{% /expand %}}
{{% expand "Calculate the median value of each field" %}}
```sql
SELECT MEDIAN(*) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | median_co | median_hum | median_temp |
| :------------------- | --------: | ---------: | ----------: |
| 1970-01-01T00:00:00Z | 1 | 36.05 | 22.45 |
{{% /expand %}}
{{% expand "Calculate the median value of fields where the field key matches a regular expression" %}}
```sql
SELECT MEDIAN(/^[th]/) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | median_hum | median_temp |
| :------------------- | ---------: | ----------: |
| 1970-01-01T00:00:00Z | 36.05 | 22.45 |
{{% /expand %}}
{{% expand "Calculate the median value of a field within time windows (grouped by time)" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
MEDIAN(temp)
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY time(6h)
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | median |
| :------------------- | -----------------: |
| 2022-01-01T06:00:00Z | 22.549999999999997 |
| 2022-01-01T12:00:00Z | 22.7 |
| 2022-01-01T18:00:00Z | 23.1 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## MODE()
Returns the most frequent value in a list of
[field values](/influxdb/cloud-serverless/reference/glossary/#field-value).
```sql
MODE(field_expression)
```
#### Arguments
- **field_expression**: Expression to identify one or more fields to operate on.
Can be a [field key](/influxdb/cloud-serverless/reference/glossary/#field-key),
constant, regular expression, or wildcard (`*`).
Supports all field types.
#### Notable behaviors
- `MODE()` returns the field value with the earliest
[timestamp](/influxdb/cloud-serverless/reference/glossary/#timestamp)
if there's a tie between two or more values for the maximum number of occurrences.
#### Examples
{{< expand-wrapper >}}
{{% expand "Calculate the mode value of a field" %}}
```sql
SELECT MODE(co) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | mode |
| :------------------- | ---: |
| 1970-01-01T00:00:00Z | 0 |
{{% /expand %}}
{{% expand "Calculate the mode value of each field" %}}
```sql
SELECT MODE(*) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | mode_co | mode_hum | mode_temp |
| :------------------- | ------: | -------: | --------: |
| 1970-01-01T00:00:00Z | 0 | 36 | 22.7 |
{{% /expand %}}
{{% expand "Calculate the mode of field keys that match a regular expression" %}}
```sql
SELECT MODE(/^[th]/) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | mode_hum | mode_temp |
| :------------------- | -------: | --------: |
| 1970-01-01T00:00:00Z | 36 | 22.7 |
{{% /expand %}}
{{% expand "Calculate the mode a field within time windows (grouped by time)" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
MODE(co)
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY time(6h)
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | mode |
| :------------------- | ---: |
| 2022-01-01T06:00:00Z | 0 |
| 2022-01-01T12:00:00Z | 1 |
| 2022-01-01T18:00:00Z | 18 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## SPREAD()
Returns the difference between the minimum and maximum
[field values](/influxdb/cloud-serverless/reference/glossary/#field-value).
```sql
SPREAD(field_expression)
```
#### Arguments
- **field_expression**: Expression to identify one or more fields to operate on.
Can be a [field key](/influxdb/cloud-serverless/reference/glossary/#field-key),
constant, regular expression, or wildcard (`*`).
Supports **numeric fields**.
#### Examples
{{< expand-wrapper >}}
{{% expand "Calculate the spread of a field" %}}
```sql
SELECT SPREAD(temp) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | spread |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 2.3000000000000007 |
{{% /expand %}}
{{% expand "Calculate the spread of each field" %}}
```sql
SELECT SPREAD(*) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | spread_co | spread_hum | spread_temp |
| :------------------- | --------: | ---------: | -----------------: |
| 1970-01-01T00:00:00Z | 26 | 1 | 2.3000000000000007 |
{{% /expand %}}
{{% expand "Calculate the spread of field keys that match a regular expression" %}}
```sql
SELECT SPREAD(/^[th]/) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | spread_hum | spread_temp |
| :------------------- | ---------: | -----------------: |
| 1970-01-01T00:00:00Z | 1 | 2.3000000000000007 |
{{% /expand %}}
{{% expand "Calculate the spread of a field within time windows (grouped by time)" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
SPREAD(co)
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY time(6h)
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | spread |
| :------------------- | -----: |
| 2022-01-01T06:00:00Z | 0 |
| 2022-01-01T12:00:00Z | 9 |
| 2022-01-01T18:00:00Z | 8 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## STDDEV()
Returns the standard deviation of [field values](/influxdb/cloud-serverless/reference/glossary/#field-value).
```sql
STDDEV(field_expression)
```
#### Arguments
- **field_expression**: Expression to identify one or more fields to operate on.
Can be a [field key](/influxdb/cloud-serverless/reference/glossary/#field-key),
constant, regular expression, or wildcard (`*`).
Supports **numeric fields**.
#### Examples
{{< expand-wrapper >}}
{{% expand "Calculate the standard deviation of a field" %}}
```sql
SELECT STDDEV(temp) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | stddev |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 0.5553238833191091 |
{{% /expand %}}
{{% expand "Calculate the standard deviation of each field" %}}
```sql
SELECT STDDEV(*) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | stddev_co | stddev_hum | stddev_temp |
| :------------------- | ----------------: | ------------------: | -----------------: |
| 1970-01-01T00:00:00Z | 7.774613519951676 | 0.25495097567963926 | 0.5553238833191091 |
{{% /expand %}}
{{% expand "Calculate the standard deviation of fields where the field key matches a regular expression" %}}
```sql
SELECT STDDEV(/^[th]/) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | stddev_hum | stddev_temp |
| :------------------- | ------------------: | -----------------: |
| 1970-01-01T00:00:00Z | 0.25495097567963926 | 0.5553238833191091 |
{{% /expand %}}
{{% expand "Calculate the standard deviation of a field within time windows (grouped by time)" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
STDDEV(co)
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY time(6h)
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | stddev |
| :------------------- | -----------------: |
| 2022-01-01T06:00:00Z | 0 |
| 2022-01-01T12:00:00Z | 3.6742346141747673 |
| 2022-01-01T18:00:00Z | 4 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## SUM()
Returns the sum of [field values](/influxdb/cloud-serverless/reference/glossary/#field-value).
```sql
SUM(field_expression)
```
#### Arguments
- **field_expression**: Expression to identify one or more fields to operate on.
Can be a [field key](/influxdb/cloud-serverless/reference/glossary/#field-key),
constant, regular expression, or wildcard (`*`).
Supports **numeric fields**.
#### Examples
{{< expand-wrapper >}}
{{% expand "Calculate the sum of values in a field" %}}
```sql
SELECT SUM(co) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | sum |
| :------------------- | --: |
| 1970-01-01T00:00:00Z | 137 |
{{% /expand %}}
{{% expand "Calculate the sum of values in each field" %}}
```sql
SELECT SUM(*) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | sum_co | sum_hum | sum_temp |
| :------------------- | -----: | ------: | -------: |
| 1970-01-01T00:00:00Z | 137 | 939.9 | 582.3 |
{{% /expand %}}
{{% expand "Calculate the sum of values for fields where the field key matches a regular expression" %}}
```sql
SELECT SUM(/^[th]/) FROM home
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | sum_hum | sum_temp |
| :------------------- | ------: | -------: |
| 1970-01-01T00:00:00Z | 939.9 | 582.3 |
{{% /expand %}}
{{% expand "Calculate the sum of values in a field within time windows (grouped by time)" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
SUM(co)
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY time(6h)
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | sum |
| :------------------- | --: |
| 2022-01-01T06:00:00Z | 0 |
| 2022-01-01T12:00:00Z | 21 |
| 2022-01-01T18:00:00Z | 66 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -8,138 +8,6 @@ menu:
name: Date and time
parent: influxql-functions
weight: 206
source: /shared/influxql-v3-reference/functions/date-time.md
---
Use InfluxQL date and time functions to perform time-related operations.
- [now()](#now)
- [time()](#time)
- [tz()](#tz)
## now()
Returns the current system time (UTC).
_Supported only in the [`WHERE` clause](/influxdb/cloud-serverless/reference/influxql/where/)._
```sql
now()
```
## time()
Used in the [`GROUP BY` clause](/influxdb/cloud-serverless/reference/influxql/group-by/)
to group data into time-based intervals, also known as "windows", using the specified interval.
Timestamps in the `time` column are updated to the start boundary of the window
they're in and grouped by `time`.
Windows use preset round-number boundaries based on the specified interval that
are independent of time conditions in the
[`WHERE` clause](/influxdb/cloud-serverless/reference/influxql/where/).
This operation can be used to do the following:
- Downsample data by aggregating multiple points in each window into a single
point per window.
- Normalize irregular time series data to occur at regular intervals.
_Supported only in the [`GROUP BY` clause](/influxdb/cloud-serverless/reference/influxql/group-by/)._
```sql
time(interval[, offset])
```
#### Arguments
- **interval**: Duration literal that specifies the window interval.
- **offset**: Duration literal that shifts preset time boundaries forward or backward.
Can be positive or negative. _Default is `0s`._
##### Examples {#time-examples}
{{< expand-wrapper >}}
{{% expand "Downsample data into time-based intervals" %}}
The following example uses the
[Bitcoin price sample dataset](/influxdb/cloud-serverless/reference/sample-data/#bitcoin-price-data).
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'GBP'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-15T00:00:00Z'
GROUP BY time(2d)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 2023-05-01T00:00:00Z | 23680.120447159094 |
| 2023-05-03T00:00:00Z | 24048.71484033149 |
| 2023-05-05T00:00:00Z | 24461.9194901099 |
| 2023-05-07T00:00:00Z | 23796.43801933702 |
| 2023-05-09T00:00:00Z | 23118.709889285707 |
| 2023-05-11T00:00:00Z | 22465.008364444446 |
| 2023-05-13T00:00:00Z | 22499.464763186803 |
{{% /expand %}}
{{< /expand-wrapper >}}
## tz()
Applies a timezone offset to timestamps in query results.
Offsets include any seasonal offset such as Daylight Savings Time (DST) or
British Summer Time (BST).
_Supported only in the [time zone clause](/influxdb/cloud-serverless/reference/influxql/time-and-timezone/#time-zone-clause)._
```sql
tz(time_zone)
```
#### Arguments
- **time_zone**: Timezone string literal to adjust times to.
Uses timezone names defined in the
[Internet Assigned Numbers Authority time zone database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List).
#### Examples {#tz-examples}
{{< expand-wrapper >}}
{{% expand "Return the UTC offset for Chicago's time zone" %}}
The following example uses the
[Get started home sensor sample dataset](/influxdb/cloud-serverless/reference/sample-data/#get-started-home-sensor-data).
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T12:00:00Z'
tz('America/Chicago')
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------------ | --: | ---: | :------ | ---: |
| 2022-01-01T02:00:00-06:00 | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T03:00:00-06:00 | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T04:00:00-06:00 | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T05:00:00-06:00 | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T06:00:00-06:00 | 0 | 36 | Kitchen | 22.5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -10,237 +10,6 @@ menu:
identifier: influxql-misc-functions
parent: influxql-functions
weight: 206
source: /shared/influxql-v3-reference/functions/misc.md
---
Use InfluxQL miscellaneous functions to perform different operations in
InfluxQL queries.
- [fill()](#fill)
## fill()
Fills _null_ field values returned from empty time windows in `GROUP BY time()`
queries with a specified fill value.
_Supported only in the [`GROUP BY` clause](/influxdb/cloud-serverless/reference/influxql/group-by/)._
```sql
fill(behavior)
```
#### Arguments
- **behavior**: Defines the behavior of the fill operation.
If no `FILL` clause is included, the default behavior is `fill(null)`.
The following options are available:
- **numeric literal**: Replaces null values with the specified numeric literal.
- **linear**: Uses linear interpolation between existing values to replace null values.
- **none**: Removes rows with null field values.
- **null**: Keeps null values and associated timestamps.
- **previous**: Replaces null values with the most recent non-null value.
#### Examples {#fill-examples}
The following example uses the
[Bitcoin price sample dataset](/influxdb/cloud-serverless/reference/sample-data/#bitcoin-price-data).
{{< tabs-wrapper >}}
{{% tabs "small" %}}
[fill(numeric_literal)](#)
[fill(linear)](#)
[fill(none)](#)
[fill(null)](#)
[fill(previous)](#)
{{% /tabs %}}
{{% tab-content %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-01T02:00:00Z'
GROUP BY
time(30m)
fill(0)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | ---------: |
| 2023-05-01T00:00:00Z | 29319.9092 |
| 2023-05-01T00:30:00Z | 29307.4416 |
| 2023-05-01T01:00:00Z | 0 |
| 2023-05-01T01:30:00Z | 29263.2886 |
{{% /tab-content %}}
{{% tab-content %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-01T02:00:00Z'
GROUP BY
time(30m)
fill(linear)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | ---------: |
| 2023-05-01T00:00:00Z | 29319.9092 |
| 2023-05-01T00:30:00Z | 29307.4416 |
| 2023-05-01T01:00:00Z | 29285.3651 |
| 2023-05-01T01:30:00Z | 29263.2886 |
{{% /tab-content %}}
{{% tab-content %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-01T02:00:00Z'
GROUP BY
time(30m)
fill(none)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | ---------: |
| 2023-05-01T00:00:00Z | 29319.9092 |
| 2023-05-01T00:30:00Z | 29307.4416 |
| 2023-05-01T01:30:00Z | 29263.2886 |
{{% /tab-content %}}
{{% tab-content %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-01T02:00:00Z'
GROUP BY
time(30m)
fill(null)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | ---------: |
| 2023-05-01T00:00:00Z | 29319.9092 |
| 2023-05-01T00:30:00Z | 29307.4416 |
| 2023-05-01T01:00:00Z | |
| 2023-05-01T01:30:00Z | 29263.2886 |
{{% /tab-content %}}
{{% tab-content %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-01T02:00:00Z'
GROUP BY
time(30m)
fill(previous)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | ---------: |
| 2023-05-01T00:00:00Z | 29319.9092 |
| 2023-05-01T00:30:00Z | 29307.4416 |
| 2023-05-01T01:00:00Z | 29307.4416 |
| 2023-05-01T01:30:00Z | 29263.2886 |
{{% /tab-content %}}
{{< /tabs-wrapper >}}
<!-- ## tz()
Applies a timezone offset to timestamps in query results.
Offsets include any seasonal offset such as Daylight Savings Time (DST) or
British Summer Time (BST).
_Supported only in the [time zone clause](/influxdb/cloud-serverless/reference/influxql/time-and-timezone/#time-zone-clause)._
```sql
tz(time_zone)
```
#### Arguments
- **time_zone**: Timezone string literal to adjust times to.
Uses timezone names defined in the
[Internet Assigned Numbers Authority time zone database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List).
#### Examples {#tz-examples}
{{< expand-wrapper >}}
{{% expand "Return the UTC offset for Chicago's time zone" %}}
The following example uses the
[Get started home sensor sample dataset](/influxdb/cloud-serverless/reference/sample-data/#get-started-home-sensor-data).
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T12:00:00Z'
tz('America/Chicago')
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------------ | --: | ---: | :------ | ---: |
| 2022-01-01T02:00:00-06:00 | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T03:00:00-06:00 | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T04:00:00-06:00 | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T05:00:00-06:00 | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T06:00:00-06:00 | 0 | 36 | Kitchen | 22.5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}} -->

View File

@ -13,632 +13,6 @@ list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] GROUP BY group_expression[, ..., group_expression_n]
```
source: /shared/influxql-v3-reference/group-by.md
---
Use the `GROUP BY` clause to group data by one or more specified
[tags](/influxdb/cloud-serverless/reference/glossary/#tag) or into specified time intervals.
`GROUP BY` requires an [aggregate](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/)
or [selector](/influxdb/cloud-serverless/reference/influxql/functions/selectors/)
function in the `SELECT` statement.
<!-- TOC -->
- [Syntax](#syntax)
- [GROUP BY clause behaviors](#group-by-clause-behaviors)
- [Group by tags](#group-by-tags)
- [GROUP BY tags examples](#group-by-tags-examples)
- [GROUP BY time](#group-by-time)
- [GROUP by time and fill gaps](#group-by-time-and-fill-gaps)
- [GROUP BY time examples](#group-by-time-examples)
- [GROUP BY time with offset](#group-by-time-with-offset)
- [GROUP BY time and fill gaps](#group-by-time-and-fill-gaps)
- [Result set](#result-set)
- [Default time range](#default-time-range)
- [Notable behaviors of the GROUP BY clause](#notable-behaviors-of-the-group-by-clause)
- [Cannot group by fields](#cannot-group-by-fields)
- [Tag order does not matter](#tag-order-does-not-matter)
- [Grouping by tag and no time range returns unexpected timestamps](#grouping-by-tag-and-no-time-range-returns-unexpected-timestamps)
- [Data grouped by time may return unexpected timestamps](#data-grouped-by-time-may-return-unexpected-timestamps)
- [Example data](#example-data)
- [Query results](#query-results)
- [Fill with no data in the queried time range](#fill-with-no-data-in-the-queried-time-range)
- [Fill with previous if no previous value exists](#fill-with-previous-if-no-previous-value-exists)
- [Fill with linear interpolation if there are not two values to interpolate between](#fill-with-linear-interpolation-if-there-are-not-two-values-to-interpolate-between)
<!-- /TOC -->
## Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] GROUP BY group_expression[, ..., group_expression_n]
```
- **group_expression**: Expression to identify tags or time intervals to group by.
Can be a [tag key](/influxdb/cloud-serverless/reference/glossary/#tag-key),
constant, [regular expression](/influxdb/cloud-serverless/reference/influxql/regular-expressions/),
wildcard (`*`), or [function expression](/influxdb/cloud-serverless/reference/influxql/functions/).
## GROUP BY clause behaviors
- `GROUP BY tag_key` - Groups data by a specific tag
- `GROUP BY tag_key1, tag_key2` - Groups data by more than one tag
- `GROUP BY *` - Groups data by all [tags](/influxdb/cloud-serverless/reference/glossary/#tag)
- `GROUP BY /regex/` - Groups data by tag keys that match the regular expression
- `GROUP BY time()` - Groups data into time intervals (windows)
{{% note %}}
If a query includes `WHERE` and `GROUP BY`, the `GROUP BY` clause must appear after
the `WHERE` clause.
{{% /note %}}
## GROUP BY tags
Groups data by one or more tag columns.
### GROUP BY tags examples
The following examples use the
[Bitcoin price sample data](/influxdb/cloud-serverless/reference/sample-data/#bitcoin-price-data).
{{< expand-wrapper >}}
{{% expand "Group data by a single tag" %}}
```sql
SELECT MEAN(*) FROM bitcoin GROUP BY code
```
{{% influxql/table-meta %}}
name: bitcoin
tags: code=EUR
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 27328.848667840004 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=GBP
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 23441.832453919982 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=USD
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 28054.160950480004 |
{{% /expand %}}
{{% expand "Group data by more than one tag" %}}
```sql
SELECT MEAN(*) FROM bitcoin GROUP BY code, description
```
{{% influxql/table-meta %}}
name: bitcoin
tags: code=EUR, description=Euro
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 27328.848667840004 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=GBP, description=British Pound Sterling
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 23441.832453919982 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=USD, description=United States Dollar
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 28054.160950480004 |
{{% /expand %}}
{{% expand "Group data by all tags" %}}
```sql
SELECT MEAN(*) FROM bitcoin GROUP BY *
```
{{% influxql/table-meta %}}
name: bitcoin
tags: code=EUR, crypto=bitcoin, description=Euro, symbol=&euro;
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 27328.848667840004 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=GBP, crypto=bitcoin, description=British Pound Sterling, symbol=&pound;
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 23441.832453919982 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=USD, crypto=bitcoin, description=United States Dollar, symbol=&#36;
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 28054.160950480004 |
{{% /expand %}}
{{% expand "Group data by tag keys that match a regular expression" %}}
```sql
SELECT MEAN(*) FROM bitcoin GROUP BY /^[cd]/
```
{{% influxql/table-meta %}}
name: bitcoin
tags: code=EUR, crypto=bitcoin, description=Euro
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 27328.848667840004 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=GBP, crypto=bitcoin, description=British Pound Sterling
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 23441.832453919982 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=USD, crypto=bitcoin, description=United States Dollar
{{% /influxql/table-meta %}}
| time | mean_price |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 28054.160950480004 |
{{% /expand %}}
{{< /expand-wrapper >}}
## GROUP BY time
`GROUP BY time()` groups data by into specified time intervals, also known as "windows",
and applies the [aggregate](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/)
and [selector](/influxdb/cloud-serverless/reference/influxql/functions/selectors/)
functions in the `SELECT` clause to each interval.
Use the [`time()` function](/influxdb/cloud-serverless/reference/influxql/functions/date-time/#time)
to specify the time interval to group by.
```sql
SELECT_clause FROM_clause WHERE <time_range> GROUP BY time(time_interval[, offset])[, group_expression (...)] [fill(behavior)]
```
`GROUP BY time()` intervals use preset round-number time boundaries that
are independent of time conditions in the [`WHERE` clause](/influxdb/cloud-serverless/reference/influxql/where/).
**Output data uses window start boundaries as the aggregate timestamps.**
Use the `offset` argument of the `time()` function to shift time boundaries forward or
backward in time.
### GROUP by time and fill gaps
When grouping by time, if a window in the queried time range does not contain data,
results return a row for the empty window containing the timestamp of the empty
window and _null_ values for each queried field.
Use the [`fill()` function](/influxdb/cloud-serverless/reference/influxql/functions/misc/#fill)
_at the end of the `GROUP BY` clause_ to replace _null_ field values.
If no `FILL` clause is included, the default behavior is `fill(null)`.
`fill()` provides the following behaviors for filling values:
- **numeric literal**: Replaces null values with the specified numeric literal.
- **linear**: Uses linear interpolation between existing values to replace null values.
- **none**: Removes rows with null field values.
- **null**: Keeps null values and associated timestamps.
- **previous**: Replaces null values with the most recent non-null value.
_See the [`fill()` documentation](/influxdb/cloud-serverless/reference/influxql/functions/misc/#fill)
for detailed examples._
### GROUP BY time examples
The following examples use the
[Bitcoin price sample data](/influxdb/cloud-serverless/reference/sample-data/#bitcoin-price-data).
{{< expand-wrapper >}}
{{% expand "Group and aggregate query results into 1 hour windows" %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-15T00:00:00Z'
GROUP BY time(1h)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 2023-05-01T00:00:00Z | 24494.27265 |
| 2023-05-01T01:00:00Z | 24452.1698 |
| 2023-05-01T02:00:00Z | 23902.666124999996 |
| 2023-05-01T03:00:00Z | 23875.211349999998 |
| 2023-05-01T04:00:00Z | 23855.6441 |
| ... | ... |
{{% /expand %}}
{{% expand "Group and aggregate query results into 1 week intervals by tag" %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-15T00:00:00Z'
GROUP BY time(1w), code
```
{{% influxql/table-meta %}}
name: bitcoin
tags: code=EUR
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 2023-04-27T00:00:00Z | 27681.21808576779 |
| 2023-05-04T00:00:00Z | 27829.413580354256 |
| 2023-05-11T00:00:00Z | 26210.24799033149 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=GBP
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 2023-04-27T00:00:00Z | 23744.083925842704 |
| 2023-05-04T00:00:00Z | 23871.201395652173 |
| 2023-05-11T00:00:00Z | 22482.33174723755 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=USD
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 2023-04-27T00:00:00Z | 28415.88231123595 |
| 2023-05-04T00:00:00Z | 28568.010941384844 |
| 2023-05-11T00:00:00Z | 26905.87242099449 |
{{% /expand %}}
{{< /expand-wrapper >}}
###### GROUP BY time with offset
{{< expand-wrapper >}}
{{% expand "Group and aggregate query results into 1 hour intervals and offset time boundaries by +15 minutes" %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-02T00:00:00Z'
GROUP BY time(1h, 15m)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 2023-04-30T23:15:00Z | |
| 2023-05-01T00:15:00Z | 29313.6754 |
| 2023-05-01T01:15:00Z | 28932.0882 |
| 2023-05-01T02:15:00Z | 28596.375225000003 |
| 2023-05-01T03:15:00Z | 28578.915075 |
| ... | ... |
_Note that `offset` forces the first time boundary to be outside
the queried time range so the query returns no results for that first interval._
{{% /expand %}}
{{% expand "Group and aggregate query results into 1 hour intervals and offset time boundaries by -15 minutes" %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-02T00:00:00Z'
GROUP BY time(1h, -15m)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 2023-04-30T23:45:00Z | 29319.9092 |
| 2023-05-01T00:45:00Z | 29285.3651 |
| 2023-05-01T01:45:00Z | 28607.202666666668 |
| 2023-05-01T02:45:00Z | 28576.056175 |
| 2023-05-01T03:45:00Z | 28566.96315 |
| ... | ... |
{{% /expand %}}
{{< /expand-wrapper >}}
###### GROUP BY time and fill gaps
{{< expand-wrapper >}}
{{% expand "Group and aggregate query results into 30 minute intervals and fill gaps with `0`" %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-01T02:00:00Z'
GROUP BY
time(30m)
fill(0)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| -------------------- | ---------- |
| 2023-05-01T00:00:00Z | 29319.9092 |
| 2023-05-01T00:30:00Z | 29307.4416 |
| 2023-05-01T01:00:00Z | 0 |
| 2023-05-01T01:30:00Z | 29263.2886 |
{{% /expand %}}
{{% expand "Group and aggregate query results into 30 minute intervals and fill gaps using linear interpolation" %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-01T02:00:00Z'
GROUP BY
time(30m)
fill(linear)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| -------------------- | ---------- |
| 2023-05-01T00:00:00Z | 29319.9092 |
| 2023-05-01T00:30:00Z | 29307.4416 |
| 2023-05-01T01:00:00Z | 29285.3651 |
| 2023-05-01T01:30:00Z | 29263.2886 |
{{% /expand %}}
{{% expand "Group and aggregate query results into 30 minute intervals and fill gaps with previous values" %}}
```sql
SELECT
MEAN(price)
FROM bitcoin
WHERE
code = 'USD'
AND time >= '2023-05-01T00:00:00Z'
AND time < '2023-05-01T02:00:00Z'
GROUP BY
time(30m)
fill(previous)
```
{{% influxql/table-meta %}}
name: bitcoin
{{% /influxql/table-meta %}}
| time | mean |
| -------------------- | ---------- |
| 2023-05-01T00:00:00Z | 29319.9092 |
| 2023-05-01T00:30:00Z | 29307.4416 |
| 2023-05-01T01:00:00Z | 29307.4416 |
| 2023-05-01T01:30:00Z | 29263.2886 |
{{% /expand %}}
{{< /expand-wrapper >}}
## Result set
If at least one row satisfies the query, {{% product-name %}} returns row data in the query result set.
If a query uses a `GROUP BY` clause, the result set includes the following:
- Columns listed in the query's `SELECT` clause
- A `time` column that contains the timestamp for the record or the group
- An `iox::measurement` column that contains the record's measurement (table) name
- Columns listed in the query's `GROUP BY` clause; each row in the result set contains the values used for grouping
### Default time range
If a query doesn't specify a time range in the
[`WHERE` clause](/influxdb/cloud-serverless/reference/influxql/where/), InfluxDB uses the
[default time range](/influxdb/cloud-serverless/reference/influxql/#default-time-range) for filtering and grouping by time.
If a query includes the `GROUP BY` clause and doesn't specify a time range in the
`WHERE` clause, the default time group is the
[default time range](/influxdb/cloud-serverless/reference/influxql/#default-time-range), and the `time` column in the result set contains the start of the range--for example:
```sql
SELECT mean(temp) FROM home GROUP BY room
```
{{% influxql/table-meta %}}
name: home
tags: room=Kitchen
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -----------------: |
| 1970-01-01T00:00:00Z | 22.623076923076926 |
{{% influxql/table-meta %}}
name: home
tags: room=Living Room
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | ----------------: |
| 1970-01-01T00:00:00Z | 22.16923076923077 |
## Notable behaviors of the GROUP BY clause
### Cannot group by fields
InfluxQL does not support grouping data by **fields**.
### Tag order does not matter
The order that tags are listed in the `GROUP BY` clause does not affect how
data is grouped.
### Grouping by tag and no time range returns unexpected timestamps
The `time` column contains the start of the [default time range](#default-time-range).
### Data grouped by time may return unexpected timestamps
Because `GROUP BY time()` intervals use preset round-number time boundaries that
are independent of time conditions in the [`WHERE` clause](/influxdb/cloud-serverless/reference/influxql/where/),
results may include timestamps outside of the queried time range.
Results represent only data with timestamps in the specified time range, but
output timestamps are determined by by the preset time boundaries.
The following example groups data by 1-hour intervals, but the time range defined
in the `WHERE` clause covers only part of a window:
```sql
SELECT MEAN(field)
FROM example
WHERE
time >= '2022-01-01T00:30:00Z'
AND time <= '2022-01-01T01:30:00Z'
GROUP BY time(1h)
```
{{% note %}}
**Note**: The timestamp in the first row of query results data occurs before the start of
the queried time range.
[See why](#why-do-these-results-include-timestamps-outside-of-the-queried-time-range).
{{% /note %}}
{{% influxdb/custom-timestamps %}}
{{< flex >}}
{{% flex-content %}}
#### Example data
| time | field |
| :------------------- | ----: |
| 2022-01-01T00:00:00Z | 8 |
| 2022-01-01T00:15:00Z | 4 |
| 2022-01-01T00:30:00Z | 0 |
| 2022-01-01T00:45:00Z | 8 |
| 2022-01-01T01:00:00Z | 5 |
| 2022-01-01T01:15:00Z | 0 |
| 2022-01-01T01:30:00Z | 8 |
| 2022-01-01T01:45:00Z | 8 |
| 2022-01-01T02:00:00Z | 9 |
| 2022-01-01T02:15:00Z | 6 |
| 2022-01-01T02:30:00Z | 3 |
| 2022-01-01T02:45:00Z | 0 |
{{% /flex-content %}}
{{% flex-content %}}
#### Query results
| time | field |
| :------------------- | ----: |
| 2022-01-01T00:00:00Z | 4 |
| 2022-01-01T01:00:00Z | 5.25 |
| 2022-01-01T02:00:00Z | 6 |
{{% /flex-content %}}
{{< /flex >}}
{{% /influxdb/custom-timestamps %}}
{{< expand-wrapper >}}
{{% expand "Why do these results include timestamps outside of the queried time range?" %}}
`GROUP BY time()` creates windows with predefined time boundaries based on the
specified interval. These boundaries are not determined by the queried time
range, however, aggregate values in query results are calculated using only
values that are in the queried time range.
{{< html-diagram/influxql-windows >}}
{{% /expand %}}
{{< /expand-wrapper >}}
### Fill with no data in the queried time range
Queries ignore `fill()` if no data exists in the queried time range.
This is the expected behavior.
### Fill with previous if no previous value exists
`fill(previous)` doesnt fill null values if there is no previous value in
the queried time range.
### Fill with linear interpolation if there are not two values to interpolate between
`fill(linear)` doesn't fill null values if there are no values before or after
the null value in the queried time range.

View File

@ -6,159 +6,6 @@ menu:
name: InfluxQL internals
parent: influxql-reference
weight: 219
source: /shared/influxql-v3-reference/internals.md
---
Learn about the implementation of InfluxQL to understand how
results are processed and how to create efficient queries:
- [Query life cycle](#query-life-cycle)
- [Understanding iterators](#understanding-iterators)
- [Cursors](#cursors)
- [Auxiliary fields](#auxiliary-fields)
- [Built-in iterators](#built-in-iterators)
- [Call iterators](#call-iterators)
## Query life cycle
1. InfluxQL query string is tokenized and then parsed into an abstract syntax
tree (AST). This is the code representation of the query itself.
2. The AST is passed to the `QueryExecutor` which directs queries to the
appropriate handlers. For example, queries related to meta data are executed
by the **meta service** and `SELECT` statements are executed by the shards
themselves.
3. The query engine then determines the shards that match the `SELECT`
statement's time range. From these shards, iterators are created for each
field in the statement.
4. Iterators are passed to the emitter which drains them and joins the resulting
points. The emitter's job is to convert simple time/value points into the
more complex result objects that are returned to the client.
### Understanding iterators
Iterators provide a simple interface for looping over a set of points.
For example, this is an iterator over Float points:
```
type FloatIterator interface {
Next() *FloatPoint
}
```
These iterators are created through the `IteratorCreator` interface:
```
type IteratorCreator interface {
CreateIterator(opt *IteratorOptions) (Iterator, error)
}
```
The `IteratorOptions` provide arguments about field selection, time ranges,
and dimensions that the iterator creator can use when planning an iterator.
The `IteratorCreator` interface is used at many levels such as the `Shards`,
`Shard`, and `Engine`. This allows optimizations to be performed when applicable
such as returning a precomputed `COUNT()`.
Iterators aren't just for reading raw data from storage, though. Iterators can be
composed so that they provide additional functionality around an input
iterator. For example, a `DistinctIterator` can compute the distinct values for
each time window for an input iterator. Or a `FillIterator` can generate
additional points that are missing from an input iterator.
This composition also lends itself well to aggregation.
For example, in the following SQL, `MEAN(value)` is a `MeanIterator` that wraps an iterator from the
underlying shards:
```sql
SELECT MEAN(value) FROM cpu GROUP BY time(10m)
```
The following example wraps `MEAN(value)` with an additional iterator (`DERIVATIVE()`) to determine
the derivative of the mean:
```sql
SELECT DERIVATIVE(MEAN(value), 20m) FROM cpu GROUP BY time(10m)
```
### Cursors
A **cursor** identifies data by shard in tuples (time, value) for a single series (measurement, tag set and field). The cursor traverses data stored as a log-structured merge-tree and handles deduplication across levels, tombstones for deleted data, and merging the cache (Write Ahead Log). A cursor sorts the `(time, value)` tuples by time in ascending or descending order.
For example, a query that evaluates one field for 1,000 series over 3 shards constructs a minimum of 3,000 cursors (1,000 per shard).
### Auxiliary fields
Because InfluxQL allows users to use selector functions such as `FIRST()`,
`LAST()`, `MIN()`, and `MAX()`, the engine must provide a way to return related
data at the same time with the selected point.
Let's look at the following query:
```sql
SELECT FIRST(value), host FROM cpu GROUP BY time(1h)
```
We are selecting the first `value` that occurs every hour but we also want to
retrieve the `host` associated with that point. Since the `Point` types only
specify a single typed `Value` for efficiency, we push the `host` into the
auxiliary fields of the point. These auxiliary fields are attached to the point
until it is passed to the emitter where the fields get split off to their own
iterator.
### Built-in iterators
There are many helper iterators that let us build queries:
* Merge Iterator - This iterator combines one or more iterators into a single
new iterator of the same type. This iterator guarantees that all points
within a window will be output before starting the next window, but does not
provide ordering guarantees within the window. This allows for fast access
for aggregate queries that don't need stronger sorting guarantees.
* Sorted Merge Iterator - Like `MergeIterator`, this iterator combines one or more iterators
into a new iterator of the same type. However, this iterator guarantees
time ordering of every point. This makes it slower than the `MergeIterator`
but this ordering guarantee is required for non-aggregate queries which
return the raw data points.
* Limit Iterator - This iterator limits the number of points per name or tag
group. This is the implementation of the `LIMIT` & `OFFSET` syntax.
* Fill Iterator - This iterator injects extra points if they are missing from
the input iterator. It can provide `null` points, points with the previous
value, or points with a specific value.
* Buffered Iterator - This iterator provides the ability to "unread" a point
back onto a buffer so it can be read again next time. This is used extensively
to provide lookahead for windowing.
* Reduce Iterator - This iterator calls a reduction function for each point in
a window. When the window is complete, then all points for that window are
output. This is used for simple aggregate functions such as `COUNT()`.
* Reduce Slice Iterator - This iterator collects all points for a window first,
and then passes them all to a reduction function at once. The results are
returned from the iterator. This is used for aggregate functions such as
`DERIVATIVE()`.
* Transform Iterator - This iterator calls a transform function for each point
from an input iterator. This is used for executing binary expressions.
* Dedupe Iterator - This iterator only outputs unique points. Because it is resource-intensive, this iterator is only used for small queries such as meta query statements.
### Call iterators
Function calls in InfluxQL are implemented at two levels:
- Some calls can be
wrapped at multiple layers to improve efficiency. For example, a `COUNT()` can
be performed at the shard level and then multiple `CountIterator`s can be
wrapped with another `CountIterator` to compute the count of all shards. These
iterators can be created using `NewCallIterator()`.
- Some iterators are more complex or need to be implemented at a higher level.
For example, the `DERIVATIVE()` function needs to retrieve all points for a window
before performing the calculation. This iterator is created by the engine itself
and is never requested to be created by the lower levels.

View File

@ -13,249 +13,6 @@ list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] LIMIT row_N SLIMIT series_N
```
source: /shared/influxql-v3-reference/limit-and-slimit.md
---
Use `LIMIT` to limit the number of **rows** returned per InfluxQL group.
Use `SLIMIT` to limit the number of [series](/influxdb/cloud-serverless/reference/glossary/#series)
returned in query results.
- [LIMIT clause](#limit-clause)
- [Syntax](#limit-syntax)
- [Examples](#limit-examples)
- [SLIMIT clause](#slimit-clause)
<!-- - [Syntax](#slimit-syntax) -->
<!-- - [Examples](#slimit-examples) -->
<!-- - [Use LIMIT and SLIMIT together](#use-limit-and-slimit-together) -->
<!-- - [Syntax](#limit-slimit-syntax) -->
<!-- - [Examples](#limit-slimit-examples) -->
## LIMIT clause
The `LIMIT` clause limits the number of rows to return from each InfluxQL group.
If the query doesn't include a [`GROUP BY` clause](/influxdb/cloud-serverless/reference/influxql/group-by/),
the entire result set is considered a single group.
If a query [groups data by time](/influxdb/cloud-serverless/reference/influxql/group-by/#group-by-time),
limits are applied after aggregate and selector operations are applied to each
time window.
### Syntax {#limit-syntax}
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] LIMIT N
```
#### Arguments
- **N**: Maximum number of points to return from each InfluxQL group.
If `N` is greater than the number of points in a group,
all points from the group are returned.
### Examples {#limit-examples}
The following examples use the
[Get started home sensor sample data](/influxdb/cloud-serverless/reference/sample-data/#get-started-home-sensor-data).
{{< expand-wrapper >}}
{{% expand "Limit the number of rows returned" %}}
```sql
SELECT * FROM home LIMIT 3
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :---------- | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Living Room | 21.1 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Limit the number of rows returned from each InfluxQL group" %}}
```sql
SELECT
MEAN(*)
FROM home
GROUP BY
time(2h),
room
LIMIT 3
```
{{% influxdb/custom-timestamps %}}
{{% influxql/table-meta %}}
name: home
tags: room=Kitchen
{{% /influxql/table-meta %}}
| time | mean_co | mean_hum | mean_temp |
| :------------------- | ------: | -------: | -----------------: |
| 2022-01-01T08:00:00Z | 0 | 36.05 | 22 |
| 2022-01-01T10:00:00Z | 0 | 36.05 | 22.549999999999997 |
| 2022-01-01T12:00:00Z | 0.5 | 36.25 | 22.65 |
{{% influxql/table-meta %}}
name: home
tags: room=Living Room
{{% /influxql/table-meta %}}
| time | mean_co | mean_hum | mean_temp |
| :------------------- | ------: | -------: | -----------------: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | 21.25 |
| 2022-01-01T10:00:00Z | 0 | 36 | 22 |
| 2022-01-01T12:00:00Z | 0 | 35.95 | 22.299999999999997 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## SLIMIT clause
{{% warn %}}
InfluxQL is being rearchitected to work with the InfluxDB 3.0 storage engine.
This process is ongoing and some InfluxQL features, such as `SLIMIT` are still
being implemented. For more information, see
[InfluxQL feature support](/influxdb/cloud-serverless/reference/influxql/feature-support/).
{{% /warn %}}
<!-- The `SLIMIT` clause limits the number of [series](/influxdb/cloud-serverless/reference/glossary/#series)
to return in query results.
{{% note %}}
For meaningful results, queries that include the `SLIMIT` clause should also
include the [`GROUP BY` clause](/influxdb/cloud-serverless/reference/influxql/group-by/) that
[groups by tags](/influxdb/cloud-serverless/reference/influxql/group-by/#group-by-tags-examples).
Without grouping data by tags, all results are treated as a single series and
`SLIMIT` returns the full queried result set.
{{% /note %}}
### Syntax {#slimit-syntax}
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] [LIMIT_clause] SLIMIT N
```
If the query includes a [`LIMIT` clause](#limit-clause), the `SLIMIT` clause
must come **after** the `LIMIT` clause.
See [Use LIMIT and SLIMIT together](#use-limit-and-slimit-together).
#### Arguments
- **N**: Maximum number of series to return in query results.
If `N` is greater than the number of series in a measurement, the query
returns all series.
### Examples {#slimit-examples}
{{< expand-wrapper >}}
{{% expand "Limit the number of series returned" %}}
The following example uses the
[Bitcoin price sample data](/influxdb/cloud-serverless/reference/sample-data/#bitcoin-price-data).
```sql
SELECT * FROM bitcoin GROUP BY * SLIMIT 2
```
{{% influxql/table-meta %}}
name: bitcoin
tags: code=EUR, crypto=bitcoin, description=Euro, symbol=&euro;
{{% /influxql/table-meta %}}
| time | price |
| :------------------- | ---------: |
| 2023-05-01T00:19:00Z | 28561.8722 |
| 2023-05-01T00:48:00Z | 28549.727 |
| 2023-05-01T01:31:00Z | 28506.7155 |
| 2023-05-01T02:07:00Z | 27861.4404 |
| 2023-05-01T02:26:00Z | 27864.0643 |
| ... | ... |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=GBP, crypto=bitcoin, description=British Pound Sterling, symbol=&pound;
{{% /influxql/table-meta %}}
| time | price |
| :------------------- | ---------: |
| 2023-05-01T00:19:00Z | 24499.4816 |
| 2023-05-01T00:48:00Z | 24489.0637 |
| 2023-05-01T01:31:00Z | 24452.1698 |
| 2023-05-01T02:07:00Z | 23898.673 |
| 2023-05-01T02:26:00Z | 23900.9237 |
| ... | ... |
{{% /expand %}}
{{< /expand-wrapper >}}
## Use LIMIT and SLIMIT together
Using the `LIMIT` clause and the `SLIMIT` clause together returns the specified
maximum number of rows from the specified maximum number of series in query results.
### Syntax {#limit-slimit-syntax}
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] LIMIT row_N SLIMIT series_N
```
In queries that include both the `LIMIT` clause and the `SLIMIT` clause,
the `LIMIT` clause must come **first**.
#### Arguments
- **row_N**: Maximum number of points to return from each InfluxQL group.
If `row_N` is greater than the number of points in a group,
all points from the group are returned.
- **series_N**: Maximum number of series to return in query results.
If `series_N` is greater than the number of series in a measurement, the query
returns all series.
### Examples {#limit-slimit-examples}
{{< expand-wrapper >}}
{{% expand "Limit the number of rows and series returned" %}}
The following example uses the
[Bitcoin price sample data](/influxdb/cloud-serverless/reference/sample-data/#bitcoin-price-data).
```sql
SELECT * FROM bitcoin GROUP BY * LIMIT 3 SLIMIT 2
```
{{% influxql/table-meta %}}
name: bitcoin
tags: code=EUR, crypto=bitcoin, description=Euro, symbol=&euro;
{{% /influxql/table-meta %}}
| time | price |
| :------------------- | ---------: |
| 2023-05-01T00:19:00Z | 28561.8722 |
| 2023-05-01T00:48:00Z | 28549.727 |
| 2023-05-01T01:31:00Z | 28506.7155 |
{{% influxql/table-meta %}}
name: bitcoin
tags: code=GBP, crypto=bitcoin, description=British Pound Sterling, symbol=&pound;
{{% /influxql/table-meta %}}
| time | price |
| :------------------- | ---------: |
| 2023-05-01T00:19:00Z | 24499.4816 |
| 2023-05-01T00:48:00Z | 24489.0637 |
| 2023-05-01T01:31:00Z | 24452.1698 |
{{% /expand %}}
{{< /expand-wrapper >}} -->

View File

@ -9,273 +9,6 @@ menu:
parent: influxql-reference
identifier: influxql-mathematical-operators
weight: 215
source: /shared/influxql-v3-reference/math-operators.md
---
Use InfluxQL mathematical operators to perform mathematical operations in InfluxQL queries.
Mathematical operators follow the [standard order of operations](https://golang.org/ref/spec#Operator_precedence).
Parentheses take precedence to division and multiplication, which takes precedence to addition and subtraction.
For example `5 / 2 + 3 * 2 = (5 / 2) + (3 * 2)` and `5 + 2 * 3 - 2 = 5 + (2 * 3) - 2`.
- [Addition](#addition)
- [Subtraction](#subtraction)
- [Multiplication](#multiplication)
- [Division](#division)
- [Modulo](#modulo)
- [Bitwise AND](#bitwise-and)
- [Bitwise OR](#bitwise-or)
- [Bitwise Exclusive-OR](#bitwise-exclusive-or)
- [Unsupported Operators](#unsupported-operators)
- [Notable behaviors of mathematical operators](#notable-behaviors-of-mathematical-operators)
## Addition
Add two numeric operands. Operands may be an identifier, constant, or literal
numeric value.
```sql
SELECT A + 5 FROM example
SELECT A + B FROM example
SELECT * FROM example WHERE A + 5 > 10
SELECT * FROM example WHERE A + B > 10
```
## Subtraction
Subtract one numeric operand from another. Operands may be an identifier,
constant, or literal numeric value.
```sql
SELECT 1 - A FROM example
SELECT B - A FROM example
SELECT * FROM example WHERE 1 - A <= 3
SELECT * FROM example WHERE B - A <= 3
```
## Multiplication
Multiply two numeric operands. Operands may be an identifier, constant, or literal
numeric value.
```sql
SELECT A * 10 FROM example
SELECT A * B FROM example
SELECT * FROM example WHERE A * 10 >= 20
SELECT * FROM example WHERE A * B >= 20
```
Multiplication distributes across other operators.
```sql
SELECT 10 * (A + B + C) FROM example
SELECT 10 * (A - B - C) FROM example
SELECT 10 * (A + B - C) FROM example
```
## Division
Divide one numeric operand by another. Operands may be an identifier, constant,
or literal numeric value.
```sql
SELECT A / 10 FROM example
SELECT A / B FROM example
SELECT * FROM example WHERE A / 10 <= 2
SELECT * FROM example WHERE A / B <= 2
```
Division distributes across other operators.
```sql
SELECT 10 / (A + B + C) FROM example
SELECT 10 / (A - B - C) FROM example
SELECT 10 / (A + B - C) FROM example
```
## Modulo
Perform a modulo operation with two numeric operands. Operands may be an
identifier, constant, or literal numeric value.
```sql
SELECT A % 2 FROM example
SELECT A % B FROM example
SELECT A FROM example WHERE A % 2 = 0
SELECT A, B FROM example WHERE A % B = 0
```
## Bitwise AND
Perform a bitwise `AND` operation on two operands _of the same type_.
Supported types are **integers** and **booleans**.
Operands may be an identifier, constant, literal integer value, or literal boolean value.
```sql
SELECT A & 255 FROM example
SELECT A & B FROM example
SELECT (A ^ true) & B FROM example
SELECT * FROM example WHERE A & 15 > 0
```
## Bitwise OR
Perform a bitwise `OR` operation on two operands _of the same type_.
Supported types are **integers** and **booleans**.
Operands may be an identifier, constant, literal integer value, or literal boolean value.
```sql
SELECT A | 5 FROM example
SELECT A | B FROM example
SELECT * FROM example WHERE "bitfield" | 12 = 12
```
## Bitwise Exclusive-OR
Perform a bitwise `Exclusive-OR` operation on two operands _of the same type_.
Supported types are **integers** and **booleans**.
Operands may be an identifier, constant, literal integer value, or literal boolean value.
```sql
SELECT A ^ 255 FROM example
SELECT A ^ B FROM example
SELECT * FROM example WHERE "bitfield" ^ 6 > 0
```
## Unsupported Operators
### Inequalities
Using any of `=`,`!=`,`<`,`>`,`<=`,`>=`,`<>` in the `SELECT` statement yields
empty results for all types.
Comparison operators can only be used in the `WHERE` clause.
### Logical Operators
Using any of `!|`,`NAND`,`XOR`,`NOR` yield a parser error.
Additionally using `AND`, `OR` in the `SELECT` clause of a query will not behave
as mathematical operators and simply yield empty results, as they are InfluxQL tokens.
However, you can apply the bitwise operators `&`, `|` and `^` to boolean values.
### Bitwise Not
There is no bitwise-not operator, because the results you expect depend on the width of your bitfield.
InfluxQL does not know how wide your bitfield is, so cannot implement a suitable
bitwise-not operator.
For example, if your bitfield is 8 bits wide, then the integer 1 represents the bits `0000 0001`.
The bitwise-not of this should return the bits `1111 1110` (that is, the integer 254)
However, if your bitfield is 16 bits wide, then the integer 1 represents the bits `0000 0000 0000 0001`.
The bitwise-not of this should return the bits `1111 1111 1111 1110` (that is, the integer 65534)
#### Solution
You can implement a bitwise-not operation by using the `^` (bitwise xor) operator
together with the number representing all-ones for your word-width:
For 8-bit data:
```sql
SELECT A ^ 255 FROM example
```
For 16-bit data:
```sql
SELECT A ^ 65535 FROM example
```
For 32-bit data:
```sql
SELECT A ^ 4294967295 FROM example
```
In each case, the constant you need can be calculated as `(2 ** width) - 1`.
## Notable behaviors of mathematical operators
- [Mathematical operators with wildcards and regular expressions](#mathematical-operators-with-wildcards-and-regular-expressions)
- [Mathematical operators with functions](#mathematical-operators-with-functions)
### Mathematical operators with wildcards and regular expressions
InfluxQL does not support combining mathematical operations with a wildcard (`*`)
or [regular expression](/influxdb/cloud-serverless/reference/influxql/regular-expressions/)
in the `SELECT` clause.
The following queries are invalid and the system returns an error:
Perform a mathematical operation on a wildcard.
```sql
SELECT * + 2 FROM "nope"
-- ERR: unsupported expression with wildcard: * + 2
```
Perform a mathematical operation on a wildcard within a function.
```sql
SELECT COUNT(*) / 2 FROM "nope"
-- ERR: unsupported expression with wildcard: count(*) / 2
```
Perform a mathematical operation on a regular expression.
```sql
SELECT /A/ + 2 FROM "nope"
-- ERR: error parsing query: found +, expected FROM at line 1, char 12
```
Perform a mathematical operation on a regular expression within a function.
```sql
SELECT COUNT(/A/) + 2 FROM "nope"
-- ERR: unsupported expression with regex field: count(/A/) + 2
```
### Mathematical operators with functions
InfluxQL does not support mathematical operators inside of function calls.
Note that InfluxQL only allows functions in the `SELECT` clause.
For example, the following will work:
```sql
SELECT 10 * mean("value") FROM "cpu"
```
However, the following query will return a parse error:
```sql
SELECT mean(10 * "value") FROM "cpu"
-- Error: expected field argument in mean()
```
<!-- {{% note %}}
InfluxQL supports [subqueries](/influxdb/v2/query-data/influxql/explore-data/subqueries/) which offer similar functionality to using mathematical operators inside a function call.
{{% /note %}} -->

View File

@ -14,236 +14,6 @@ list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] [LIMIT_clause] OFFSET row_N [SLIMIT_clause] SOFFSET series_N
```
source: /shared/influxql-v3-reference/offset-and-soffset.md
---
Use `OFFSET` to specify the number of [rows](/influxdb/cloud-serverless/reference/glossary/#series)
to skip in each InfluxQL group before returning results.
Use `SOFFSET` to specify the number of [series](/influxdb/cloud-serverless/reference/glossary/#series)
to skip before returning results.
- [OFFSET clause](#offset-clause)
- [Syntax](#offset-syntax)
- [Notable OFFSET clause behaviors](#notable-offset-clause-behaviors)
- [Examples](#offset-examples)
- [SOFFSET clause](#soffset-clause)
<!-- - [Syntax](#soffset-syntax) -->
<!-- - [Notable SOFFSET clause behaviors](#notable-soffset-clause-behaviors) -->
<!-- - [Examples](#soffset-examples) -->
## `OFFSET` clause
The `OFFSET` clause skips `N` rows in each InfluxQL group before returning results.
Offsets honor row limits specified in the
[`LIMIT` clause](/influxdb/cloud-serverless/reference/influxql/limit-and-slimit/#limit-clause)
and display the limited number of rows after the specified offset.
Use `LIMIT` and `OFFSET` together to paginate query results.
### Syntax {#offset-syntax}
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] [LIMIT_clause] OFFSET N [SLIMIT_clause] [SOFFSET_clause]
```
#### Arguments
- **N**: Number of rows to skip in each InfluxQL group before returning results.
### Notable OFFSET clause behaviors
- If there is no `LIMIT` clause in a query with an `OFFSET` clause, the query
returns a single row per InfluxQL group at the specified offset.
- If the query doesn't include a [`GROUP BY` clause](/influxdb/cloud-serverless/reference/influxql/group-by/),
the entire result set is considered a single group and is returned in full.
- If a query [groups data by time](/influxdb/cloud-serverless/reference/influxql/group-by/#group-by-time),
the offset is applied after aggregate and selector operations are applied to each
time window.
- If the [`WHERE` clause](/influxdb/cloud-serverless/reference/influxql/where/)
includes a time range and the `OFFSET` clause causes InfluxQL to return points
with timestamps outside of that time range, InfluxQL returns no results.
### Examples {#offset-examples}
The following examples use the
[Get started home sensor sample data](/influxdb/cloud-serverless/reference/sample-data/#get-started-home-sensor-data).
{{< expand-wrapper >}}
{{% expand "Return the nth row" %}}
```sql
SELECT * FROM home OFFSET 3
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :---------- | ---: |
| 2022-01-01T09:00:00Z | 0 | 35.9 | Living Room | 21.4 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Paginate results by 3 and return the 2nd page of results" %}}
```sql
SELECT * FROM home WHERE room = 'Kitchen' LIMIT 3 OFFSET 3
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :------ | ---: |
| 2022-01-01T11:00:00Z | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T12:00:00Z | 0 | 36 | Kitchen | 22.5 |
| 2022-01-01T13:00:00Z | 1 | 36.5 | Kitchen | 22.8 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Paginate results from each series by 3 and return the 2nd page of each series" %}}
```sql
SELECT * FROM home GROUP BY * LIMIT 3 OFFSET 3
```
{{% influxdb/custom-timestamps %}}
{{% influxql/table-meta %}}
name: home
tags: room=Kitchen
{{% /influxql/table-meta %}}
| time | co | hum | temp |
| :------------------- | --: | ---: | ---: |
| 2022-01-01T11:00:00Z | 0 | 36 | 22.4 |
| 2022-01-01T12:00:00Z | 0 | 36 | 22.5 |
| 2022-01-01T13:00:00Z | 1 | 36.5 | 22.8 |
{{% influxql/table-meta %}}
name: home
tags: room=Living Room
{{% /influxql/table-meta %}}
| time | co | hum | temp |
| :------------------- | --: | ---: | ---: |
| 2022-01-01T11:00:00Z | 0 | 36 | 22.2 |
| 2022-01-01T12:00:00Z | 0 | 35.9 | 22.2 |
| 2022-01-01T13:00:00Z | 0 | 36 | 22.4 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## `SOFFSET` clause
{{% warn %}}
InfluxQL is being rearchitected to work with the InfluxDB 3.0 storage engine.
This process is ongoing and some InfluxQL features, such as `SOFFSET` are still
being implemented. For more information, see
[InfluxQL feature support](/influxdb/cloud-serverless/reference/influxql/feature-support/).
{{% /warn %}}
<!-- The `SOFFSET` clause skips `N` [series](/influxdb/cloud-serverless/reference/glossary/#series)
before returning results.
Offsets honor series limits specified in the
[`SLIMIT` clause](/influxdb/cloud-serverless/reference/influxql/limit-and-slimit/#slimit-clause)
and display the limited number of series after the specified offset.
Use `SLIMIT` and `SOFFSET` together to paginate grouped query results.
The `SOFFSET` clause requires these other clauses:
- [`SLIMIT` clause](/influxdb/cloud-serverless/reference/influxql/limit-and-slimit/#slimit-clause)
- [`GROUP BY` clause](/influxdb/cloud-serverless/reference/influxql/group-by/) that
[groups by tags](/influxdb/cloud-serverless/reference/influxql/group-by/#group-by-tags-examples)
### Syntax {#soffset-syntax}
```sql
SELECT_clause FROM_clause [WHERE_clause] GROUP_BY_clause [ORDER_BY_clause] [LIMIT_clause] [OFFSET_clause] SLIMIT_clause SOFFSET N
```
#### Arguments
- **N**: Number of [series](/influxdb/cloud-serverless/reference/glossary/#series)
to skip before returning results.
{{% note %}}
**Note:**
{{% /note %}}
### Notable SOFFSET clause behaviors
- If there is no `SLIMIT` clause in a query with an `SOFFSET` clause, the query
returns no results.
- If the query doesn't include a [`GROUP BY` clause](/influxdb/cloud-serverless/reference/influxql/group-by/),
the query returns no results.
- If the `SOFFSET` clause skips more than the total number of series, the query
returns no results.
### Examples {#soffset-examples}
The following examples use the
[Bitcoin price sample data](/influxdb/cloud-serverless/reference/sample-data/#bitcoin-price-data).
{{< expand-wrapper >}}
{{% expand "Return the 2nd series" %}}
```sql
SELECT * FROM bitcoin GROUP BY * SLIMIT 1 SOFFSET 1
```
{{% influxql/table-meta %}}
name: bitcoin
tags: code=GBP, crypto=bitcoin, description=British Pound Sterling, symbol=&pound;
{{% /influxql/table-meta %}}
| time | price |
| :------------------- | ---------: |
| 2023-05-01T00:19:00Z | 24499.4816 |
| 2023-05-01T00:48:00Z | 24489.0637 |
| 2023-05-01T01:31:00Z | 24452.1698 |
| 2023-05-01T02:07:00Z | 23898.673 |
| 2023-05-01T02:26:00Z | 23900.9237 |
| ... | ... |
{{% /expand %}}
{{% expand "Paginate series by 2 and return the 2nd page of results" %}}
```sql
SELECT * FROM bitcoin GROUP BY * 2 SOFFSET 2
```
{{% note %}}
Because the **Bitcoin price sample data** contains only 3 series, when paginating
by 2, the 2nd "page" contains only one series.
{{% /note %}}
{{% influxql/table-meta %}}
name: bitcoin
tags: code=USD, crypto=bitcoin, description=United States Dollar, symbol=&#36;
{{% /influxql/table-meta %}}
| time | price |
| :------------------- | ---------: |
| 2023-05-01T00:19:00Z | 29319.9092 |
| 2023-05-01T00:48:00Z | 29307.4416 |
| 2023-05-01T01:31:00Z | 29263.2886 |
| 2023-05-01T02:07:00Z | 28600.8878 |
| 2023-05-01T02:26:00Z | 28603.5813 |
| ... | ... |
{{% /expand %}}
{{< /expand-wrapper >}} -->

View File

@ -13,97 +13,6 @@ list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] ORDER BY time [DESC|ASC]
```
source: /shared/influxql-v3-reference/order-by.md
---
Use the `ORDER BY` clause to sort data by time in ascending or descending order.
InfluxQL only supports sorting data by `time`.
- [Syntax](#syntax)
- [Examples](#examples)
## Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] ORDER BY time [ASC|DESC]
```
- If the the `ORDER BY` clause is not included, the default behavior is to sort data by
time in **ascending** order: `ORDER BY time ASC`.
- If the query includes [`WHERE`](/influxdb/cloud-serverless/reference/influxql/where/)
and [`GROUP BY`](/influxdb/cloud-serverless/reference/influxql/group-by/) clauses,
the `ORDER BY` clause must come **after** these clauses.
#### Sort orders
- **ASC (ascending)**: The first row in the results has the oldest timestamp.
The last row in the results has the most recent timestamp.
- **DESC (descending)**: The first row in the results has the most recent timestamp.
The last row in the results has the oldest timestamp.
## Examples
The following examples use the
[Get started home sensor sample data](/influxdb/cloud-serverless/reference/sample-data/#get-started-home-sensor-data).
{{< expand-wrapper >}}
{{% expand "Sort data with the oldest points first" %}}
{{% note %}}
Ordering data by time in ascending order is the default behavior.
Including `ORDER BY time ASC` in the query isn't necessary, but it is supported.
{{% /note %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T12:00:00Z'
ORDER BY time ASC
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :------ | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T11:00:00Z | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T12:00:00Z | 0 | 36 | Kitchen | 22.5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Sort data with the newest points first" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T12:00:00Z'
ORDER BY time DESC
```
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :------ | ---: |
| 2022-01-01T12:00:00Z | 0 | 36 | Kitchen | 22.5 |
| 2022-01-01T11:00:00Z | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -17,48 +17,6 @@ list_code_example: |
-- Quoted identifier
"this-is-an-identifier"
```
source: /shared/influxql-v3-reference/quoting.md
---
InfluxQL supports both single and double quotation marks, but they each function
differently and serve different purposes.
- [Single quotes](#single-quotes)
- [Double quotes](#double-quotes)
## Single quotes
Use single quotation marks (`'`) in the
[string literal](/influxdb/cloud-serverless/reference/influxql/#strings) and
[timestamp literal](/influxdb/cloud-serverless/reference/influxql/#dates--times) syntax.
In the following example, the `WHERE` clause evaluates the value of the `room` tag.
Tags only contain string values, so the right operand of the predicate expression
should be a string literal.
```sql
... WHERE room = 'Kitchen'
```
## Double quotes
Use double quotation marks (`"`) to quote [identifiers](/influxdb/cloud-serverless/reference/influxql/#identifiers).
Identifiers **must** be double-quoted in the following cases:
- The identifier contains non-word characters.
Word characters are defined as `[a-z,A-Z,0-9,_]`.
- The identifier is case-sensitive.
- The identifier contains [InfluxQL keywords](/influxdb/cloud-serverless/reference/influxql/#keywords).
- The identifier begins with a digit.
Double-quoted identifiers can also:
- Contain any Unicode character except for a new line.
- Contain escaped `"` characters (for example: `\"`).
- Include [InfluxQL keywords](/influxdb/cloud-serverless/reference/influxql/#keywords).
**While not always necessary, we recommend that you double quote identifiers.**
{{% note %}}
InfluxQL quoting guidelines differ from
[line protocol quoting guidelines](/influxdb/cloud-serverless/reference/syntax/line-protocol/#quotes).
{{% /note %}}

View File

@ -13,198 +13,6 @@ list_code_example: |
```sql
SELECT /<regular_expression_field_key>/ FROM /<regular_expression_measurement>/ WHERE [<tag_key> <operator> /<regular_expression_tag_value>/ | <field_key> <operator> /<regular_expression_field_value>/] GROUP BY /<regular_expression_tag_key>/
```
source: /shared/influxql-v3-reference/regular-expressions.md
---
Regular expressions are a sequence of characters used to identify patterns in
identifiers and string values.
InfluxQL supports regular expressions in the following operations:
- Identifying **fields** and **tags** to query in the
[`SELECT` clause](/influxdb/cloud-serverless/reference/influxql/select/).
- Identifying **measurements** to query in the
[`FROM` clause](/influxdb/cloud-serverless/reference/influxql/select/#from-clause).
- Testing **tag values** and **string field values** in the
[`WHERE` clause](/influxdb/cloud-serverless/reference/influxql/where/).
- Identifying **tag keys** to group by in the
[`GROUP BY` clause](/influxdb/cloud-serverless/reference/influxql/group-by/)
{{% note %}}
#### Query performance
Regular expression comparisons are more computationally intensive than exact
string comparisons. Queries with regular expressions are not as performant
as those without.
{{% /note %}}
## Regular expression syntax
InfluxQL Regular expressions are surrounded by `/` characters and use the
[Go regular expression syntax](http://golang.org/pkg/regexp/syntax/).
```sql
/regular_expression/
```
### Regular expression flags
Regular expression flags modify the pattern-matching behavior of the expression.
InfluxQL supports the following regular expression flags:
| Flag | Description |
| :--- | :------------------------------------------------------------------------------ |
| i | case-insensitive |
| m | multi-line mode: `^` and `$` match begin/end line in addition to begin/end text |
| s | let `.` match `\n` |
| U | ungreedy: swap meaning of `x*` and `x*?`, `x+` and `x+?`, etc. |
Include regular expression flags at the beginning of your regular expression
pattern enclosed in parentheses (`()`) and preceded by a question mark (`?`).
```sql
/(?iU)foo*/
```
## Regular expression operators
InfluxQL provides the following regular expression operators that test if a
string operand matches a regular expression:
- `=~`: Returns true if the string matches the regular expression
- `!~`: Returns true if the string does not match the regular expression
InfluxQL regular expression operators are used to test string column values in
the [`WHERE` clause](/influxdb/cloud-serverless/reference/influxql/where/).
## Regular expression examples
The examples below use the following sample data sets:
- [NOAA Bay Area weather data](/influxdb/cloud-serverless/reference/sample-data/#noaa-bay-area-weather-data)
- [Get started home sensor data](/influxdb/cloud-serverless/reference/sample-data/#get-started-home-sensor-data)
{{< expand-wrapper >}}
{{% expand "Use a regular expression to specify field keys and tag keys in the SELECT clause" %}}
```sql
SELECT /^t/ FROM weather
```
{{% influxql/table-meta %}}
name: weather
{{% /influxql/table-meta %}}
| time | temp_avg | temp_max | temp_min |
| :------------------- | -------: | -------: | -------: |
| 2020-01-01T00:00:00Z | 52 | 66 | 44 |
| 2020-01-01T00:00:00Z | 53 | 59 | 47 |
| 2020-01-01T00:00:00Z | 50 | 57 | 44 |
| 2020-01-02T00:00:00Z | 54 | 61 | 49 |
| 2020-01-02T00:00:00Z | 51 | 60 | 44 |
| 2020-01-02T00:00:00Z | 53 | 66 | 42 |
| ... | ... | ... | ... |
{{% /expand %}}
{{% expand "Use a regular expression to specify measurements in the FROM clause" %}}
```sql
SELECT /^t/ FROM /^[hw]/
```
{{% influxql/table-meta %}}
name: weather
{{% /influxql/table-meta %}}
| time | temp | temp_avg | temp_max | temp_min |
| :------------------- | ---: | -------: | -------: | -------: |
| 2020-01-01T00:00:00Z | | 52 | 66 | 44 |
| 2020-01-01T00:00:00Z | | 53 | 59 | 47 |
| 2020-01-01T00:00:00Z | | 50 | 57 | 44 |
| 2020-01-02T00:00:00Z | | 54 | 61 | 49 |
| 2020-01-02T00:00:00Z | | 51 | 60 | 44 |
| 2020-01-02T00:00:00Z | | 53 | 66 | 42 |
| ... | ... | ... | ... | ... |
{{% /expand %}}
{{% expand "Use a regular expression to specify tag values in the WHERE clause" %}}
```sql
SELECT * FROM weather WHERE location !~ /^[S]/
```
{{% influxql/table-meta %}}
name: weather
{{% /influxql/table-meta %}}
| time | location | precip | temp_avg | temp_max | temp_min | wind_avg |
| :------------------- | :------- | -----: | -------: | -------: | -------: | -------: |
| 2020-01-01T00:00:00Z | Concord | 0 | 52 | 66 | 44 | 3.13 |
| 2020-01-01T00:00:00Z | Hayward | 0 | 50 | 57 | 44 | 2.24 |
| 2020-01-02T00:00:00Z | Concord | 0 | 53 | 66 | 42 | 3.13 |
| 2020-01-02T00:00:00Z | Hayward | 0 | 51 | 60 | 44 | 3.8 |
| 2020-01-03T00:00:00Z | Concord | 0 | 49 | 60 | 38 | 2.68 |
| 2020-01-03T00:00:00Z | Hayward | 0 | 50 | 62 | 41 | 3.13 |
| ... | ... | ... | ... | ... | ... | ... |
{{% /expand %}}
{{% expand "Use a regular expression to specify a tag with no value in the WHERE clause" %}}
```sql
SELECT * FROM home, weather WHERE location !~ /./
```
{{% influxql/table-meta %}}
name: weather
{{% /influxql/table-meta %}}
| time | co | hum | location | precip | room | temp | temp_avg | temp_max | temp_min | wind_avg |
| :------------------- | --: | ---: | -------- | ------ | :---------- | ---: | -------- | -------- | -------- | -------- |
| 2022-01-01T08:00:00Z | 0 | 35.9 | | | Kitchen | 21 | | | | |
| 2022-01-01T08:00:00Z | 0 | 35.9 | | | Living Room | 21.1 | | | | |
| 2022-01-01T09:00:00Z | 0 | 36.2 | | | Kitchen | 23 | | | | |
| 2022-01-01T09:00:00Z | 0 | 35.9 | | | Living Room | 21.4 | | | | |
| 2022-01-01T10:00:00Z | 0 | 36.1 | | | Kitchen | 22.7 | | | | |
| 2022-01-01T10:00:00Z | 0 | 36 | | | Living Room | 21.8 | | | | |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
{{% /expand %}}
{{% expand "Use a regular expression to specify tag keys in the GROUP BY clause" %}}
```sql
SELECT MAX(precip) FROM weather GROUP BY /^l/
```
{{% influxql/table-meta %}}
name: weather
tags: location=Concord
{{% /influxql/table-meta %}}
| time | max |
| :------------------- | ---: |
| 2021-10-24T00:00:00Z | 4.53 |
{{% influxql/table-meta %}}
name: weather
tags: location=Hayward
{{% /influxql/table-meta %}}
| time | max |
| :------------------- | ---: |
| 2022-12-31T00:00:00Z | 4.34 |
{{% influxql/table-meta %}}
name: weather
tags: location=San Francisco
{{% /influxql/table-meta %}}
| time | max |
| :------------------- | ---: |
| 2021-10-24T00:00:00Z | 4.02 |
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -14,451 +14,6 @@ list_code_example: |
```sql
SELECT <field_key>[,<field_key>,<tag_key>] FROM <measurement_name>[,<measurement_name>]
```
source: /shared/influxql-v3-reference/select.md
---
Use the `SELECT` statement to query data from one or more
[measurements](/influxdb/cloud-serverless/reference/glossary/#measurement).
The `SELECT` statement **requires** a [`SELECT` clause](#select-clause) and a
[`FROM` clause](#from-clause).
- [Syntax](#syntax)
- [SELECT clause](#select-clause)
- [FROM clause](#from-clause)
- [Notable SELECT statement behaviors](#notable-select-statement-behaviors)
- [Data types and casting operations](#data-types-and-casting-operations)
- [SELECT statement examples](#select-statement-examples)
<!-- - [Multiple statements](#multiple-statements) -->
## Syntax
```sql
SELECT field_expression[, ..., field_expression_n[, tag_expression[, ..., tag_expression_n]]] FROM measurement_expression[, ..., measurement_expression_n]
```
### SELECT clause
The `SELECT` clause supports several formats for identifying data to query.
It requires one or more **field expressions** and optional **tag expressions**.
- **field_expression**: Expression to identify one or more fields to return in query results.
Can be a [field key](/influxdb/cloud-serverless/reference/glossary/#field-key),
constant, [regular expression](/influxdb/cloud-serverless/reference/influxql/regular-expressions/),
[wildcard (`*`)](#wildcard-expressions-in-select-clauses), or
[function expression](/influxdb/cloud-serverless/reference/influxql/functions/) and any
combination of arithmetic operators.
- **tag_expression**: Expression to identify one or more tags to return in query results.
Can be a [tag key](/influxdb/cloud-serverless/reference/glossary/#tag-key) or constant.
#### Select clause behaviors
- `SELECT field_key` - Returns a specific field.
- `SELECT field_key1, field_key2` - Returns two specific fields.
- `SELECT field_key, tag_key` - Returns a specific field and tag.
- `SELECT *` - Returns all [fields](/influxdb/cloud-serverless/reference/glossary/#field)
and [tags](/influxdb/cloud-serverless/reference/glossary/#tag).
_See [Wildcard expressions](#wildcard-expressions)._
- `SELECT /^[t]/` - Returns all [fields](/influxdb/cloud-serverless/reference/glossary/#field)
and [tags](/influxdb/cloud-serverless/reference/glossary/#tag) with keys that
match the regular expression. At least one field key must match the regular
expression. If no field keys match the regular expression, no results are
returned.
### FROM clause
The `FROM` clause specifies the
[measurement](/influxdb/cloud-serverless/reference/glossary/#measurement) or
[subquery](/influxdb/cloud-serverless/reference/influxql/subqueries/) to query.
It requires one or more comma-delimited
[measurement expressions](#measurement_expression) or [subqueries](#subquery).
#### measurement_expression
A measurement expression identifies a measurement to query.
It can be a measurement name, fully-qualified measurement, constant, or
a [regular expression](/influxdb/cloud-serverless/reference/influxql/regular-expressions/).
- **Measurement name**: When using just the measurement name, InfluxQL assumes
the default retention policy of the database specified in the query request.
```sql
FROM measurement
```
- **Fully-qualified measurement**: A fully qualified measurement includes a
database name, retention policy name, and measurement name, each separated by
a period (`.`). If the retention policy is not specified, InfluxQL uses the
default retention policy for the specified database.
```sql
FROM database.retention_policy.measurement
-- Fully-qualified measurement with default retention policy
FROM database..measurement
```
{{% note %}}
#### InfluxQL retention policies
In {{< product-name >}}, **retention policies** are not part of the data model
like they are in InfluxDB 1.x.
Each {{< product-name >}} database has a **retention period** which defines the
maximum age of data to retain in the database. To use fully-qualified
measurements in InfluxQL queries, use the following naming convention when
[creating a database](/influxdb/cloud-serverless/admin/databases/create/):
```
database_name/retention_policy
```
{{% /note %}}
#### Subquery
An InfluxQL subquery is a query nested in the `FROM` clause of an InfluxQL query.
The outer query queries results returned by the inner query (subquery).
For more information, see [InfluxQL subqueries](/influxdb/cloud-serverless/reference/influxql/subqueries/).
## Notable SELECT statement behaviors
- [Must query at least one field](#must-query-at-least-one-field)
- [Wildcard expressions](#wildcard-expressions)
- [Cannot include both aggregate and non-aggregate field expressions](#cannot-include-both-aggregate-and-non-aggregate-field-expressions)
### Must query at least one field
A query requires at least one [field key](/influxdb/cloud-serverless/reference/glossary/#field-key)
in the `SELECT` clause to return data.
If the `SELECT` clause includes only [tag keys](/influxdb/cloud-serverless/reference/glossary/#tag-key),
the query returns an empty result.
When using regular expressions in the `SELECT` clause, if regular expression
matches only tag keys and no field keys, the query returns an empty result.
To return data associated with tag keys, include at least one field key in the
`SELECT` clause.
### Wildcard expressions
When using a wildcard expression (`*`) in the `SELECT` clause, the query returns
all tags and fields.
If a [function](/influxdb/cloud-serverless/reference/influxql/functions/) is
applied to a wildcard expression, the query returns all _fields_ with
the function applied, but does not return _tags_ unless they are included in
the `SELECT` clause.
### Cannot include both aggregate and non-aggregate field expressions
The `SELECT` statement cannot include an aggregate field expression
(one that uses an [aggregate](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/)
or [selector](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/)
function) **and** a non-aggregate field expression.
For example, in the following query, an aggregate function is applied to one
field, but not the other:
```sql
SELECT mean(temp), hum FROM home
```
This query returns an error.
For more information, see [error about mixing aggregate and non-aggregate queries](/enterprise_influxdb/v1/troubleshooting/errors/#error-parsing-query-mixing-aggregate-and-non-aggregate-queries-is-not-supported).
## Data types and casting operations
The [`SELECT` clause](#select-clause) supports specifying a
[field's](/influxdb/cloud-serverless/reference/glossary/#field) type and basic
casting operations with the `::` syntax.
```sql
SELECT field_expression::type FROM measurement_expression
```
The `::` syntax allows users to perform basic cast operations in queries.
Currently, InfluxQL supports casting _numeric_ [field values](/influxdb/cloud-serverless/reference/glossary/#field-value)
to other numeric types.
Casting to an **identifier type** acts as a filter on results and returns only
columns of that specific identifier type along with the `time` column.
{{< flex >}}
{{% flex-content "third" %}}
##### Numeric types
- `float`
- `integer`
- `unsigned`
{{% /flex-content %}}
{{% flex-content "third" %}}
##### Non-numeric types
- `string`
- `boolean`
{{% /flex-content %}}
{{% flex-content "third" %}}
##### Identifier types
- `field`
- `tag`
{{% /flex-content %}}
{{< /flex >}}
{{% note %}}
InfluxQL returns no data if the query attempts to cast a numeric value to a
non-numeric type and vice versa.
{{% /note %}}
When casting a float value to an integer or unsigned integer, the float value
is truncated at the decimal point. No rounding is performed.
## SELECT statement examples
The examples below use the following sample data sets:
- [Get started home sensor data](/influxdb/cloud-serverless/reference/sample-data/#get-started-home-sensor-data)
- [NOAA Bay Area weather data](/influxdb/cloud-serverless/reference/sample-data/#noaa-bay-area-weather-data)
{{< expand-wrapper >}}
{{% expand "Select all fields and tags from a measurement" %}}
```sql
SELECT * FROM home
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :---------- | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Living Room | 21.1 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T09:00:00Z | 0 | 35.9 | Living Room | 21.4 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T10:00:00Z | 0 | 36 | Living Room | 21.8 |
| ... | ... | ... | ... | ... |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select specific tags and fields from a measurement" %}}
```sql
SELECT temp, hum, room FROM home
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | temp | hum | room |
| :------------------- | ---: | ---: | :---------- |
| 2022-01-01T08:00:00Z | 21 | 35.9 | Kitchen |
| 2022-01-01T08:00:00Z | 21.1 | 35.9 | Living Room |
| 2022-01-01T09:00:00Z | 23 | 36.2 | Kitchen |
| 2022-01-01T09:00:00Z | 21.4 | 35.9 | Living Room |
| 2022-01-01T10:00:00Z | 22.7 | 36.1 | Kitchen |
| 2022-01-01T10:00:00Z | 21.8 | 36 | Living Room |
| ... | ... | ... | ... |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select all fields from a measurement" %}}
```sql
SELECT *::field FROM home
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | hum | temp |
| :------------------- | --: | ---: | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | 21 |
| 2022-01-01T08:00:00Z | 0 | 35.9 | 21.1 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | 23 |
| 2022-01-01T09:00:00Z | 0 | 35.9 | 21.4 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | 22.7 |
| 2022-01-01T10:00:00Z | 0 | 36 | 21.8 |
| ... | ... | ... | ... |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select a field from a measurement and perform basic arithmetic" %}}
```sql
SELECT (temp * (9 / 5)) + 32 FROM home
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | temp |
| :------------------- | ----------------: |
| 2022-01-01T08:00:00Z | 69.80000000000001 |
| 2022-01-01T08:00:00Z | 69.98 |
| 2022-01-01T09:00:00Z | 73.4 |
| 2022-01-01T09:00:00Z | 70.52 |
| 2022-01-01T10:00:00Z | 72.86 |
| 2022-01-01T10:00:00Z | 71.24000000000001 |
| ... | ... |
{{% /influxdb/custom-timestamps %}}
{{% note %}}
**Note:** InfluxDB follows the standard order of operations.
See [InfluxQL mathematical operators](/influxdb/cloud-serverless/reference/influxql/math-operators/)
for more on supported operators.
{{% /note %}}
{{% /expand %}}
{{% expand "Select all data from more than one measurement" %}}
```sql
SELECT * FROM home, weather
```
{{% influxql/table-meta %}}
Name: weather
{{% /influxql/table-meta %}}
| time | co | hum | location | precip | room | temp | temp_avg | temp_max | temp_min | wind_avg |
| :------------------- | --: | --: | :------------ | -----: | :--- | ---: | -------: | -------: | -------: | -------: |
| 2020-01-01T00:00:00Z | | | Concord | 0 | | | 52 | 66 | 44 | 3.13 |
| 2020-01-01T00:00:00Z | | | San Francisco | 0 | | | 53 | 59 | 47 | 14.32 |
| 2020-01-01T00:00:00Z | | | Hayward | 0 | | | 50 | 57 | 44 | 2.24 |
| 2020-01-02T00:00:00Z | | | San Francisco | 0 | | | 54 | 61 | 49 | 5.82 |
| 2020-01-02T00:00:00Z | | | Hayward | 0 | | | 51 | 60 | 44 | 3.8 |
| 2020-01-02T00:00:00Z | | | Concord | 0 | | | 53 | 66 | 42 | 3.13 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
{{% /expand %}}
{{% expand "Select all data from a fully-qualified measurement (with default retention policy)" %}}
```sql
SELECT * FROM "get-started"..home
```
{{% influxql/table-meta %}}
Name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :---------- | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Living Room | 21.1 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T09:00:00Z | 0 | 35.9 | Living Room | 21.4 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T10:00:00Z | 0 | 36 | Living Room | 21.8 |
| ... | ... | ... | ... | ... |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
### Type-casting examples
{{< expand-wrapper >}}
{{% expand "Cast an integer field to a float" %}}
```sql
SELECT co::float FROM home
```
{{% /expand %}}
{{% expand "Cast a float field to an integer" %}}
```sql
SELECT temp::integer FROM home
```
{{% /expand %}}
{{% expand "Cast a float field to an unsigned integer" %}}
```sql
SELECT temp::unsigned FROM home
```
{{% /expand %}}
{{< /expand-wrapper >}}
<!-- ## Multiple statements
Separate multiple `SELECT` statements in a query with a semicolon (`;`).
### Examples
The **InfluxDB v1 query API** returns a JSON response with a `statement_id`
field for each `SELECT` statement.
```json
{
"results": [
{
"statement_id": 0,
"series": [
{
"name": "h2o_feet",
"columns": [
"time",
"mean"
],
"values": [
[
"1970-01-01T00:00:00Z",
4.442107025822522
]
]
}
]
},
{
"statement_id": 1,
"series": [
{
"name": "h2o_feet",
"columns": [
"time",
"water_level"
],
"values": [
[
"2015-08-18T00:00:00Z",
8.12
],
[
"2015-08-18T00:00:00Z",
2.064
]
]
}
]
}
]
}
``` -->

View File

@ -1,7 +1,7 @@
---
title: InfluxQL SHOW statements
description: >
Use InfluxQL `SHOW` statements to query schema information from a bucket.
Use InfluxQL `SHOW` statements to query schema information from a database.
menu:
influxdb_cloud_serverless:
name: SHOW statements
@ -14,153 +14,6 @@ list_code_example: |
```
related:
- /influxdb/cloud-serverless/query-data/influxql/explore-schema/
source: /shared/influxql-v3-reference/show.md
---
Use InfluxQL `SHOW` statements to query schema information from a database.
- [SHOW RETENTION POLICIES](#show-retention-policies)
- [SHOW MEASUREMENTS](#show-measurements)
- [SHOW FIELD KEYS](#show-field-keys)
- [SHOW TAG KEYS](#show-tag-keys)
- [SHOW TAG VALUES](#show-tag-values)
## SHOW RETENTION POLICIES
Use the `SHOW RETENTION POLICIES` statement to list retention policies associated
with a database.
Each database has a single retention policy--`autogen`.
{{% note %}}
In {{< product-name >}}, retention policies are not part of the
data structure but are expected by InfluxQL and used in fully-qualified measurements
in the [`FROM` clause](/influxdb/cloud-serverless/reference/influxql/select/#from-clause).
The data returned for each retention policy does not represent the actual
retention-related attributes of the database. The values are placeholder values
meant only for InfluxQL feature parity.
For information about database data retention, see
[List databases](/influxdb/cloud-serverless/admin/databases/list/).
{{% /note %}}
```sql
SHOW RETENTION POLICIES [ON <database-name>]
```
#### Examples
```sql
-- Show retention policies in the database specified in the query request
SHOW RETENTION POLICIES
-- Show retention policies in a specific database
SHOW RETENTION POLICIES ON "example-database"
```
## SHOW MEASUREMENTS
Use the `SHOW MEASUREMENTS` statement to list measurements in a bucket.
```sql
SHOW MEASUREMENTS [with_measurement_clause] [where_clause] [limit_clause] [offset_clause]
```
#### Examples
```sql
-- Show all measurements
SHOW MEASUREMENTS
-- Show measurements where region tag = 'uswest' AND host tag = 'serverA'
SHOW MEASUREMENTS WHERE "region" = 'uswest' AND "host" = 'serverA'
-- Show measurements that start with 'h2o'
SHOW MEASUREMENTS WITH MEASUREMENT =~ /h2o.*/
```
## SHOW FIELD KEYS
Use the `SHOW FIELD KEYS` statement to list all field keys in a measurement.
```sql
SHOW FIELD KEYS [from_clause]
```
#### Examples
```sql
-- Show field keys and field value data types from all measurements
SHOW FIELD KEYS
-- Show field keys and field value data types from specified measurement
SHOW FIELD KEYS FROM "cpu"
```
## SHOW TAG KEYS
Use the `SHOW TAG KEYS` statement to list tag keys in a measurement.
```sql
SHOW TAG KEYS [from_clause] [where_clause] [limit_clause] [offset_clause]
```
#### Examples
```sql
-- Show all tag keys
SHOW TAG KEYS
-- Show all tag keys from the cpu measurement
SHOW TAG KEYS FROM "cpu"
-- Show all tag keys from the cpu measurement where the region key = 'uswest'
SHOW TAG KEYS FROM "cpu" WHERE "region" = 'uswest'
-- Show all tag keys where the host key = 'serverA'
SHOW TAG KEYS WHERE "host" = 'serverA'
```
## SHOW TAG VALUES
Use the `SHOW TAG VALUES` statement to list values of specified tags in a database.
```sql
SHOW TAG VALUES [from_clause] WITH KEY = <tag-expression> [where_clause] [limit_clause] [offset_clause]
```
By default, the `SHOW TAG VALUES` statement only returns unique tag values from
**the last day**. To modify the time range, include a
[`WHERE` clause with a time-based predicate](/influxdb/cloud-serverless/reference/influxql/where/#time-ranges).
{{% note %}}
#### Include a FROM clause
We strongly recommend including a `FROM` clause with the `SHOW TAG VALUES`
statement that specifies 1-50 tables to query.
Without a `FROM` clause, the InfluxDB query engine must read data from all
tables and return unique tag values from each.
Depending on the number of tables in your database and the number of unique tag
values in each table, excluding a `FROM` clause can result in poor query performance,
query timeouts, or unnecessary resource allocation that may affect other queries.
{{% /note %}}
#### Examples
```sql
-- Show tag values from the cpu measurement for the region tag
SHOW TAG VALUES FROM "cpu" WITH KEY = "region"
-- Show tag values from the cpu measurement for the region tag for a custom time range
SHOW TAG VALUES FROM "cpu" WITH KEY = "region" WHERE time > -7d
-- Show tag values from multiple measurements for the region tag
SHOW TAG VALUES FROM "cpu", "memory", "disk" WITH KEY = "region"
-- Show tag values from the cpu measurement for all tag keys that do not include the letter c
SHOW TAG VALUES FROM "cpu" WITH KEY !~ /.*c.*/
-- Show tag values from the cpu measurement for region & host tag keys where service = 'redis'
SHOW TAG VALUES FROM "cpu" WITH KEY IN ("region", "host") WHERE "service" = 'redis'
```

View File

@ -13,234 +13,6 @@ list_code_example: |
```sql
SELECT_clause FROM ( SELECT_statement ) [...]
```
source: /shared/influxql-v3-reference/subqueries.md
---
An InfluxQL subquery is a query nested in the `FROM` clause of an InfluxQL query.
The outer query queries results returned by the inner query (subquery).
- [Syntax](#syntax)
- [Examples](#examples)
- [Notable subquery behaviors](#notable-subquery-behaviors)
{{% note %}}
InfluxQL does not support a `HAVING` clause, however InfluxQL subqueries offer
functionality similar to the [SQL `HAVING` clause](/influxdb/cloud-serverless/reference/sql/having/).
{{% /note %}}
## Syntax
```sql
SELECT_clause FROM ( SELECT_statement ) [...]
```
When using subqueries, InfluxQL **performs the inner query first**, then performs
the outer query.
The outer query requires a [`SELECT` clause](/influxdb/cloud-serverless/reference/influxql/select/#select-clause)
and a [`FROM` clause](/influxdb/cloud-serverless/reference/influxql/select/#from-clause).
The inner query is enclosed in parentheses in the outer query's `FROM` clause.
InfluxQL supports multiple nested subqueries:
```sql
SELECT_clause FROM ( SELECT_clause FROM ( SELECT_statement ) [...] ) [...]
```
## Examples
{{% note %}}
#### Sample data
The examples below use the following sample data sets:
- [Get started home sensor data](/influxdb/cloud-serverless/reference/sample-data/#get-started-home-sensor-data)
- [Random numbers sample data](/influxdb/cloud-serverless/reference/sample-data/#random-numbers-sample-data)
{{% /note %}}
{{< expand-wrapper >}}
{{% expand "Apply an aggregate function to an aggregated result set" %}}
```sql
SELECT
SUM(max)
FROM
(
SELECT
MAX(temp)
FROM
home
GROUP BY
room
)
```
{{% influxql/table-meta %}}
Table: home
{{% /influxql/table-meta %}}
| time | sum |
| :------------------- | ---: |
| 1970-01-01T00:00:00Z | 46.1 |
{{% /expand %}}
{{% expand "Calculate the average difference between two fields" %}}
```sql
SELECT
MEAN(difference)
FROM
(
SELECT
a - b AS difference
FROM
numbers
)
```
{{% influxql/table-meta %}}
Table: numbers
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | -------------------: |
| 1970-01-01T00:00:00Z | -0.03629771779732732 |
{{% /expand %}}
{{% expand "Filter aggregate values based on a threshold" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
co_change
FROM
(
SELECT
SPREAD(co) AS co_change
FROM
home
GROUP BY
room,
time(2h)
)
WHERE
time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
AND co_change >= 4
```
{{% influxql/table-meta %}}
Table: home
{{% /influxql/table-meta %}}
| time | co_chnage |
| :------------------- | --------: |
| 2022-01-01T18:00:00Z | 4 |
| 2022-01-01T18:00:00Z | 5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Perform additional aggregate operations on aggregate values" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT
SUM(co_derivative) AS sum_derivative
FROM
(
SELECT
DERIVATIVE(MEAN(co)) AS co_derivative
FROM
home
GROUP BY
time(12m),
room
)
WHERE
time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
GROUP BY
room
```
{{% /influxdb/custom-timestamps %}}
{{% influxql/table-meta %}}
Table: home
{{% /influxql/table-meta %}}
| time | room | sum_derivative |
| :------------------- | :---------- | -------------: |
| 1970-01-01T00:00:00Z | Kitchen | 5.2 |
| 1970-01-01T00:00:00Z | Living Room | 3.4 |
{{% /expand %}}
{{< /expand-wrapper >}}
## Notable subquery behaviors
- [Apply time bounds to the outer query to improve performance](#apply-time-bounds-to-the-outer-query-to-improve-performance)
- [Cannot use multiple SELECT statements in a subquery](#cannot-use-multiple-select-statements-in-a-subquery)
### Apply time bounds to the outer query to improve performance
To improve the performance of InfluxQL queries that use subqueries and a
specified time range, apply the `WHERE` clause with time-based predicates to the
outer query rather than the inner query.
For example--the following queries return the same results, but **the query with
time-based predicate on the outer query is more performant than the query with
time-based predicate on the inner query**:
{{% influxdb/custom-timestamps %}}
#### Time bounds on the outer query {note="(Recommended)"}
```sql
SELECT
inner_value AS value
FROM
(
SELECT
raw_value as inner_value
)
WHERE
time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
```
#### Time bounds on the inner query
```sql
SELECT
inner_value AS value
FROM
(
SELECT
raw_value as inner_value
WHERE
time >= '2022-07-19T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
)
```
{{% /influxdb/custom-timestamps %}}
### Cannot use multiple SELECT statements in a subquery
InfluxQL does not support multiple
[`SELECT` statements](/influxdb/cloud-serverless/reference/influxql/select/)
per subquery:
```sql
SELECT_clause FROM (SELECT_statement; SELECT_statement) [...]
```
However, InfluxQL does support multiple nested subqueries per outer query:
```sql
SELECT_clause FROM ( SELECT_clause FROM ( SELECT_statement ) [...] ) [...]
------------------ ----------------
Subquery 1 Subquery 2
```

View File

@ -13,362 +13,6 @@ list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] [LIMIT_clause] [OFFSET_clause] [SLIMIT_clause] [SOFFSET_clause] tz('<time_zone>')
```
source: /shared/influxql-v3-reference/time-and-timezone.md
---
InfluxQL is designed for working with time series data and includes features specifically for working with time.
You can review the following ways to work with time and timestamps in your InfluxQL queries:
- [Time syntax](#time-syntax)
- [Add and subtract time values](#add-and-subtract-time-values)
- [Query time range](#query-time-range)
- [Supported operators](#supported-operators)
- [Query examples](#query-examples)
- [Time zone clause](#time-zone-clause)
- [Notable behaviors](#notable-behaviors)
- [Cannot query multiple time ranges](#cannot-query-multiple-time-ranges)
- [Querying future data with a `GROUP BY time()` clause](#querying-future-data-with-a-group-by-time-clause)
- [Cannot use parameters for durations](#cannot-use-parameters-for-durations)
## Time syntax
InfluxQL supports the following timestamp literal syntaxes:
```sql
'2006-01-02T15:04:05.00Z' -- RFC3339 date-time string
'2006-01-02 15:04:05.00' -- RFC3339-like date-time string
1136189045000000000 -- Unix nanosecond epoch time
1136189045s -- Unix epoch time
```
- **RFC3339 date-time string**:
[String literal](/influxdb/cloud-serverless/reference/influxql/#strings) using
the RFC3339 timestamp format, `YYYY-MM-DDTHH:MM:SS.nnnnnnnnnZ`.
- **RFC3339-like date-time string**:
[String literal](/influxdb/cloud-serverless/reference/influxql/#strings) using
the RFC3339-like timestamp format, `YYYY-MM-DD HH:MM:SS.nnnnnnnnn`.
- **Unix nanosecond epoch time**:
[Integer](/influxdb/cloud-serverless/reference/influxql/#integers) that
represents the number of nanoseconds elapsed since the
[Unix epoch](/influxdb/cloud-serverless/reference/glossary/#unix-epoch).
- **Unix epoch time**:
[Duration literal](/influxdb/cloud-serverless/reference/influxql/#durations)
that represents the number of specified time units elapsed since the
[Unix epoch](/influxdb/cloud-serverless/reference/glossary/#unix-epoch).
_[View supported duration units](/influxdb/cloud-serverless/reference/influxql/#durations)_.
##### Supported timestamp values
| | RFC3339 | Unix nanosecond time |
| ----------- | :----------------------------: | -------------------: |
| **Maximum** | 2262-04-11T23:47:16.854775807Z | 9223372036854775807 |
| **Minimum** | 1677-09-21T00:12:43.145224193Z | -9223372036854775807 |
### Add and subtract time values
Timestamp values support addition and subtraction operations with
[duration literals](/influxdb/cloud-serverless/reference/influxql/#durations).
Add (`+`) or subtract (`-`) a duration to or from a timestamp to return an
updated timestamp.
```sql
'2023-01-01T00:00:00Z' + 2h -- Resolves to 2023-01-01T02:00:00Z
'2023-01-01 00:00:00' - 20h -- Resolves to 2022-12-31T04:00:00Z
1672531200000000000 + 1y -- Resolves to 2024-01-01T00:00:00Z
```
{{% note %}}
InfluxQL requires a whitespace between the `+` operators `-` and the duration literal.
{{% /note %}}
## Query time range
To specify the time range of a query, use conditional expressions in the
[`WHERE` clause](/inflxudb/cloud-serverless/reference/influxql/where/) that
compare the value of the `time` column to an absolute timestamp or a relative
timestamp.
- **Absolute time range**: Define query time bounds with timestamp literals
```sql
WHERE time >= '2023-01-01T00:00:00Z' AND time <= '2023-07-01T00:00:00Z'
WHERE time >= '2023-01-01 00:00:00' AND time <= '2023-07-01 00:00:00'
WHERE time >= 1672531200000000000 AND time <= 1688169600000000000
WHERE time >= 1672531200s and time <= 1688169600000ms
```
- **Relative time range**: Define query time bounds with a duration literal
added to or subtracted from timestamp literals.
{{% note %}}
Use `now()` to return the current system time (UTC).
{{% /note %}}
```sql
-- Query data from the last day
WHERE time >= now() - 1d
-- Query data from the previous week
WHERE time >= now() - 1w AND time <= now() - 2w
-- Query data relative to a specific time
WHERE time >= '2023-01-01' - 1w AND time <= '2023-01-01' + 1w
```
### Supported operators
Conditional expressions with time operands support the following comparison operators:
| Operator | Meaning |
|:--------:|:------- |
| `=` | equal to |
| `<>` | not equal to |
| `!=` | not equal to |
| `>` | greater than |
| `>=` | greater than or equal to |
| `<` | less than |
| `<=` | less than or equal to |
{{% note %}}
Currently, InfluxQL supports the `AND` logical operator to define query time bounds,
but does not support using the `OR` logical operator to query multiple time ranges.
{{% /note %}}
## Query examples
The following examples use the
[Get started home sensor sample dataset](/influxdb/cloud-serverless/reference/sample-data/#get-started-home-sensor-data).
{{< expand-wrapper >}}
{{% expand "Specify a time range with RFC3339 date-time strings" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T12:00:00Z'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :------ | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T11:00:00Z | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T12:00:00Z | 0 | 36 | Kitchen | 22.5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Specify a time range with RFC3339-like date-time strings" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01 08:00:00'
AND time <= '2022-01-01 12:00:00'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :------ | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T11:00:00Z | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T12:00:00Z | 0 | 36 | Kitchen | 22.5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Specify a time range with nanosecond epoch timestamps" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= 1641024000000000000
AND time <= 1641038400000000000
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :------ | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T11:00:00Z | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T12:00:00Z | 0 | 36 | Kitchen | 22.5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Specify a time range with second-precision epoch timestamps" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= 1641024000s
AND time <= 1641038400s
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :------ | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T11:00:00Z | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T12:00:00Z | 0 | 36 | Kitchen | 22.5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Specify a time range relative to a timestamp" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT * FROM home WHERE time >= '2022-01-01T20:00:00Z' - 2h
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :---------- | ---: |
| 2022-01-01T18:00:00Z | 18 | 36.9 | Kitchen | 23.3 |
| 2022-01-01T18:00:00Z | 9 | 36.2 | Living Room | 22.8 |
| 2022-01-01T19:00:00Z | 22 | 36.6 | Kitchen | 23.1 |
| 2022-01-01T19:00:00Z | 14 | 36.3 | Living Room | 22.5 |
| 2022-01-01T20:00:00Z | 26 | 36.5 | Kitchen | 22.7 |
| 2022-01-01T20:00:00Z | 17 | 36.4 | Living Room | 22.2 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Specify a time range relative to now" %}}
```sql
SELECT * FROM home WHERE time >= now() - 2h
```
{{% /expand %}}
{{< /expand-wrapper >}}
## Time zone clause
By default, InfluxDB stores and returns timestamps in UTC.
Use the time zone clause and the `tz()` function to apply a time zone offset to
UTC times and return timestamps in the specified time zone including any applicable
seasonal offset such as Daylight Savings Time (DST) or British Summer Time (BST).
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] [LIMIT_clause] [OFFSET_clause] [SLIMIT_clause] [SOFFSET_clause] tz('time_zone')
```
- **time_zone**: Time zone string literal to adjust times to.
Uses time zone names defined in the
[Internet Assigned Numbers Authority time zone database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List).
### Time zone example
{{< expand-wrapper >}}
{{% expand "Return the UTC offset for Chicago's time zone" %}}
{{% influxdb/custom-timestamps %}}
The following example uses the
[Get started home sensor sample dataset](/influxdb/cloud-serverless/reference/sample-data/#get-started-home-sensor-data).
```sql
SELECT *
FROM home
WHERE
room = 'Kitchen'
AND time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T12:00:00Z'
tz('America/Chicago')
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------------ | --: | ---: | :------ | ---: |
| 2022-01-01T02:00:00-06:00 | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T03:00:00-06:00 | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T04:00:00-06:00 | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T05:00:00-06:00 | 0 | 36 | Kitchen | 22.4 |
| 2022-01-01T06:00:00-06:00 | 0 | 36 | Kitchen | 22.5 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## Notable behaviors
- [Cannot query multiple time ranges](#cannot-query-multiple-time-ranges)
- [Querying future data with a `GROUP BY time()` clause](#querying-future-data-with-a-group-by-time-clause)
- [Cannot use parameters for durations](#cannot-use-parameters-for-durations)
### Cannot query multiple time ranges
InfluxDB does not support using `OR` in the `WHERE` clause to query multiple time ranges.
For example, the following query returns no results:
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
(time >= '2022-01-01T08:00:00Z' AND time <= '2022-01-01T10:00:00Z')
OR (time >= '2022-01-01T18:00:00Z' AND time <= '2022-01-01T20:00:00Z')
```
{{% /influxdb/custom-timestamps %}}
### Querying future data with a `GROUP BY time()` clause
Queries that do not specify time bounds in the `WHERE` clause and do not include
a `GROUP BY time()` clause use the [minimum and maximum timestamps](#supported-timestamp-values)
as the default time range.
If the query includes a `GROUP BY time()` clause, the default time range is
between `1677-09-21T00:12:43.145224193Z` and
[`now()`](/influxdb/cloud-serverless/reference/influxql/functions/date-time/#now).
To query data with timestamps that occur in the future (after `now()`),
provide an explicit upper bound in the `WHERE` clause.
### Cannot use parameters for durations
Currently, InfluxDB doesn't support using parameters for durations in
[parameterized queries](/influxdb/cloud-serverless/query-data/parameterized-queries/).

View File

@ -12,359 +12,6 @@ list_code_example: |
```sql
SELECT_clause FROM_clause WHERE <conditional_expression> [(AND|OR) <conditional_expression> [...]]
```
source: /shared/influxql-v3-reference/where.md
---
Use the `WHERE` clause to filter data based on
[field values](/influxdb/cloud-serverless/reference/glossary/#field),
[tag values](/influxdb/cloud-serverless/reference/glossary/#tag), and
[timestamps](/influxdb/cloud-serverless/reference/glossary/#timestamp).
- [Syntax](#syntax)
- [Operators](#comparison-operators)
- [Comparison operators](#comparison-operators)
- [Logical operators](#logical-operators)
- [Time ranges](#time-ranges)
- [Regular expressions](#regular-expressions)
- [WHERE clause examples](#where-clause-examples)
- [Notable behaviors](#notable-behaviors)
- [Single and double quotes](#single-and-double-quotes)
- [Cannot query multiple time ranges](#cannot-query-multiple-time-ranges)
## Syntax
```sql
SELECT_clause FROM_clause WHERE <conditional_expression> [(AND|OR) <conditional_expression> [...]]
```
- **conditional_expression**: Comparison between two operands that evaluates to
`true` or `false`. Comparison logic is determined by
[operators](#operators) used in the expression.
These expressions can operate on InfluxDB fields, tags, and timestamps.
Use logical operators (`AND`, `OR`) to chain multiple conditional expressions
together.
## Operators
Operators evaluate the relationship between two operands and return
`true` or `false`.
### Comparison operators
| Operator | Meaning | Supported data types |
| :------: | :--------------------------------- | :---------------------- |
| `=` | Equal to | all |
| `<>` | Not equal to | all |
| `!=` | Not equal to | all |
| `>` | Greater than | numeric, timestamp |
| `>=` | Greater than or equal to | numeric, timestamp |
| `<` | Less than | numeric, timestamp |
| `<=` | Less than or equal to | numeric, timestamp |
| `=~` | Matches a regular expression | strings |
| `!~` | Doesn't match a regular expression | strings |
### Logical operators
| Operator | Meaning |
| :------- | :---------------------------------------------------------------------- |
| `AND` | Returns `true` if both operands are `true`. Otherwise, returns `false`. |
| `OR` | Returns `true` if any operand is `true`. Otherwise, returns `false`. |
## Time ranges
Use the `WHERE` clause to specify a time range to query.
If a time range isn't specified in the `WHERE` clause, the [default time range](/influxdb/cloud-serverless/reference/influxql/#default-time-range) is used.
Timestamps are stored in the `time` column.
Use comparison operators to compare the value of the `time` column to a
timestamp literal, integer (Unix nanosecond timestamp), or [expression](/influxdb/cloud-serverless/reference/glossary/#expression).
{{< code-tabs-wrapper >}}
{{% code-tabs %}}
[Timestamp](#)
[Integer](#)
[Expression](#)
{{% /code-tabs %}}
{{% code-tab-content %}}
```sql
WHERE
time >= '2023-01-01T00:00:00Z'
AND time < '2023-07-01T00:00:00Z'
```
{{% /code-tab-content %}}
{{% code-tab-content %}}
```sql
WHERE
time >= 1672531200000000000
AND time < 1688169600000000000
```
{{% /code-tab-content %}}
{{% code-tab-content %}}
```sql
WHERE
time >= now() - 1d
AND time < now()
```
{{% /code-tab-content %}}
{{< /code-tabs-wrapper >}}
See [Time syntax](/influxdb/cloud-serverless/reference/influxql/time-and-timezone/#time-syntax)
for information on how to specify alternative time ranges in the `WHERE` clause.
{{% note %}}
InfluxQL [does not support querying multiple time ranges](#cannot-query-multiple-time-ranges).
{{% /note %}}
## Regular expressions
Regular expressions can be used to evaluate _string_ values in the `WHERE` clause
using regular expression comparison operators:
- `=~`: Matches a regular expression
- `!~`: Doesn't match a regular expression
```sql
SELECT * FROM home WHERE room =~ /^K/
```
For more information about InfluxQL regular expression syntax, see
[InfluxQL regular expressions](/influxdb/cloud-serverless/reference/influxql/regular-expressions/).
## WHERE clause examples
The following examples use the
[Get started home sensor sample dataset](/influxdb/cloud-serverless/reference/sample-data/#get-started-home-sensor-data).
{{< expand-wrapper >}}
{{% expand "Select data with a specific tag value" %}}
```sql
SELECT * FROM home WHERE room = 'Living Room'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :---------- | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Living Room | 21.1 |
| 2022-01-01T09:00:00Z | 0 | 35.9 | Living Room | 21.4 |
| 2022-01-01T10:00:00Z | 0 | 36 | Living Room | 21.8 |
| 2022-01-01T11:00:00Z | 0 | 36 | Living Room | 22.2 |
| 2022-01-01T12:00:00Z | 0 | 35.9 | Living Room | 22.2 |
| ... | ... | ... | ... | ... |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select data from a specific time range" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T10:00:00Z'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :---------- | ---: |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Kitchen | 21 |
| 2022-01-01T08:00:00Z | 0 | 35.9 | Living Room | 21.1 |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T09:00:00Z | 0 | 35.9 | Living Room | 21.4 |
| 2022-01-01T10:00:00Z | 0 | 36.1 | Kitchen | 22.7 |
| 2022-01-01T10:00:00Z | 0 | 36 | Living Room | 21.8 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select data from a relative time range" %}}
{{% influxdb/custom-timestamps %}}
```sql
SELECT * FROM home WHERE time >= '2022-01-01T20:00:00Z' - 2h
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :---------- | ---: |
| 2022-01-01T18:00:00Z | 18 | 36.9 | Kitchen | 23.3 |
| 2022-01-01T18:00:00Z | 9 | 36.2 | Living Room | 22.8 |
| 2022-01-01T19:00:00Z | 22 | 36.6 | Kitchen | 23.1 |
| 2022-01-01T19:00:00Z | 14 | 36.3 | Living Room | 22.5 |
| 2022-01-01T20:00:00Z | 26 | 36.5 | Kitchen | 22.7 |
| 2022-01-01T20:00:00Z | 17 | 36.4 | Living Room | 22.2 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select field values above a threshold" %}}
```sql
SELECT co FROM home WHERE co > 9
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co |
| :------------------- | --: |
| 2022-01-01T18:00:00Z | 18 |
| 2022-01-01T19:00:00Z | 14 |
| 2022-01-01T19:00:00Z | 22 |
| 2022-01-01T20:00:00Z | 17 |
| 2022-01-01T20:00:00Z | 26 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select specific field values" %}}
```sql
SELECT room, co FROM home WHERE co = 9
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | room | co |
| :------------------- | :---------- | --: |
| 2022-01-01T17:00:00Z | Kitchen | 9 |
| 2022-01-01T18:00:00Z | Living Room | 9 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select field values based on arithmetic" %}}
```sql
SELECT room, co FROM home WHERE co - 10 > 5
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | room | co |
| :------------------- | :---------- | --: |
| 2022-01-01T18:00:00Z | Kitchen | 18 |
| 2022-01-01T19:00:00Z | Kitchen | 22 |
| 2022-01-01T20:00:00Z | Living Room | 17 |
| 2022-01-01T20:00:00Z | Kitchen | 26 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select data with field values above a threshold and a specific tag value" %}}
```sql
SELECT * FROM home WHERE temp > 22.7 AND room = 'Kitchen'
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | hum | room | temp |
| :------------------- | --: | ---: | :------ | ---: |
| 2022-01-01T09:00:00Z | 0 | 36.2 | Kitchen | 23 |
| 2022-01-01T13:00:00Z | 1 | 36.5 | Kitchen | 22.8 |
| 2022-01-01T14:00:00Z | 1 | 36.3 | Kitchen | 22.8 |
| 2022-01-01T18:00:00Z | 18 | 36.9 | Kitchen | 23.3 |
| 2022-01-01T19:00:00Z | 22 | 36.6 | Kitchen | 23.1 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{% expand "Select data based on the relationship between columns" %}}
```sql
SELECT co, temp FROM home WHERE co > temp
```
{{% influxql/table-meta %}}
name: home
{{% /influxql/table-meta %}}
{{% influxdb/custom-timestamps %}}
| time | co | temp |
| :------------------- | --: | ---: |
| 2022-01-01T20:00:00Z | 26 | 22.7 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## Notable behaviors
- [Single and double quotes](#single-and-double-quotes)
- [Cannot query multiple time ranges](#cannot-query-multiple-time-ranges)
### Single and double quotes
In InfluxQL, single quotation marks (`'`) and double quotation marks (`"`) work
differently and can alter the way a `WHERE` clause functions.
Single quotes are used in [string](/influxdb/cloud-serverless/reference/influxql/#strings)
and [timestamp](/influxdb/cloud-serverless/reference/influxql/#dates--times) literals.
Double quotes are used to quote [identifiers](/influxdb/cloud-serverless/reference/influxql/#identifiers),
(time, field, and tag column names).
For example, the following conditional expression compares the value of the
`location` _column_ to the _literal string_, `London`:
```sql
"location" = 'London'
```
The following conditional expression compares the value of the `location` _column_
to the value of the `London` _column_:
```sql
"location" = "London"
```
Misused double and single quotes in the `WHERE` clause often results in unexpected
empty query results.
For more information about quotation marks, see
[InfluxQL quotation](/influxdb/cloud-serverless/reference/influxql/quoting/).
### Cannot query multiple time ranges
InfluxDB does not support using `OR` in the `WHERE` clause to query multiple time ranges.
For example, the following query returns no results:
{{% influxdb/custom-timestamps %}}
```sql
SELECT *
FROM home
WHERE
(time >= '2022-01-01T08:00:00Z' AND time <= '2022-01-01T10:00:00Z')
OR (time >= '2022-01-01T18:00:00Z' AND time <= '2022-01-01T20:00:00Z')
```
{{% /influxdb/custom-timestamps %}}

View File

@ -9,689 +9,10 @@ menu:
weight: 101
related:
- /influxdb/cloud-serverless/reference/internals/arrow-flightsql/
source: /content/shared/sql-reference/_index.md
---
{{% product-name %}} uses the [Apache Arrow DataFusion](https://arrow.apache.org/datafusion/) implementation of SQL.
- [Identifiers](#identifiers)
- [Quoting and case sensitivity](#quoting-and-case-sensitivity)
- [Literals](#literals)
- [Duration units](#duration-units)
- [Operators](#operators)
- [Keywords](#keywords)
- [Conditional expressions](#conditional-expressions)
- [Statements and clauses](#statements-and-clauses)
- [Comments](#comments)
- [Functions](#functions)
## Identifiers
An identifier is a token which refers to the name of an InfluxDB database object, such as a **measurement** or a column name (**time**, **tag keys**, or **field keys**).
## Quoting
Use double quotes on [identifiers](#identifiers) to treat them as case-sensitive.
Use single quotes on string literals.
General quoting guidelines:
- Single quote RFC3339 and RFC3339-like time values.
- Do _not_ quote Unix epoch time values (integers cast to a timestamp).
- Double-quote mixed case, [camel case](https://en.wikipedia.org/wiki/Camel_case) or case-sensitive identifiers.
- Double-quote identifiers that contain special characters or whitespace characters.
##### Quoting examples
```sql
-- Double-quote identifiers that contain whitespace
SELECT "water temperature", "buoy location" FROM buoy
-- Double-quote measurement names with special characters
SELECT * FROM "h2o-temperature"
-- Double-quote identifiers that should be treated as case-sensitive
SELECT "pH" FROM "Water"
```
{{% note %}}
**Note:** We recommend always double-quoting identifiers, regardless of case-sensitivity.
{{% /note %}}
Unquoted identifiers **are not** case-sensitive and match any measurement, tag key, or field key with the same characters, despite case.
For example, if you have two fields in a measurement named `ph` and `pH`, the unquoted identifier, `pH` will match both.
To query in a case-sensitive manner, double-quote identifiers.
## Literals
A literal is an explicit value not represented by an identifier.
### String literals
String literals are surrounded by single quotes.
```sql
'santa_monica'
'pH'
'average temperature'
```
### Numeric literals
Number literals are positive or negative numbers that are either exact numbers or floats.
```sql
-- Integers
10
+10
-10
-- Unsigned integers
10::BIGINT UNSIGNED
+10::BIGINT UNSIGNED
-- Floats
10.78654
-100.56
```
### Date and time literals
The following date and time literals are supported:
```sql
'2022-01-31T06:30:30.123Z' -- (RFC3339)
'2022-01-31T06:30:30.123' -- (RFC3339-like)
'2022-01-31 06:30:30.123' -- (RFC3339-like)
'2022-01-31 06:30:30' -- ((RFC3339-like, no fractional seconds)
1643610630123000000::TIMESTAMP -- (Unix epoch nanosecond cast to a timestamp)
```
### Boolean literals
Boolean literals are either `TRUE` or `FALSE`.
## Duration units
Interval literals specify a length or unit of time.
```sql
INTERVAL '4 minutes'
INTERVAL '12 days 6 hours 30 minutes'
```
The following units of time are supported:
- nanoseconds
- microseconds
- milliseconds
- seconds
- minutes
- hours
- days
- weeks
- months
- years
- century
## Operators
Operators are reserved words or characters which perform certain operations, including comparisons and arithmetic.
### Arithmetic operators
Arithmetic operators take two numeric values (either literals or variables) and
perform a calculation that returns a single numeric value.
| Operator | Description | Example | Result |
| :------: | :------------- | ------- | -----: |
| `+` | Addition | `2 + 2` | `4` |
| `-` | Subtraction | `4 - 2` | `2` |
| `*` | Multiplication | `2 * 3` | `6` |
| `/` | Division | `6 / 3` | `2` |
| `%` | Modulo | `7 % 2` | `1` |
### Comparison operators
Comparison operators evaluate the relationship between the left and right operands and `TRUE` or `FALSE`.
| Operator | Meaning | Example |
| :------: | :------------------------------------------------------- | :----------------- |
| `=` | Equal to | `123 = 123` |
| `<>` | Not equal to | `123 <> 456` |
| `!=` | Not equal to | `123 != 456` |
| `>` | Greater than | `3 > 2` |
| `>=` | Greater than or equal to | `3 >= 2` |
| `<` | Less than | `1 < 2` |
| `<=` | Less than or equal to | `1 <= 2` |
| `~` | Matches a regular expression | `'abc' ~ 'a.*'` |
| `~\*` | Matches a regular expression _(case-insensitive)_ | `'Abc' ~\* 'A.*'` |
| `!~` | Does not match a regular expression | `'abc' !~ 'd.*'` |
| `!~\*` | Does not match a regular expression _(case-insensitive)_ | `'Abc' !~\* 'a.*'` |
### Logical operators
| Operator | Meaning |
| :-------: | :------------------------------------------------------------------------- |
| `AND` | Returns true if both operands are true. Otherwise, returns false. |
| `BETWEEN` | Returns true if the left operand is within the range of the right operand. |
| `EXISTS` | Returns true if the operand is not null. |
| `IN` | Returns true if the left operand is in the right operand list. |
| `LIKE` | Returns true if the left operand matches the right operand pattern string. |
| `NOT` | Negates the subsequent expression. |
| `OR` | Returns true if any operand is true. Otherwise, returns false. |
### Bitwise operators
Bitwise operators perform bitwise operations on bit patterns or binary numerals.
| Operator | Meaning | Example | Result |
| :------: | :------------------ | :------- | -----: |
| `&` | Bitwise and | `5 & 3` | `1` |
| `\|` | Bitwise or | `5 \| 3` | `7` |
| `^` | Bitwise xor | `5 ^ 3` | `6` |
| `>>` | Bitwise shift right | `5 >> 3` | `0` |
| `<<` | Bitwise shift left | `5 << 3` | `40` |
### Other operators
| Operator | Meaning | Example | Result |
| :------------: | :----------------------- | :--------------------------------------------------------------------------------------- | :------------ |
| `\|\|` | Concatenates strings | `'Hello' \|\| ' world'` | `Hello world` |
| `AT TIME ZONE` | Apply a time zone offset | _[View example](/influxdb/cloud-serverless/reference/sql/operators/other/#at-time-zone)_ | |
## Keywords
The following reserved keywords cannot be used as identifiers.
```sql
AND
ALL
ANALYZE
AS
ASC
AT TIME ZONE
BETWEEN
BOTTOM
CASE
DESC
DISTINCT
EXISTS
EXPLAIN
FROM
GROUP BY
HAVING
IN
INNER JOIN
JOIN
LEFT JOIN
LIKE
LIMIT
NOT
EXISTS
NOT IN
OR
ORDER BY
FULL OUTER JOIN
RIGHT JOIN
SELECT
TOP
TYPE
UNION
UNION ALL
WHERE
WITH
```
## Conditional expressions
Conditional expressions evaluate conditions based on input values.
The following conditional expressions are supported:
| Expression | Description |
| :--------- | :----------------------------------------------------------------- |
| CASE | Allows for use of WHEN-THEN-ELSE statements. |
| COALESCE | Returns the first non-NULL expression in a specified list. |
| NULLIF | Returns a NULL value if value1 = value2. Otherwise returns value1. |
## Statements and clauses
InfluxDB SQL supports the following basic syntax for queries:
```sql
[ WITH with_query [, …] ]
SELECT [ ALL | DISTINCT ] select_expr [, …]
[ FROM from_item [, …] ]
[ JOIN join_item [, …] ]
[ WHERE condition ]
[ GROUP BY grouping_element [, …] ]
[ HAVING condition]
[ UNION [ ALL ] ]
[ ORDER BY expression [ ASC | DESC ][, …] ]
[ LIMIT count ]
```
### SELECT statement and FROM clause
Use the SQL `SELECT` statement to query data from a specific measurement or measurements. The `FROM` clause always accompanies the `SELECT` statement.
#### Examples
```sql
SELECT * FROM "h2o_feet"
```
### WHERE clause
Use the `WHERE` clause to filter results based on `fields`, `tags`, and `timestamps`.
Use predicates to evaluate each row.
Rows that evaluate as `TRUE` are returned in the result set.
Rows that evaluate as `FALSE` are omitted from the result set.
#### Examples
```sql
SELECT * FROM "h2o_feet" WHERE "water_level" <= 9
```
```sql
SELECT
*
FROM
"h2o_feet"
WHERE
"location" = 'santa_monica'
AND "level description" = 'below 3 feet'
```
### JOIN clause
Use the `JOIN` clause to join data from multiple measurements (tables).
For more information about joins, see
[JOIN clause](/influxdb/cloud-serverless/reference/sql/join/).
The following join types are supported:
{{< flex >}}
{{< flex-content "quarter" >}}
<a href="#inner-join">
<p style="text-align:center"><strong>INNER JOIN</strong></p>
{{< svg svg="static/svgs/join-diagram.svg" class="inner small center" >}}
</a>
{{< /flex-content >}}
{{< flex-content "quarter" >}}
<a href="#left-outer-join">
<p style="text-align:center"><strong>LEFT [OUTER] JOIN</strong></p>
{{< svg svg="static/svgs/join-diagram.svg" class="left small center" >}}
</a>
{{< /flex-content >}}
{{< flex-content "quarter" >}}
<a href="#right-outer-join">
<p style="text-align:center"><strong>RIGHT [OUTER] JOIN</strong></p>
{{< svg svg="static/svgs/join-diagram.svg" class="right small center" >}}
</a>
{{< /flex-content >}}
{{< flex-content "quarter" >}}
<a href="#full-outer-join">
<p style="text-align:center"><strong>FULL [OUTER] JOIN</strong></p>
{{< svg svg="static/svgs/join-diagram.svg" class="full small center" >}}
</a>
{{< /flex-content >}}
{{< /flex >}}
{{< expand-wrapper >}}
{{% expand "INNER JOIN" %}}
Inner joins combine rows from tables on the left and right side of the join
based on common column values defined in the `ON` clause. Rows that don't have
matching column values are not included in the output table.
```sql
SELECT
*
FROM
home
INNER JOIN home_actions ON
home.room = home_actions.room
AND home.time = home_actions.time;
```
{{% /expand %}}
{{% expand "LEFT [OUTER] JOIN" %}}
A left outer join returns all rows from the left side of the join and only
returns data from the right side of the join in rows with matching column values
defined in the `ON` clause.
```sql
SELECT
*
FROM
home
LEFT OUTER JOIN home_actions ON
home.room = home_actions.room
AND home.time = home_actions.time;
```
{{% /expand %}}
{{% expand "RIGHT [OUTER] JOIN" %}}
A right outer join returns all rows from the right side of the join and only
returns data from the left side of the join in rows with matching column values
defined in the `ON` clause.
```sql
SELECT
*
FROM
home
RIGHT OUTER JOIN home_actions ON
home.room = home_actions.room
AND home.time = home_actions.time;
```
{{% /expand %}}
{{% expand "FULL [OUTER] JOIN" %}}
A full outer join returns all data from the left and right sides of the join and
combines rows with matching column values defined in the `ON` clause.
```sql
SELECT
*
FROM
home
FULL OUTER JOIN home_actions ON
home.room = home_actions.room
AND home.time = home_actions.time;
```
{{% /expand %}}
{{< /expand-wrapper >}}
### GROUP BY clause
Use the `GROUP BY` clause to group query results based on specified column values. `GROUP BY` **requires** an aggregate or selector function in the `SELECT` statement.
#### Examples
```sql
SELECT
MEAN("water_level"),
"location"
FROM
"h2o_feet"
GROUP BY
"location"
```
### HAVING clause
Use the `HAVING` clause to filter query results based on a specified condition.
The `HAVING` clause must _follow_ the `GROUP BY` clause, but _precede_ the `ORDER BY` clause.
#### Examples
```sql
SELECT
MEAN("water_level"),
"location"
FROM
"h2o_feet"
GROUP BY
"location"
HAVING
MEAN("water_level") > 4
ORDER BY
"location"
```
### UNION clause
The `UNION` clause combines the results of two or more `SELECT` statements without returning any duplicate rows. `UNION ALL` returns all results, including duplicates.
#### Examples
```sql
SELECT
'pH'
FROM
"h2o_pH"
UNION ALL
SELECT
"location"
FROM
"h2o_quality"
```
### ORDER BY clause
The `ORDER BY` clause orders results by specified columns and order.
Sort data based on fields, tags, and timestamps.
The following orders are supported:
- `ASC`: ascending _(default)_
- `DESC`: descending
#### Examples
```sql
SELECT
"water_level",
"location"
FROM
"h2o_feet"
ORDER BY
"location",
"time" DESC
```
### LIMIT clause
The `LIMIT` clause limits the number of rows to return.
The defined limit should be a non-negative integer.
#### Examples
```sql
SELECT
"water_level",
"location"
FROM
"h2o_feet"
LIMIT
10
```
### WITH clause
The `WITH` clause provides a way to write auxiliary statements for use in a larger query.
It can help break down large, complicated queries into simpler forms.
```sql
WITH summary_data as
(SELECT degrees, location, time
FROM average_temperature)
SELECT * FROM summary_data
```
### OVER clause
The `OVER` clause is used with SQL window functions.
A **window function** performs a calculation across a set of table rows that are related in some way to the current row.
While similar to aggregate functions, window functions output results into rows retaining their separate identities.
```sql
SELECT
time,
water_level
FROM
(
SELECT
time,
"water_level",
row_number() OVER (
order by
water_level desc
) as rn
FROM
h2o_feet
)
WHERE
rn <= 3;
```
## Comments
Use comments to describe and add detail or notes to your queries.
- Single line comments use the double hyphen `--` symbol. Single line comments end with a line break.
- Multi-line comments begin with `/*` and end with ` */`.
```sql
-- Single-line comment
/*
* Multi-line comment
*/
```
## Schema information
{{% product-name %}} supports the following metadata schema queries:
```sql
SHOW tables
SHOW columns FROM <measurement>
```
## Functions
Following is a list of supported functions by type.
### Aggregate functions
An aggregate function performs a calculation or computation on a set of data values in a column and returns a single value.
| Function | Description |
| :------- | :--------------------------------------------------------- |
| COUNT() | Returns returns the number of rows from a field or tag key |
| AVG() | Returns the average value of a column |
| SUM() | Returns the summed value of a column |
| MEAN() | Returns the mean value of a column |
| MIN() | Returns the smallest value of the selected column |
| MAX() | Returns the largest value of the selected column |
#### Examples
```sql
SELECT COUNT("water_level")
FROM "h2o_feet"
SELECT AVG("water_level"), "location"
FROM "h2o_feet"
GROUP BY "location"
SELECT SUM("water_level"), "location"
FROM "h2o_feet"
GROUP BY "location"
```
### Selector functions
Selector functions are unique to InfluxDB. They behave like aggregate functions in that they take a row of data and compute it down to a single value. However, selectors are unique in that they return a **time value** in addition to the computed value. In short, selectors return an aggregated value along with a timestamp.
| Function | Description |
| :--------------- | :-------------------------------------------------------------- |
| SELECTOR_FIRST() | Returns the first value of a selected column and timestamp. |
| SELECTOR_LAST() | Returns the last value of a selected column and timestamp. |
| SELECTOR_MIN() | Returns the smallest value of a selected column and timestamp. |
| SELECTOR_MAX() | Returns the largest value of a selected column and timestamp. |
#### Examples
```sql
SELECT
SELECTOR_MAX("pH", time)['value'],
SELECTOR_MAX("pH", time)['time']
FROM "h2o_pH"
SELECT
SELECTOR_LAST("water_level", time)['value'],
SELECTOR_LAST("water_level", time)['time']
FROM "h2o_feet"
WHERE time >= timestamp '2019-09-10T00:00:00Z' AND time <= timestamp '2019-09-19T00:00:00Z'
```
### Date and time functions
| Function | Description |
| :----------- | :---------------------------------------------------------------------------------------------- |
| DATE_BIN() | Bins the input timestamp into a specified interval. |
| DATE_TRUNC() | Truncates a timestamp expression based on the date part specified, such as hour, day, or month. |
| DATE_PART() | Returns the specified part of a date. |
| NOW() | Returns the current time (UTC). |
#### Examples
```sql
SELECT DATE_BIN(INTERVAL '1 hour', time, '2019-09-18T00:00:00Z') AS "_time",
SUM(water_level)
FROM "h2o_feet"
GROUP BY "_time"
```
```sql
SELECT DATE_TRUNC('month',time) AS "date",
SUM(water_level)
FROM "h2o_feet"
GROUP BY time
```
### Approximate functions
| Function | Description |
| :--------------------------------- | :-------------------------------------------------------------------------------------------- |
| APPROX_MEDIAN | Returns the approximate median of input values. |
| APPROX_DISTINCT | Returns the approximate count of the number of distinct values. Implemented only for strings. |
| APPROX_PERCENTILE_CONT | Returns the approximate percentile of input values. |
| APPROX_PERCENTILE_CONT_WITH_WEIGHT | Returns the approximate percentile of input values with weight. |
### Math functions
| Function | Description |
| :------- | :------------------------------------------------------------------------------- |
| ABS() | Absolute value |
| ACOS() | Inverse cosine |
| ASIN() | Inverse sine |
| ATAN() | Inverse tangent |
| ATAN2() | Inverse tangent of y / x |
| CEIL() | Returns the smallest integer value greater than or equal to the specified number |
| COS() | Cosine |
| EXP() | Exponential |
| FLOOR() | Nearest integer less than or equal to the specified number |
| LN() | Natural logarithm |
| LOG10() | Base 10 logarithm |
| LOG2() | Base 2 logarithm |
| POWER() | Returns the value of a number raised to the power of the number |
| ROUND() | Round to the nearest integer |
| SIGNUM() | Sign of the argument (-1, 0, +1) |
| SINE() | Sine |
| SQRT() | Returns the square root of a number |
| TAN() | Tangent |
| TRUNC() | Truncates a number to the specified number of decimal places |
### Conditional functions
| Function | Description |
| :------- | :--------------------------------------------------------------------------------------------------------- |
| COALESCE | Returns the first argument that is not null. If all arguments are null, then `COALESCE` will return nulls. |
| NULLIF | Returns a null value if value1 equals value2, otherwise returns value1. |
### Regular expression functions
| Function | Description |
| :------------- | :---------------------------------------------------------------------------- |
| REGEXP_MATCH | Matches a regular expression against a string and returns matched substrings. |
| REGEXP_REPLACE | Replaces substrings that match a regular expression by a new substring. |
<!--
The content of this page is at /content/shared/sql-reference/_index.md
-->

View File

@ -11,217 +11,10 @@ menu:
weight: 200
related:
- /influxdb/cloud-serverless/query-data/sql/cast-types/
source: /content/shared/sql-reference/data-types.md
---
{{< product-name >}} uses the [Apache Arrow DataFusion](https://arrow.apache.org/datafusion/)
implementation of SQL.
Data types define the type of values that can be stored in table columns.
In InfluxDB's SQL implementation, a **measurement** is structured as a table,
and **tags**, **fields** and **timestamps** are exposed as columns.
## SQL and Arrow data types
In SQL, each column, expression, and parameter has a data type.
A data type is an attribute that specifies the type of data that the object can hold.
DataFusion uses the [Arrow](https://arrow.apache.org/) type system for query execution.
All SQL types are mapped to [Arrow data types](https://docs.rs/arrow/latest/arrow/datatypes/enum.DataType.html).
Both SQL and Arrow data types play an important role in how data is operated on
during query execution and returned in query results.
{{% note %}}
When performing casting operations, cast to the SQL data type unless you use
[`arrow_cast()`](/influxdb/cloud-serverless/reference/sql/functions/misc/#arrow_cast)
to cast to a specific Arrow type.
Names and identifiers in SQL are _case-insensitive_ by default. For example:
```sql
SELECT
'99'::BIGINT,
'2019-09-18T00:00:00Z'::timestamp
```
{{% /note %}}
- [String types](#string-types)
- [Numeric types](#numeric-types)
- [Integers](#integers)
- [Unsigned integers](#unsigned-integers)
- [Floats](#floats)
- [Date and time data types](#date-and-time-data-types)
- [Timestamp](#timestamp)
- [Interval](#interval)
- [Boolean types](#boolean-types)
- [Unsupported SQL types](#unsupported-sql-types)
- [Data types compatible with parameters](#data-types-compatible-with-parameters)
## String types
| SQL data type | Arrow data type | Description |
| :------------ | :-------------- | --------------------------------- |
| STRING | UTF8 | Character string, variable-length |
| CHAR | UTF8 | Character string, fixed-length |
| VARCHAR | UTF8 | Character string, variable-length |
| TEXT | UTF8 | Variable unlimited length |
##### Example string literals
```sql
'abcdefghijk'
'time'
'h2o_temperature'
```
## Numeric types
The following numeric types are supported:
| SQL data type | Arrow data type | Description |
| :-------------- | :-------------- | :--------------------------- |
| BIGINT | INT64 | 64-bit signed integer |
| BIGINT UNSIGNED | UINT64 | 64-bit unsigned integer |
| DOUBLE | FLOAT64 | 64-bit floating-point number |
### Integers
InfluxDB SQL supports the 64-bit signed integers:
**Minimum signed integer**: `-9223372036854775808`
**Maximum signed integer**: `9223372036854775807`
##### Example integer literals
```sql
234
-446
5
```
### Unsigned integers
InfluxDB SQL supports the 64-bit unsigned integers:
**Minimum unsigned integer**: `0`
**Maximum unsigned integer**: `18446744073709551615`
##### Example unsigned integer literals
Unsigned integer literals are comprised of an integer cast to the `BIGINT UNSIGNED` type:
```sql
234::BIGINT UNSIGNED
458374893::BIGINT UNSIGNED
5::BIGINT UNSIGNED
```
### Floats
InfluxDB SQL supports the 64-bit double floating point values.
Floats can be a decimal point, decimal integer, or decimal fraction.
##### Example float literals
```sql
23.8
-446.89
5.00
0.033
```
## Date and time data types
InfluxDB SQL supports the following DATE/TIME data types:
| SQL data type | Arrow data type | Description |
| :------------ | :--------------------------------- | :-------------------------------------------- |
| TIMESTAMP | Timestamp(Nanosecond, None) | Nanosecond timestamp with no time zone offset |
| INTERVAL | Interval(IntervalMonthDayNano) | Interval of time with a specified duration |
### Timestamp
A time type is a single point in time using nanosecond precision.
The following date and time formats are supported:
```sql
YYYY-MM-DDT00:00:00.000Z
YYYY-MM-DDT00:00:00.000-00:00
YYYY-MM-DD 00:00:00.000-00:00
YYYY-MM-DDT00:00:00Z
YYYY-MM-DD 00:00:00.000
YYYY-MM-DD 00:00:00
```
##### Example timestamp literals
```sql
'2023-01-02T03:04:06.000Z'
'2023-01-02T03:04:06.000-00:00'
'2023-01-02 03:04:06.000-00:00'
'2023-01-02T03:04:06Z'
'2023-01-02 03:04:06.000'
'2023-01-02 03:04:06'
```
### Interval
The INTERVAL data type can be used with the following precision:
- nanosecond
- microsecond
- millisecond
- second
- minute
- hour
- day
- week
- month
- year
- century
##### Example interval literals
```sql
INTERVAL '10 minutes'
INTERVAL '1 year'
INTERVAL '2 days 1 hour 31 minutes'
```
## Boolean types
Booleans store TRUE or FALSE values.
| SQL data type | Arrow data type | Description |
| :------------ | :-------------- | :------------------- |
| BOOLEAN | Boolean | True or false values |
##### Example boolean literals
```sql
true
TRUE
false
FALSE
```
## Unsupported SQL types
The following SQL types are not currently supported:
- UUID
- BLOB
- CLOB
- BINARY
- VARBINARY
- REGCLASS
- NVARCHAR
- CUSTOM
- ARRAY
- ENUM
- SET
- DATETIME
- BYTEA
## Data types compatible with parameters
For information about data types that can be substituted by parameters,
see how to [use parameterized queries with SQL](/influxdb/cloud-serverless/query-data/sql/parameterized-queries/).
<!--
The content of this page is at /content/shared/sql-reference/data-types.md
-->

View File

@ -11,113 +11,10 @@ related:
- /influxdb/cloud-serverless/reference/internals/query-plan/
- /influxdb/cloud-serverless/query-data/execute-queries/analyze-query-plan/
- /influxdb/cloud-serverless/query-data/execute-queries/troubleshoot/
source: /content/shared/sql-reference/explain.md
---
The `EXPLAIN` command returns the [logical plan](/influxdb/cloud-serverless/reference/internals/query-plan/#logical-plan) and the [physical plan](/influxdb/cloud-serverless/reference/internals/query-plan/#physical-plan) for the
specified SQL statement.
```sql
EXPLAIN [ANALYZE] [VERBOSE] statement
```
- [`EXPLAIN`](#explain)
- [Example `EXPLAIN`](#example-explain)
- [`EXPLAIN ANALYZE`](#explain-analyze)
- [Example `EXPLAIN ANALYZE`](#example-explain-analyze)
- [`EXPLAIN ANALYZE VERBOSE`](#explain-analyze-verbose)
- [Example `EXPLAIN ANALYZE VERBOSE`](#example-explain-analyze-verbose)
## `EXPLAIN`
Returns the logical plan and physical (execution) plan of a statement.
To output more details, use `EXPLAIN VERBOSE`.
`EXPLAIN` doesn't execute the statement.
To execute the statement and view runtime metrics, use [`EXPLAIN ANALYZE`](#explain-analyze).
### Example `EXPLAIN`
```sql
EXPLAIN
SELECT
room,
avg(temp) AS temp
FROM home
GROUP BY room
```
{{< expand-wrapper >}}
{{% expand "View `EXPLAIN` example output" %}}
| | plan_type | plan |
|---:|:--------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 0 | logical_plan |<span style="white-space:pre-wrap;"> Projection: home.room, AVG(home.temp) AS temp </span>|
| | |<span style="white-space:pre-wrap;"> Aggregate: groupBy=[[home.room]], aggr=[[AVG(home.temp)]] </span>|
| | |<span style="white-space:pre-wrap;"> TableScan: home projection=[room, temp] </span>|
| 1 | physical_plan |<span style="white-space:pre-wrap;"> ProjectionExec: expr=[room@0 as room, AVG(home.temp)@1 as temp] </span>|
| | |<span style="white-space:pre-wrap;"> AggregateExec: mode=FinalPartitioned, gby=[room@0 as room], aggr=[AVG(home.temp)] </span>|
| | |<span style="white-space:pre-wrap;"> CoalesceBatchesExec: target_batch_size=8192 </span>|
| | |<span style="white-space:pre-wrap;"> RepartitionExec: partitioning=Hash([room@0], 8), input_partitions=8 </span>|
| | |<span style="white-space:pre-wrap;"> AggregateExec: mode=Partial, gby=[room@0 as room], aggr=[AVG(home.temp)] </span>|
| | |<span style="white-space:pre-wrap;"> ParquetExec: file_groups={8 groups: [[70434/116281/404d73cea0236530ea94f5470701eb814a8f0565c0e4bef5a2d2e33dfbfc3567/1be334e8-0af8-00da-2615-f67cd4be90f7.parquet, 70434/116281/b7a9e7c57fbfc3bba9427e4b3e35c89e001e2e618b0c7eb9feb4d50a3932f4db/d29370d4-262f-0d32-2459-fe7b099f682f.parquet], [70434/116281/c14418ba28a22a3abb693a1cb326a63b62dc611aec58c9bed438fdafd3bc5882/8b29ae98-761f-0550-2fe4-ee77503658e9.parquet], [70434/116281/fa677477eed622ae8123da1251aa7c351f801e2ee2f0bc28c0fe3002a30b3563/65bb4dc3-04e1-0e02-107a-90cee83c51b0.parquet], [70434/116281/db162bdd30261019960dd70da182e6ebd270284569ecfb5deffea7e65baa0df9/2505e079-67c5-06d9-3ede-89aca542dd18.parquet], [70434/116281/0c025dcccae8691f5fd70b0f131eea4ca6fafb95a02f90a3dc7bb015efd3ab4f/3f3e44c3-b71e-0ca4-3dc7-8b2f75b9ff86.parquet], ...]}, projection=[room, temp] </span>|
{{% /expand %}}
{{< /expand-wrapper >}}
## `EXPLAIN ANALYZE`
Executes a statement and returns the execution plan and runtime metrics of the statement.
The report includes the [logical plan](/influxdb/cloud-serverless/reference/internals/query-plan/#logical-plan) and the [physical plan](/influxdb/cloud-serverless/reference/internals/query-plan/#physical-plan) annotated with execution counters, number of rows produced, and runtime metrics sampled during the query execution.
If the plan requires reading lots of data files, `EXPLAIN` and `EXPLAIN ANALYZE` may truncate the list of files in the report.
To output more information, including intermediate plans and paths for all scanned Parquet files, use [`EXPLAIN ANALYZE VERBOSE`](#explain-analyze-verbose).
### Example `EXPLAIN ANALYZE`
```sql
EXPLAIN ANALYZE
SELECT
room,
avg(temp) AS temp
FROM home
WHERE time >= '2023-01-01' AND time <= '2023-12-31'
GROUP BY room
```
{{< expand-wrapper >}}
{{% expand "View `EXPLAIN ANALYZE` example output" %}}
| | plan_type | plan |
|---:|:------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 0 | Plan with Metrics |<span style="white-space:pre-wrap;"> ProjectionExec: expr=[room@0 as room, AVG(home.temp)@1 as temp], metrics=[output_rows=2, elapsed_compute=4.768µs] </span>|
| | |<span style="white-space:pre-wrap;"> AggregateExec: mode=FinalPartitioned, gby=[room@0 as room], aggr=[AVG(home.temp)], ordering_mode=Sorted, metrics=[output_rows=2, elapsed_compute=140.405µs] </span>|
| | |<span style="white-space:pre-wrap;"> CoalesceBatchesExec: target_batch_size=8192, metrics=[output_rows=2, elapsed_compute=6.821µs] </span>|
| | |<span style="white-space:pre-wrap;"> RepartitionExec: partitioning=Hash([room@0], 8), input_partitions=8, preserve_order=true, sort_exprs=room@0 ASC, metrics=[output_rows=2, elapsed_compute=18.408µs, repart_time=59.698µs, fetch_time=1.057882762s, send_time=5.83µs] </span>|
| | |<span style="white-space:pre-wrap;"> AggregateExec: mode=Partial, gby=[room@0 as room], aggr=[AVG(home.temp)], ordering_mode=Sorted, metrics=[output_rows=2, elapsed_compute=137.577µs] </span>|
| | |<span style="white-space:pre-wrap;"> RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=6, preserve_order=true, sort_exprs=room@0 ASC, metrics=[output_rows=46, elapsed_compute=26.637µs, repart_time=6ns, fetch_time=399.971411ms, send_time=6.658µs] </span>|
| | |<span style="white-space:pre-wrap;"> ProjectionExec: expr=[room@0 as room, temp@2 as temp], metrics=[output_rows=46, elapsed_compute=3.102µs] </span>|
| | |<span style="white-space:pre-wrap;"> CoalesceBatchesExec: target_batch_size=8192, metrics=[output_rows=46, elapsed_compute=25.585µs] </span>|
| | |<span style="white-space:pre-wrap;"> FilterExec: time@1 >= 1672531200000000000 AND time@1 <= 1703980800000000000, metrics=[output_rows=46, elapsed_compute=26.51µs] </span>|
| | |<span style="white-space:pre-wrap;"> ParquetExec: file_groups={6 groups: [[70434/116281/404d73cea0236530ea94f5470701eb814a8f0565c0e4bef5a2d2e33dfbfc3567/1be334e8-0af8-00da-2615-f67cd4be90f7.parquet], [70434/116281/c14418ba28a22a3abb693a1cb326a63b62dc611aec58c9bed438fdafd3bc5882/8b29ae98-761f-0550-2fe4-ee77503658e9.parquet], [70434/116281/fa677477eed622ae8123da1251aa7c351f801e2ee2f0bc28c0fe3002a30b3563/65bb4dc3-04e1-0e02-107a-90cee83c51b0.parquet], [70434/116281/db162bdd30261019960dd70da182e6ebd270284569ecfb5deffea7e65baa0df9/2505e079-67c5-06d9-3ede-89aca542dd18.parquet], [70434/116281/0c025dcccae8691f5fd70b0f131eea4ca6fafb95a02f90a3dc7bb015efd3ab4f/3f3e44c3-b71e-0ca4-3dc7-8b2f75b9ff86.parquet], ...]}, projection=[room, time, temp], output_ordering=[room@0 ASC, time@1 ASC], predicate=time@6 >= 1672531200000000000 AND time@6 <= 1703980800000000000, pruning_predicate=time_max@0 >= 1672531200000000000 AND time_min@1 <= 1703980800000000000, required_guarantees=[], metrics=[output_rows=46, elapsed_compute=6ns, predicate_evaluation_errors=0, bytes_scanned=3279, row_groups_pruned_statistics=0, file_open_errors=0, file_scan_errors=0, pushdown_rows_filtered=0, num_predicate_creation_errors=0, row_groups_pruned_bloom_filter=0, page_index_rows_filtered=0, time_elapsed_opening=398.462968ms, time_elapsed_processing=1.626106ms, time_elapsed_scanning_total=1.36822ms, page_index_eval_time=33.474µs, pushdown_eval_time=14.267µs, time_elapsed_scanning_until_data=1.27694ms] </span>|
{{% /expand %}}
{{< /expand-wrapper >}}
## `EXPLAIN ANALYZE VERBOSE`
Executes a statement and returns the execution plan, runtime metrics, and additional details helpful for debugging the statement.
The report includes the following:
- the [logical plan](/influxdb/cloud-serverless/reference/internals/query-plan/#logical-plan)
- the [physical plan](/influxdb/cloud-serverless/reference/internals/query-plan/#physical-plan) annotated with execution counters, number of rows produced, and runtime metrics sampled during the query execution
- Information truncated in the `EXPLAIN` report--for example, the paths for all [Parquet files retrieved for the query](/influxdb/cloud-serverless/reference/internals/query-plan/#file_groups).
- All intermediate physical plans that DataFusion and the [Querier](/influxdb/cloud-serverless/reference/internals/storage-engine/#querier) generate before generating the final physical plan--helpful in debugging to see when an [`ExecutionPlan` node](/influxdb/cloud-serverless/reference/internals/query-plan/#executionplan-nodes) is added or removed, and how InfluxDB optimizes the query.
### Example `EXPLAIN ANALYZE VERBOSE`
```SQL
EXPLAIN ANALYZE VERBOSE SELECT temp FROM home
WHERE time >= now() - INTERVAL '7 days' AND room = 'Kitchen'
ORDER BY time
```
<!--
The content of this page is at /content/shared/sql-reference/explain.md
-->

View File

@ -9,6 +9,10 @@ menu:
parent: SQL reference
identifier: sql-functions
weight: 220
source: /content/shared/sql-reference/functions/_index.md
---
{{< children >}}
<!--
The content of this page is at /content/shared/sql-reference/functions/_index.md
-->

View File

@ -8,137 +8,10 @@ menu:
name: Conditional
parent: sql-functions
weight: 306
source: /content/shared/sql-reference/functions/conditional.md
---
The InfluxDB SQL implementation supports the following conditional functions for
conditionally handling _null_ values:
- [coalesce](#coalesce)
- [ifnull](#ifnull)
- [nullif](#nullif)
- [nvl](#nvl)
## coalesce
Returns the first of its arguments that is not _null_.
Returns _null_ if all arguments are _null_.
This function is often used to substitute a default value for _null_ values.
```sql
coalesce(expression1[, ..., expression_n])
```
##### Arguments
- **expression1, expression_n**:
Expression to use if previous expressions are _null_.
Can be a constant, column, or function, and any combination of arithmetic operators.
Pass as many expression arguments as necessary.
{{< expand-wrapper >}}
{{% expand "View `coalesce` query example" %}}
```sql
SELECT
val1,
val2,
val3,
coalesce(val1, val2, val3, 'quz') AS coalesce
FROM
(values ('foo', 'bar', 'baz'),
(NULL, 'bar', 'baz'),
(NULL, NULL, 'baz'),
(NULL, NULL, NULL)
) data(val1, val2, val3)
```
| val1 | val2 | val3 | coalesce |
| :--: | :--: | :--: | :------: |
| foo | bar | baz | foo |
| | bar | baz | bar |
| | | baz | baz |
| | | | quz |
{{% /expand %}}
{{< /expand-wrapper >}}
## ifnull
_Alias of [nvl](#nvl)._
## nullif
Returns _null_ if _expression1_ equals _expression2_; otherwise it returns _expression1_.
This can be used to perform the inverse operation of [`coalesce`](#coalesce).
```sql
nullif(expression1, expression2)
```
##### Arguments
- **expression1**: Expression to compare and return if equal to expression2.
Can be a constant, column, or function, and any combination of arithmetic operators.
- **expression2**: Expression to compare to expression1.
Can be a constant, column, or function, and any combination of arithmetic operators.
{{< expand-wrapper >}}
{{% expand "View `nullif` query example" %}}
```sql
SELECT
value,
nullif(value, 'baz') AS nullif
FROM
(values ('foo'),
('bar'),
('baz')
) data(value)
```
| value | nullif |
| :---- | :----- |
| foo | foo |
| bar | bar |
| baz | |
{{% /expand %}}
{{< /expand-wrapper >}}
## nvl
Returns _expression2_ if _expression1_ is _null_; otherwise it returns _expression1_.
```sql
nvl(expression1, expression2)
```
##### Arguments
- **expression1**: Return this expression if not _null_.
Can be a constant, column, or function, and any combination of arithmetic operators.
- **expression2**: Return this expression if _expression1_ is _null_.
Can be a constant, column, or function, and any combination of arithmetic operators.
{{< expand-wrapper >}}
{{% expand "View `nvl` query example" %}}
```sql
SELECT
value,
nvl(value, 'baz') AS nvl
FROM
(values ('foo'),
('bar'),
(NULL)
) data(value)
```
| value | nvl |
| :---- | :-- |
| foo | foo |
| bar | bar |
| | baz |
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
The content of this page is at /content/shared/sql-reference/functions/conditional.md
-->

View File

@ -8,239 +8,10 @@ menu:
name: Miscellaneous
parent: sql-functions
weight: 310
source: /content/shared/sql-reference/functions/misc.md
---
The InfluxDB SQL implementation supports the following miscellaneous functions
for performing a variety of operations:
- [arrow_cast](#arrow_cast)
- [arrow_typeof](#arrow_typeof)
- [interpolate](#interpolate)
- [locf](#locf)
<!-- - [struct](#struct) -->
## arrow_cast
Casts a value to a specific Arrow data type.
```sql
arrow_cast(expression, datatype)
```
#### Arguments
- **expression**: Expression to cast.
Can be a constant, column, or function, and any combination of arithmetic or
string operators.
- **datatype**: [Arrow data type](/influxdb/cloud-serverless/reference/sql/data-types/#sql-and-arrow-data-types)
to cast to.
{{< expand-wrapper >}}
{{% expand "View `arrow_cast` query example" %}}
_The following example uses the sample data set provided in
[Get started with InfluxDB tutorial](/influxdb/cloud-serverless/get-started/write/#construct-line-protocol)._
```sql
SELECT
arrow_cast(time, 'Int64') AS time,
arrow_cast(temp, 'Utf8') AS temp,
arrow_cast(co, 'Float64')AS co
FROM home
LIMIT 1
```
| time | temp | co |
| :------------------ | ---: | --: |
| 1641024000000000000 | 21.0 | 0 |
{{% /expand %}}
{{< /expand-wrapper >}}
## arrow_typeof
Returns the underlying [Arrow data type](https://arrow.apache.org/datafusion/user-guide/sql/data_types.html)
of the expression:
```sql
arrow_typeof(expression)
```
##### Arguments
- **expression**: Expression to evaluate.
Can be a constant, column, or function, and any combination of arithmetic or
string operators.
{{< expand-wrapper >}}
{{% expand "View `arrow_typeof` query example" %}}
_The following example uses the sample data set provided in
[Get started with InfluxDB tutorial](/influxdb/cloud-serverless/get-started/write/#construct-line-protocol)._
```sql
SELECT
arrow_typeof(time) AS time,
arrow_typeof(room) AS room,
arrow_typeof(temp) AS temp,
arrow_typeof(co) AS co
FROM home
LIMIT 1
```
| time | room | temp | co |
| :-------------------------- | :---------------------- | :------ | :---- |
| Timestamp(Nanosecond, None) | Dictionary(Int32, Utf8) | Float64 | Int64 |
{{% /expand %}}
{{< /expand-wrapper >}}
## interpolate
Fills null values in a specified aggregated column by interpolating values
from existing values.
Must be used with [`date_bin_gapfill`](/influxdb/cloud-serverless/reference/sql/functions/time-and-date/#date_bin_gapfill).
```sql
interpolate(aggregate_expression)
```
##### Arguments
- **aggregate_expression**: Aggregate operation on a specified expression.
The operation can use any [aggregate function](/influxdb/cloud-serverless/reference/sql/functions/aggregate/).
The expression can be a constant, column, or function, and any combination of
arithmetic operators supported by the aggregate function.
##### Related functions
[date_bin_gapfill](/influxdb/cloud-serverless/reference/sql/functions/time-and-date/#date_bin_gapfill),
[locf](#locf)
{{< expand-wrapper >}}
{{% expand "View `interpolate` query example" %}}
_The following example uses the sample data set provided in the
[Get started with InfluxDB tutorial](/influxdb/cloud-serverless/get-started/write/#construct-line-protocol)._
{{% influxdb/custom-timestamps %}}
```sql
SELECT
date_bin_gapfill(INTERVAL '30 minutes', time) as _time,
room,
interpolate(avg(temp))
FROM home
WHERE
time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T10:00:00Z'
GROUP BY _time, room
```
| _time | room | AVG(home.temp) |
| :------------------- | :---------- | -------------: |
| 2022-01-01T08:00:00Z | Kitchen | 21 |
| 2022-01-01T08:30:00Z | Kitchen | 22 |
| 2022-01-01T09:00:00Z | Kitchen | 23 |
| 2022-01-01T09:30:00Z | Kitchen | 22.85 |
| 2022-01-01T10:00:00Z | Kitchen | 22.7 |
| 2022-01-01T08:00:00Z | Living Room | 21.1 |
| 2022-01-01T08:30:00Z | Living Room | 21.25 |
| 2022-01-01T09:00:00Z | Living Room | 21.4 |
| 2022-01-01T09:30:00Z | Living Room | 21.6 |
| 2022-01-01T10:00:00Z | Living Room | 21.8 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
## locf
Fills null values in a specified aggregated column by carrying the last observed
value forward.
Must be used with [`date_bin_gapfill`](/influxdb/cloud-serverless/reference/sql/functions/time-and-date/#date_bin_gapfill).
_LOCF is an initialism of "last observation carried forward."_
```sql
locf(aggregate_expression)
```
##### Arguments
- **aggregate_expression**: Aggregate operation on a specified expression.
The operation can use any [aggregate function](/influxdb/cloud-serverless/reference/sql/functions/aggregate/).
The expression can be a constant, column, or function, and any combination of
arithmetic operators supported by the aggregate function.
##### Related functions
[date_bin_gapfill](/influxdb/cloud-serverless/reference/sql/functions/time-and-date/#date_bin_gapfill),
[interpolate](#interpolate)
{{< expand-wrapper >}}
{{% expand "View `locf` query example" %}}
_The following example uses the sample data set provided in the
[Get started with InfluxDB tutorial](/influxdb/cloud-serverless/get-started/write/#construct-line-protocol)._
{{% influxdb/custom-timestamps %}}
```sql
SELECT
date_bin_gapfill(INTERVAL '30 minutes', time) as _time,
room,
locf(avg(temp))
FROM home
WHERE
time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T10:00:00Z'
GROUP BY _time, room
```
| _time | room | AVG(home.temp) |
| :------------------- | :---------- | -------------: |
| 2022-01-01T08:00:00Z | Kitchen | 21 |
| 2022-01-01T08:30:00Z | Kitchen | 21 |
| 2022-01-01T09:00:00Z | Kitchen | 23 |
| 2022-01-01T09:30:00Z | Kitchen | 23 |
| 2022-01-01T10:00:00Z | Kitchen | 22.7 |
| 2022-01-01T08:00:00Z | Living Room | 21.1 |
| 2022-01-01T08:30:00Z | Living Room | 21.1 |
| 2022-01-01T09:00:00Z | Living Room | 21.4 |
| 2022-01-01T09:30:00Z | Living Room | 21.4 |
| 2022-01-01T10:00:00Z | Living Room | 21.8 |
{{% /influxdb/custom-timestamps %}}
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
## struct
Returns an Arrow struct using the specified input expressions.
Fields in the returned struct use the `cN` naming convention.
For example: `c0`, `c1`, `c2`, etc.
```sql
struct(expression1[, ..., expression_n])
```
##### Arguments
- **expression_n**: Expression to include in the output struct.
Can be a constant, column, or function, and any combination of arithmetic or
string operators.
{{< expand-wrapper >}}
{{% expand "View `struct` example" %}}
```sql
struct('A', 'B', 3, 4)
-- Returns {c0: A, c1: B, c3: 3, c4: 4}
```
{{% /expand %}}
{{< /expand-wrapper >}}
-->
<!--
The content of this page is at /content/shared/sql-reference/functions/misc.md
-->

View File

@ -9,145 +9,10 @@ menu:
parent: sql-functions
weight: 308
influxdb/cloud-serverless/tags: [regular expressions, sql]
source: /content/shared/sql-reference/functions/regular-expression.md
---
The InfluxDB SQL implementation uses the
[PCRE-like](https://en.wikibooks.org/wiki/Regular_Expressions/Perl-Compatible_Regular_Expressions)
regular expression [syntax](https://docs.rs/regex/latest/regex/#syntax)
(excluding some features such as look-around and back-references) and supports
the following regular expression functions:
- [regexp_like](#regexp_like)
- [regexp_match](#regexp_match)
- [regexp_replace](#regexp_replace)
## regexp_like
True if a regular expression has at least one match in a string;
false otherwise.
```sql
regexp_like(str, regexp[, flags])
```
##### Arguments
- **str**: String expression to operate on.
Can be a constant, column, or function, and any combination of string operators.
- **regexp**: Regular expression to test against the string expression.
Can be a constant, column, or function.
- **flags**: Optional regular expression flags that control the behavior of the
regular expression. The following flags are supported:
- **i**: (insensitive) Ignore case when matching.
- **m**: (multi-line) `^` and `$` match the beginning and end of a line, respectively.
- **s**: (single-line) `.` matches newline (`\n`).
- **R**: (CRLF) When multi-line mode is enabled, `\r\n` is used to delimit lines.
- **U**: (ungreedy) Swap the meaning of `x*` and `x*?`.
{{< expand-wrapper >}}
{{% expand "View `regexp_like` query example" %}}
_The following example uses the sample data set provided in
[Get started with InfluxDB tutorial](/influxdb/cloud-serverless/get-started/write/#construct-line-protocol)._
```sql
SELECT DISTINCT
room,
regexp_like(room::STRING, 'R', 'i') AS regexp_like
FROM home
```
| room | regexp_like |
| :---------- | :---------- |
| Kitchen | false |
| Living Room | true |
{{% /expand %}}
{{< /expand-wrapper >}}
## regexp_match
Returns a list of regular expression matches in a string.
```sql
regexp_match(str, regexp, flags)
```
##### Arguments
- **str**: String expression to operate on.
Can be a constant, column, or function, and any combination of string operators.
- **regexp**: Regular expression to match against.
Can be a constant, column, or function.
- **flags**: Regular expression flags that control the behavior of the
regular expression. The following flags are supported.
- **i**: (insensitive) Ignore case when matching.
{{< expand-wrapper >}}
{{% expand "View `regexp_match` query example" %}}
_The following example uses the sample data set provided in
[Get started with InfluxDB tutorial](/influxdb/cloud-serverless/get-started/write/#construct-line-protocol)._
{{% note %}}
`regexp_match` returns a _list_ Arrow type, which is not supported by InfluxDB.
Use _bracket notation_ to reference a value in the list.
Lists use 1-based indexing.
{{% /note %}}
```sql
SELECT DISTINCT
room,
regexp_match(room::STRING, '.{3}')[1] AS regexp_match
FROM home
```
| room | regexp_match |
| :---------- | :----------- |
| Kitchen | Kit |
| Living Room | Liv |
{{% /expand %}}
{{< /expand-wrapper >}}
## regexp_replace
Replaces substrings in a string that match a regular expression.
```sql
regexp_replace(str, regexp, replacement, flags)
```
##### Arguments
- **str**: String expression to operate on.
Can be a constant, column, or function, and any combination of string operators.
- **regexp**: Regular expression to match against.
Can be a constant, column, or function.
- **replacement**: Replacement string expression.
Can be a constant, column, or function, and any combination of string operators.
- **flags**: Regular expression flags that control the behavior of the
regular expression. The following flags are supported.
- **g**: (global) Search globally and don't return after the first match.
- **i**: (insensitive) Ignore case when matching.
{{< expand-wrapper >}}
{{% expand "View `regexp_replace` query example" %}}
_The following example uses the sample data set provided in
[Get started with InfluxDB tutorial](/influxdb/cloud-serverless/get-started/write/#construct-line-protocol)._
```sql
SELECT DISTINCT
room,
regexp_replace(room::STRING, '\sRoom', '', 'gi') AS regexp_replace
FROM home
```
| room | regexp_replace |
| :---------- | :------------- |
| Kitchen | Kitchen |
| Living Room | Living |
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
The content of this page is at /content/shared/sql-reference/functions/regular-expression.md
-->

View File

@ -10,191 +10,10 @@ menu:
weight: 302
related:
- /influxdb/cloud-serverless/query-data/sql/aggregate-select/
source: /content/shared/sql-reference/functions/selector.md
---
SQL selector functions are designed to work with time series data.
They behave similarly to aggregate functions in that they take a collection of
data and return a single value.
However, selectors are unique in that they return a _struct_ that contains
a **time value** in addition to the computed value.
- [How do selector functions work?](#how-do-selector-functions-work)
- [Selector functions](#selector-functions)
- [selector_min](#selector_min)
- [selector_max](#selector_max)
- [selector_first](#selector_first)
- [selector_last](#selector_last)
## How do selector functions work?
Each selector function returns an [Arrow _struct_](https://arrow.apache.org/docs/format/Columnar.html#struct-layout)
(similar to a JSON object) representing a single time and value from the
specified column in the each group.
What time and value get returned depend on the logic in the selector function.
For example, `selector_first` returns the value of specified column in the first row of the group.
`selector_max` returns the maximum value of the specified column in the group.
### Selector struct schema
The struct returned from a selector function has two properties:
- **time**: `time` value in the selected row
- **value**: value of the specified column in the selected row
```js
{time: 2023-01-01T00:00:00Z, value: 72.1}
```
### Selector functions in use
In your `SELECT` statement, execute a selector function and use bracket notation
to reference properties of the [returned struct](#selector-struct-schema) to
populate the column value:
```sql
SELECT
selector_first(temp, time)['time'] AS time,
selector_first(temp, time)['value'] AS temp,
room
FROM home
GROUP BY room
```
## Selector functions
- [selector_min](#selector_min)
- [selector_max](#selector_max)
- [selector_first](#selector_first)
- [selector_last](#selector_last)
### selector_min
Returns the smallest value of a selected column and a timestamp.
```sql
selector_min(expression, timestamp)
```
##### Arguments
- **expression**: Expression to operate on.
Can be a constant, column, or function, and any combination of string or
arithmetic operators.
- **timestamp**: Time expression.
Can be a constant, column, or function.
{{< expand-wrapper >}}
{{% expand "View `selector_min` query example" %}}
```sql
SELECT
selector_min(water_level, time)['time'] AS time,
selector_min(water_level, time)['value'] AS water_level
FROM h2o_feet
```
| time | water_level |
| :------------------- | ----------: |
| 2019-08-28T14:30:00Z | -0.61 |
{{% /expand %}}
{{< /expand-wrapper >}}
### selector_max
Returns the largest value of a selected column and a timestamp.
```sql
selector_max(expression, timestamp)
```
##### Arguments
- **expression**: Expression to operate on.
Can be a constant, column, or function, and any combination of string or
arithmetic operators.
- **timestamp**: Time expression.
Can be a constant, column, or function.
{{< expand-wrapper >}}
{{% expand "View `selector_max` query example" %}}
```sql
SELECT
selector_max(water_level, time)['time'] AS time,
selector_max(water_level, time)['value'] AS water_level
FROM h2o_feet
```
| time | water_level |
| :------------------- | ----------: |
| 2019-08-28T07:24:00Z | 9.964 |
{{% /expand %}}
{{< /expand-wrapper >}}
### selector_first
Returns the first value ordered by time ascending.
```sql
selector_first(expression, timestamp)
```
##### Arguments
- **expression**: Expression to operate on.
Can be a constant, column, or function, and any combination of string or
arithmetic operators.
- **timestamp**: Time expression.
Can be a constant, column, or function.
{{< expand-wrapper >}}
{{% expand "View `selector_first` query example" %}}
```sql
SELECT
selector_first(water_level, time)['time'] AS time,
selector_first(water_level, time)['value'] AS water_level
FROM h2o_feet
```
| time | water_level |
| :------------------- | ----------: |
| 2019-08-28T07:24:00Z | 9.964 |
{{% /expand %}}
{{< /expand-wrapper >}}
### selector_last
Returns the last value ordered by time ascending.
```sql
selector_last(expression, timestamp)
```
##### Arguments
- **expression**: Expression to operate on.
Can be a constant, column, or function, and any combination of string or
arithmetic operators.
- **timestamp**: Time expression.
Can be a constant, column, or function.
{{< expand-wrapper >}}
{{% expand "View `selector_last` query example" %}}
```sql
SELECT
selector_last(water_level, time)['time'] AS time,
selector_last(water_level, time)['value'] AS water_level
FROM h2o_feet
```
| time | water_level |
| :------------------- | ----------: |
| 2019-09-17T21:42:00Z | 4.938 |
{{% /expand %}}
{{< /expand-wrapper >}}
<!--
The content of this page is at /content/shared/sql-reference/functions/selector.md
-->

Some files were not shown because too many files have changed in this diff Show More