Cloud Serverless InfluxQL (#4980)

* port influxql reference to serverless

* ported influxql guide content to serverless

* Apply suggestions from code review

Co-authored-by: Jason Stirnaman <stirnamanj@gmail.com>

* update and port sample-data from dedicated to serverless

* Manage tokens in InfluxDB Cloud Serverless (#4984)

* add token management docs to serverless

* updated auth scheme in shared code block

* Apply suggestions from code review

Co-authored-by: Jason Stirnaman <stirnamanj@gmail.com>

* addressed pr feedback, updated serverless auth schema from bearer to token

---------

Co-authored-by: Jason Stirnaman <stirnamanj@gmail.com>

* Add DBRP mapping information to Cloud Serverless (#4982)

* add dbrp mapping to cloud serverless

* added notes about dbrp mappings to serverless influxql docs

* Apply suggestions from code review

Co-authored-by: Jason Stirnaman <stirnamanj@gmail.com>

---------

Co-authored-by: Jason Stirnaman <stirnamanj@gmail.com>

* restructure serverless sql docs

---------

Co-authored-by: Jason Stirnaman <stirnamanj@gmail.com>
pull/4987/head^2
Scott Anderson 2023-06-20 07:52:51 -06:00 committed by GitHub
parent 1302c26ddd
commit 3116379931
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
51 changed files with 14087 additions and 501 deletions

View File

@ -3,13 +3,13 @@ title: Use Python to query data with SQL
description: >
Use Python and the `influxdb3-python` library to query data stored in InfluxDB
with SQL.
weight: 401
weight: 101
menu:
influxdb_cloud_dedicated:
parent: sql-execute-queries
name: Use Python
identifier: query-with-python-sql
influxdb/cloud-dedicated/tags: [query, flightsql, python]
influxdb/cloud-dedicated/tags: [query, flightsql, python, sql]
aliases:
- /influxdb/cloud-dedicated/query-data/execute-queries/flight-sql/python/
related:
@ -224,7 +224,7 @@ from influxdb_client_3 import InfluxDBClient3
# Instantiate an InfluxDBClient3 client configured for your database
client = InfluxDBClient3(
host='b0c7cce5-8dbc-428e-98c6-7f996fb96467.a.influxdb.io',
host='cluster-id.influxdb.io',
token='DATABASE_TOKEN',
database='DATABASE_NAME'
)

View File

@ -112,60 +112,60 @@ storage engine.
### Aggregate functions
| Function | Supported | Tracking Issue |
| :------------------------------------------- | :----------------------: | :-------------------------------------------------------------------------- |
| [COUNT()](functions/aggregates/#count) | **{{< icon "check" >}}** | |
| [DISTINCT()](functions/aggregates/#distinct) | **{{< icon "check" >}}** | |
| <span style="opacity: .5;">INTEGRAL()</span> | | [influxdb_iox#6937](https://github.com/influxdata/influxdb_iox/issues/6937) |
| [MEAN()](functions/aggregates/#mean) | **{{< icon "check" >}}** | |
| [MEDIAN()](functions/aggregates/#median) | **{{< icon "check" >}}** | |
| <span style="opacity: .5;">MODE()</span> | | [influxdb_iox#7334](https://github.com/influxdata/influxdb_iox/issues/7334) |
| <span style="opacity: .5;">SPREAD()</span> | | [influxdb_iox#6937](https://github.com/influxdata/influxdb_iox/issues/6937) |
| [STDDEV()](functions/aggregates/#stddev) | **{{< icon "check" >}}** | |
| [SUM()](functions/aggregates/#sum) | **{{< icon "check" >}}** | |
| Function | Supported | Tracking Issue |
| :---------------------------------------------------------------------------------------- | :----------------------: | :-------------------------------------------------------------------------- |
| [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> | | [influxdb_iox#6937](https://github.com/influxdata/influxdb_iox/issues/6937) |
| [MEAN()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#mean) | **{{< icon "check" >}}** | |
| [MEDIAN()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#median) | **{{< icon "check" >}}** | |
| <span style="opacity: .5;">MODE()</span> | | [influxdb_iox#7334](https://github.com/influxdata/influxdb_iox/issues/7334) |
| <span style="opacity: .5;">SPREAD()</span> | | [influxdb_iox#6937](https://github.com/influxdata/influxdb_iox/issues/6937) |
| [STDDEV()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#stddev) | **{{< icon "check" >}}** | |
| [SUM()](/influxdb/cloud-dedicated/reference/influxql/functions/aggregates/#sum) | **{{< icon "check" >}}** | |
### Selector functions
| Function | Supported | Tracking Issue |
| :--------------------------------------------- | :----------------------: | :-------------------------------------------------------------------------- |
| <span style="opacity: .5;">BOTTOM()</span> | | [influxdb_iox#6935](https://github.com/influxdata/influxdb_iox/issues/6935) |
| [FIRST()](functions/selectors/#first) | **{{< icon "check" >}}** | |
| [LAST()](functions/selectors/#last) | **{{< icon "check" >}}** | |
| [MAX()](functions/selectors/#max) | **{{< icon "check" >}}** | |
| [MIN()](functions/selectors/#min) | **{{< icon "check" >}}** | |
| <span style="opacity: .5;">PERCENTILE()</span> | | [influxdb_iox#7664](https://github.com/influxdata/influxdb_iox/issues/7664) |
| <span style="opacity: .5;">SAMPLE()</span> | | [influxdb_iox#6935](https://github.com/influxdata/influxdb_iox/issues/6935) |
| <span style="opacity: .5;">TOP()</span> | | [influxdb_iox#7650](https://github.com/influxdata/influxdb_iox/issues/7650) |
| Function | Supported | Tracking Issue |
| :--------------------------------------------------------------------------------- | :----------------------: | :-------------------------------------------------------------------------- |
| <span style="opacity: .5;">BOTTOM()</span> | | [influxdb_iox#6935](https://github.com/influxdata/influxdb_iox/issues/6935) |
| [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" >}}** | |
| <span style="opacity: .5;">PERCENTILE()</span> | | [influxdb_iox#7664](https://github.com/influxdata/influxdb_iox/issues/7664) |
| <span style="opacity: .5;">SAMPLE()</span> | | [influxdb_iox#6935](https://github.com/influxdata/influxdb_iox/issues/6935) |
| <span style="opacity: .5;">TOP()</span> | | [influxdb_iox#7650](https://github.com/influxdata/influxdb_iox/issues/7650) |
### Transformations
| Function | Supported | Tracking Issue |
| :--------------------------------------------------------- | :----------------------: | :-------------------------------------------------------------------------- |
| [ABS()](functions/transformations/#abs) | **{{< icon "check" >}}** | |
| [ACOS()](functions/transformations/#acos) | **{{< icon "check" >}}** | |
| [ASIN()](functions/transformations/#asin) | **{{< icon "check" >}}** | |
| [ATAN()](functions/transformations/#atan) | **{{< icon "check" >}}** | |
| [ATAN2()](functions/transformations/#atan2) | **{{< icon "check" >}}** | |
| [CEIL()](functions/transformations/#ceil) | **{{< icon "check" >}}** | |
| [COS()](functions/transformations/#cos) | **{{< icon "check" >}}** | |
| <span style="opacity: .5;">CUMULATIVE_SUM()<span> | | [influxdb_iox#7467](https://github.com/influxdata/influxdb_iox/issues/7467) |
| <span style="opacity: .5;">DERIVATIVE()<span> | | [influxdb_iox#7647](https://github.com/influxdata/influxdb_iox/issues/7647) |
| <span style="opacity: .5;">DIFFERENCE()<span> | | [influxdb_iox#7468](https://github.com/influxdata/influxdb_iox/issues/7468) |
| <span style="opacity: .5;">ELAPSED()<span> | | [influxdb_iox#6934](https://github.com/influxdata/influxdb_iox/issues/6934) |
| [EXP()](functions/transformations/#exp) | **{{< icon "check" >}}** | |
| [FLOOR()](functions/transformations/#floor) | **{{< icon "check" >}}** | |
| [LN()](functions/transformations/#ln) | **{{< icon "check" >}}** | |
| [LOG()](functions/transformations/#log) | **{{< icon "check" >}}** | |
| [LOG2()](functions/transformations/#log2) | **{{< icon "check" >}}** | |
| [LOG10()](functions/transformations/#log10) | **{{< icon "check" >}}** | |
| <span style="opacity: .5;">MOVING_AVERAGE()<span> | | [influxdb_iox#7600](https://github.com/influxdata/influxdb_iox/issues/7600) |
| <span style="opacity: .5;">NON_NEGATIVE_DERIVATIVE()<span> | | [influxdb_iox#7649](https://github.com/influxdata/influxdb_iox/issues/7649) |
| <span style="opacity: .5;">NON_NEGATIVE_DIFFERENCE()<span> | | [influxdb_iox#7628](https://github.com/influxdata/influxdb_iox/issues/7628) |
| [POW()](functions/transformations/#pow) | **{{< icon "check" >}}** | |
| [ROUND()](functions/transformations/#round) | **{{< icon "check" >}}** | |
| [SIN()](functions/transformations/#sin) | **{{< icon "check" >}}** | |
| [SQRT()](functions/transformations/#sqrt) | **{{< icon "check" >}}** | |
| [TAN()](functions/transformations/#tan) | **{{< icon "check" >}}** | |
| Function | Supported | Tracking Issue |
| :--------------------------------------------------------------------------------------- | :----------------------: | :-------------------------------------------------------------------------- |
| [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" >}}** | |
| <span style="opacity: .5;">CUMULATIVE_SUM()<span> | | [influxdb_iox#7467](https://github.com/influxdata/influxdb_iox/issues/7467) |
| <span style="opacity: .5;">DERIVATIVE()<span> | | [influxdb_iox#7647](https://github.com/influxdata/influxdb_iox/issues/7647) |
| <span style="opacity: .5;">DIFFERENCE()<span> | | [influxdb_iox#7468](https://github.com/influxdata/influxdb_iox/issues/7468) |
| <span style="opacity: .5;">ELAPSED()<span> | | [influxdb_iox#6934](https://github.com/influxdata/influxdb_iox/issues/6934) |
| [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" >}}** | |
| <span style="opacity: .5;">MOVING_AVERAGE()<span> | | [influxdb_iox#7600](https://github.com/influxdata/influxdb_iox/issues/7600) |
| <span style="opacity: .5;">NON_NEGATIVE_DERIVATIVE()<span> | | [influxdb_iox#7649](https://github.com/influxdata/influxdb_iox/issues/7649) |
| <span style="opacity: .5;">NON_NEGATIVE_DIFFERENCE()<span> | | [influxdb_iox#7628](https://github.com/influxdata/influxdb_iox/issues/7628) |
| [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

View File

@ -0,0 +1,281 @@
---
title: InfluxQL math operators
descriptions: >
Use InfluxQL mathematical operators to perform mathematical operations in
InfluxQL queries.
menu:
influxdb_cloud_dedicated:
name: Math operators
parent: influxql-reference
identifier: influxql-mathematical-operators
weight: 215
---
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`, i.e. 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`, i.e. 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/query-data/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.7/query-data/influxql/explore-data/subqueries/) which offer similar functionality to using mathematical operators inside a function call.
{{% /note %}} -->

View File

@ -57,11 +57,6 @@ to
Use the InfluxDB v2 or v1 API to write the Get started home sensor sample data
to {{< cloud-name >}}.
Replace the following in the script below:
- `DATABASE_NAME`: your InfluxDB Cloud Dedicated database
- `DATABASE_TOKEN`: a [database token](/influxdb/cloud-dedicated/admin/tokens/)
with _write_ permission to the database
{{< code-tabs-wrapper >}}
{{% code-tabs %}}
@ -71,7 +66,7 @@ Replace the following in the script below:
{{% code-tab-content %}}
{{% influxdb/custom-timestamps %}}
{{% code-callout "DATABASE_TOKEN|DATABASE_NAME" "magenta" %}}
{{% code-placeholders "DATABASE_TOKEN|DATABASE_NAME" %}}
```sh
export INFLUX_HOST=https://cluster-id.influxdb.io
export INFLUX_TOKEN=DATABASE_TOKEN
@ -112,14 +107,14 @@ home,room=Living\ Room temp=22.2,hum=36.4,co=17i 1641067200
home,room=Kitchen temp=22.7,hum=36.5,co=26i 1641067200
"
```
{{% /code-callout %}}
{{% /code-placeholders %}}
{{% /influxdb/custom-timestamps %}}
{{% /code-tab-content %}}
{{% code-tab-content %}}
{{% influxdb/custom-timestamps %}}
{{% code-callout "DATABASE_TOKEN|DATABASE_NAME" "magenta" %}}
{{% code-placeholders "DATABASE_TOKEN|DATABASE_NAME" %}}
```sh
export INFLUX_HOST=https://cluster-id.influxdb.io
export INFLUX_TOKEN=DATABASE_TOKEN
@ -159,12 +154,18 @@ home,room=Living\ Room temp=22.2,hum=36.4,co=17i 1641067200
home,room=Kitchen temp=22.7,hum=36.5,co=26i 1641067200
"
```
{{% /code-callout %}}
{{% /code-placeholders %}}
{{% /influxdb/custom-timestamps %}}
{{% /code-tab-content %}}
{{< /code-tabs-wrapper >}}
Replace the following in the script above:
- `DATABASE_NAME`: your InfluxDB Cloud Dedicated database
- `DATABASE_TOKEN`: a [database token](/influxdb/cloud-dedicated/admin/tokens/)
with _write_ permission to the database
{{% /expand %}}
{{< /expand-wrapper >}}
@ -201,11 +202,6 @@ series use cases that involve seasonality.
Use the InfluxDB v2 or v1 API to write the NOAA Bay Area weather sample data to
{{< cloud-name >}}.
Replace the following in the script below:
- `DATABASE_NAME`: your InfluxDB Cloud Dedicated database
- `DATABASE_TOKEN`: a [database token](/influxdb/cloud-dedicated/admin/tokens/)
with sufficient permissions to the database
{{< code-tabs-wrapper >}}
{{% code-tabs %}}
@ -214,7 +210,7 @@ Replace the following in the script below:
{{% /code-tabs %}}
{{% code-tab-content %}}
{{% code-callout "DATABASE_TOKEN|DATABASE_NAME" "magenta" %}}
{{% code-placeholders "DATABASE_TOKEN|DATABASE_NAME" %}}
```sh
export INFLUX_HOST=http://cluster-id.influxdb.io
export INFLUX_TOKEN=DATABASE_TOKEN
@ -228,12 +224,12 @@ curl --request POST \
--header "Accept: application/json" \
--data-binary "$(curl --request GET https://docs.influxdata.com/downloads/bay-area-weather.lp)"
```
{{% /code-callout %}}
{{% /code-placeholders %}}
{{% /code-tab-content %}}
{{% code-tab-content %}}
{{% code-callout "DATABASE_TOKEN|DATABASE_NAME" "magenta" %}}
{{% code-placeholders "DATABASE_TOKEN|DATABASE_NAME" %}}
```sh
export INFLUX_HOST=http://cluster-id.influxdb.io
export INFLUX_TOKEN=DATABASE_TOKEN
@ -246,11 +242,17 @@ curl --request POST \
--header "Content-type: text/plain; charset=utf-8" \
--data-binary "$(curl --request GET https://docs.influxdata.com/downloads/bay-area-weather.lp)"
```
{{% /code-callout %}}
{{% /code-placeholders %}}
{{% /code-tab-content %}}
{{< /code-tabs-wrapper >}}
Replace the following in the script above:
- `DATABASE_NAME`: your InfluxDB Cloud Dedicated database
- `DATABASE_TOKEN`: a [database token](/influxdb/cloud-dedicated/admin/tokens/)
with sufficient permissions to the database
{{% /expand %}}
{{< /expand-wrapper >}}
@ -291,11 +293,6 @@ The Bitcoin price sample dataset provides Bitcoin prices from
Use the InfluxDB v2 or v1 API to write the Bitcoin price sample data to
{{< cloud-name >}}.
Replace the following in the script below:
- `DATABASE_NAME`: your InfluxDB Cloud Dedicated database
- `DATABASE_TOKEN`: a [database token](/influxdb/cloud-dedicated/admin/tokens/)
with sufficient permissions to the database
{{< code-tabs-wrapper >}}
{{% code-tabs %}}
@ -304,7 +301,7 @@ Replace the following in the script below:
{{% /code-tabs %}}
{{% code-tab-content %}}
{{% code-callout "DATABASE_TOKEN|DATABASE_NAME" "magenta" %}}
{{% code-placeholders "DATABASE_TOKEN|DATABASE_NAME" %}}
```sh
export INFLUX_HOST=https://cluster-id.influxdb.io
export INFLUX_TOKEN=DATABASE_TOKEN
@ -318,12 +315,12 @@ curl --request POST \
--header "Accept: application/json" \
--data-binary "$(curl --request GET https://docs.influxdata.com/downloads/bitcoin.lp)"
```
{{% /code-callout %}}
{{% /code-placeholders %}}
{{% /code-tab-content %}}
{{% code-tab-content %}}
{{% code-callout "DATABASE_TOKEN|DATABASE_NAME" "magenta" %}}
{{% code-placeholders "DATABASE_TOKEN|DATABASE_NAME" %}}
```sh
export INFLUX_HOST=https://cluster-id.influxdb.io
export INFLUX_TOKEN=DATABASE_TOKEN
@ -336,11 +333,17 @@ curl --request POST \
--header "Content-type: text/plain; charset=utf-8" \
--data-binary "$(curl --request GET https://docs.influxdata.com/downloads/bitcoin.lp)"
```
{{% /code-callout %}}
{{% /code-placeholders %}}
{{% /code-tab-content %}}
{{< /code-tabs-wrapper >}}
Replace the following in the script above:
- `DATABASE_NAME`: your InfluxDB Cloud Dedicated database
- `DATABASE_TOKEN`: a [database token](/influxdb/cloud-dedicated/admin/tokens/)
with sufficient permissions to the database
{{% /expand %}}
{{< /expand-wrapper >}}
@ -369,11 +372,6 @@ transformation functions.
Use the InfluxDB v2 or v1 API to write the random number sample data to
{{< cloud-name >}}.
Replace the following in the script below:
- `DATABASE_NAME`: your InfluxDB Cloud Dedicated database
- `DATABASE_TOKEN`: a [database token](/influxdb/cloud-dedicated/admin/tokens/)
with sufficient permissions to the database
{{< code-tabs-wrapper >}}
{{% code-tabs %}}
@ -382,7 +380,7 @@ Replace the following in the script below:
{{% /code-tabs %}}
{{% code-tab-content %}}
{{% code-callout "DATABASE_TOKEN|DATABASE_NAME" "magenta" %}}
{{% code-placeholders "DATABASE_TOKEN|DATABASE_NAME" %}}
```sh
export INFLUX_HOST=http://cluster-id.influxdb.io
export INFLUX_TOKEN=DATABASE_TOKEN
@ -396,12 +394,12 @@ curl --request POST \
--header "Accept: application/json" \
--data-binary "$(curl --request GET https://docs.influxdata.com/downloads/random-numbers.lp)"
```
{{% /code-callout %}}
{{% /code-placeholders %}}
{{% /code-tab-content %}}
{{% code-tab-content %}}
{{% code-callout "DATABASE_TOKEN|DATABASE_NAME" "magenta" %}}
{{% code-placeholders "DATABASE_TOKEN|DATABASE_NAME" %}}
```sh
export INFLUX_HOST=http://cluster-id.influxdb.io
export INFLUX_TOKEN=DATABASE_TOKEN
@ -414,10 +412,16 @@ curl --request POST \
--header "Content-type: text/plain; charset=utf-8" \
--data-binary "$(curl --request GET https://docs.influxdata.com/downloads/random-numbers.lp)"
```
{{% /code-callout %}}
{{% /code-placeholders %}}
{{% /code-tab-content %}}
{{< /code-tabs-wrapper >}}
Replace the following in the script above:
- `DATABASE_NAME`: your InfluxDB Cloud Dedicated database
- `DATABASE_TOKEN`: a [database token](/influxdb/cloud-dedicated/admin/tokens/)
with sufficient permissions to the database
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -0,0 +1,33 @@
---
title: Manage API tokens
seotitle: Manage API tokens in InfluxDB
description: Manage API tokens in InfluxDB using the InfluxDB UI or the influx CLI.
influxdb/cloud-serverless/tags: [tokens, authentication, security]
menu:
influxdb_cloud_serverless:
name: Manage tokens
parent: Administer InfluxDB Cloud
weight: 9
---
InfluxDB **API tokens** ensure secure interaction between InfluxDB and external
tools such as clients or applications.
An API token belongs to a specific user and identifies InfluxDB permissions
within an organization.
Learn how to create, view, update, or delete an API token.
## API token types
- [All-Access API token](#all-access-api-token)
- [Custom API token](#custom-api-token)
### All-Access API token
Grants full read and write access to all resources in an organization.
### Custom API token
Grants read access, write access, or both to specific resources in an organization.
---
{{< children hlevel="h2" >}}

View File

@ -0,0 +1,227 @@
---
title: Create a token
seotitle: Create an API token in InfluxDB
description: Create an API token in InfluxDB using the InfluxDB UI, the `influx` CLI, or the InfluxDB API.
menu:
influxdb_cloud_serverless:
name: Create a token
parent: Manage tokens
weight: 201
---
Create API tokens using the InfluxDB user interface (UI), the `influx`
command line interface (CLI), or the InfluxDB API.
{{% note %}}
To follow best practices for secure API token generation and retrieval, InfluxDB enforces access restrictions on API tokens.
- Tokens are visible to the user who created the token.
- InfluxDB only allows access to the API token value immediately after the token is created.
- You can't change access (**read/write**) permissions for an API token after it's created.
- Tokens stop working when the user who created the token is deleted.
**We recommend the following for managing your tokens:**
- Create a generic user to create and manage tokens for writing data.
- Store your tokens in a secure password vault for future access.
{{% /note %}}
{{< tabs-wrapper >}}
{{% tabs %}}
[InfluxDB UI](#)
[influx CLI](#)
[InfluxDB API](#)
{{% /tabs %}}
<!---------------------------------- BEGIN UI --------------------------------->
{{% tab-content %}}
## Create a token in the InfluxDB UI
To create an InfluxDB API token in the InfluxDB UI, navigate to the **API Tokens** management page.
In the navigation menu on the left, select **Load Data** > **API Tokens**.
{{< nav-icon "load-data" >}}
- [Create an all-access token](#create-an-all-access-token)
- [Create a custom token](#create-a-custom-token)
- [Clone a token](#clone-a-token)
### Create an all-access token
1. From the [API Tokens management page](#create-a-token-in-the-influxdb-ui),
click the **{{< icon "plus" >}} {{< caps >}}Generate API Token{{< /caps >}}** button.
2. Select **All Access API Token**.
### Create a custom token
1. From the [API Tokens management page](#create-a-token-in-the-influxdb-ui),
click the **{{< icon "plus" >}} {{< caps >}}Generate API Token{{< /caps >}}** button.
2. Select **Custom API Token**.
3. When the **Generate a Personal API Token** window appears, enter a description. If you don't provide a description for the token, InfluxDB will generate a description from the permissions you assign.
For example, if you select **Read** for a bucket named "\_monitoring" and **Write** for a bucket named "\_tasks", InfluxDB will generate the description "Read buckets \_monitoring Write buckets \_tasks".
4. Select the check boxes in the **Read** and **Write** columns to assign access permissions for the token. You can enable access to all buckets, individual buckets, Telegraf configurations, and other InfluxDB resources. By default, the new token has no access permissions.
5. When you're finished, click **{{< caps >}}Generate{{< /caps >}}**.
6. When InfluxDB displays the token value, click **{{< caps >}}Copy to Clipboard{{< /caps >}}**. This is your only chance to access and copy the token value from InfluxDB.
7. (Optional) Store the API token value in a secure password vault.
### Clone a token
To create a token with the same authorizations as an existing token, clone the existing token.
1. From the [API Tokens management page](#create-a-token-in-the-influxdb-ui),
find the token you want to clone and click the **{{< icon "settings" >}}** icon located far right of the token description.
3. Select **Clone**.
3. When InfluxDB UI displays the created token, click **{{< caps >}}Copy to Clipboard{{< /caps >}}**. This is your only chance to access and copy the token value from InfluxDB.
4. (Optional) Store the API token value in a secure password vault.
{{% /tab-content %}}
<!----------------------------------- END UI ---------------------------------->
<!--------------------------------- BEGIN CLI --------------------------------->
{{% tab-content %}}
## Create a token using the influx CLI
Use the [`influx auth create` command](/influxdb/cloud-serverless/reference/cli/influx/auth/create) to create a token.
Include flags with the command to grant specific permissions to the token.
See the [available flags](/influxdb/cloud-serverless/reference/cli/influx/auth/create#flags).
Only tokens with the `write: authorizations` permission can create tokens.
Provide the following flags with the command:
- `--token`: API token with permission to create new tokens
- `--org`: Organization name
- [Permission flags](/influxdb/cloud-serverless/reference/cli/influx/auth/create#flags)
{{% code-placeholders "(API|ORG)_(TOKEN|NAME)" %}}
```sh
influx auth create \
--token API_TOKEN \
--org ORG_NAME \
--read-buckets \
--write-buckets \
--read-dbrps \
--write-dbrps
```
{{% /code-placeholders %}}
### Examples
- [Create an all-access token](#create-an-all-access-token-cli)
- [Create a token with specific permissions](#create-a-token-with-specific-permissions)
- [Create a token with specified read permissions](#create-a-token-with-specified-read-permissions)
- [Create a token scoped to a user and with specified read and write permissions](#create-a-token-scoped-to-a-user-and-with-specified-read-and-write-permissions)
#### Create an all-access token {#create-an-all-access-token-cli}
Create an All-Access token to grant permissions to all resources in an organization.
{{% code-placeholders "(API|ORG)_(TOKEN|NAME)" %}}
```sh
influx auth create \
--token API_TOKEN \
--org ORG_NAME \
--all-access
```
{{% /code-placeholders %}}
#### Create a token with specific permissions
##### Create a token with specified read permissions
{{% code-placeholders "(API|ORG|BUCKET)_(TOKEN|NAME|ID)" %}}
```sh
influx auth create \
--token API_TOKEN \
--org ORG_NAME \
--read-bucket BUCKET_ID \
--read-bucket BUCKET_ID \
--read-dashboards \
--read-tasks \
--read-telegrafs \
--read-user
```
{{% /code-placeholders %}}
##### Create a token scoped to a user and with specified read and write permissions
{{% code-placeholders "(API|ORG)_(TOKEN|NAME)|USERNAME" %}}
```sh
influx auth create \
--token API_TOKEN \
--org ORG_NAME \
--user USERNAME \
--read-authorizations \
--write-authorizations \
--read-buckets \
--write-buckets \
--read-dashboards \
--write-dashboards \
--read-tasks \
--write-tasks \
--read-telegrafs \
--write-telegrafs \
--read-users \
--write-users
```
{{% /code-placeholders %}}
See the [`influx auth create` documentation](/{{< latest "influxdb" >}}/reference/cli/influx/auth/create)
for information about other available flags.
{{% /tab-content %}}
<!---------------------------------- END CLI ---------------------------------->
<!--------------------------------- BEGIN API --------------------------------->
{{% tab-content %}}
## Create a token using the InfluxDB API
Use the `/api/v2/authorizations` InfluxDB API endpoint to create a token.
{{< api-endpoint method="POST" endpoint="http://localhost:8086/api/v2/authorizations" api-ref="/influxdb/v2.7/api/#operation/PostAuthorizations" >}}
Include the following in your request:
- **Headers**
- **Authorization**: `Token API_TOKEN`
(API token with the [`write: authorizations`](/influxdb/cloud-serverless/api/#operation/PostAuthorizations) permission)
- **Content-type**: `application/json`
- **Request body**: JSON object with the following properties:
- **status**: Token status (active or inactive)
- **description**: Token description
- **orgID**: Organization ID
- **permissions**: JSON array of objects, each with the following properties:
- **action**: Authorized action (read or write)
- **resource**: JSON object with the following properties
- **orgID**: Organization ID
- **type**: Resource type
- **name**: _(Optional)_ Resource name to scope permission to
{{% code-placeholders "(API|ORG|AUTHORIZATION)_(TOKEN|ID|DESCRIPTION)" %}}
```sh
{{% get-shared-text "api/cloud-serverless/auth/token-create.sh" %}}
```
{{% /code-placeholders %}}
### Create a token scoped to a user
To scope a token to a user other than the token creator, pass the `userID` property in the request
body.
{{% code-placeholders "(API|ORG)_(TOKEN|ID)" %}}
```sh
{{% get-shared-text "api/cloud-serverless/auth/tokens-create-with-user.sh" %}}
```
{{% /code-placeholders %}}
See the
[`POST /api/v2/authorizations` documentation](/influxdb/v2.7/api/#operation/PostAuthorizations)
for more information about options.
{{% /tab-content %}}
<!---------------------------------- END API ---------------------------------->
{{< /tabs-wrapper >}}

View File

@ -0,0 +1,99 @@
---
title: Delete a token
seotitle: Delete an API token from InfluxDB
description: Delete an API token from InfluxDB using the InfluxDB UI or the `influx` CLI.
menu:
influxdb_cloud_serverless:
name: Delete a token
parent: Manage tokens
weight: 204
---
Delete API tokens using the InfluxDB user interface (UI), `influx` command line
interface (CLI), or InfluxDB API.
Once deleted, all users and external integrations using the API token will no longer
have access to your InfluxDB instance.
{{< tabs-wrapper >}}
{{% tabs %}}
[InfluxDB UI](#)
[influx CLI](#)
[InfluxDB API](#)
{{% /tabs %}}
<!---------------------------------- BEGIN UI --------------------------------->
{{% tab-content %}}
## Delete tokens in the InfluxDB UI
1. In the navigation menu on the left, select **Load Data** > **API Tokens**.
{{< nav-icon "data" >}}
2. Find the token that you would like to delete.
3. Click the **{{< icon "delete" >}}** icon located far right of the token description.
4. Click **{{< caps >}}Confirm{{< /caps >}}** to delete the token.
{{% /tab-content %}}
<!----------------------------------- END UI ---------------------------------->
<!--------------------------------- BEGIN CLI --------------------------------->
{{% tab-content %}}
## Delete a token using the influx CLI
Use the [`influx auth delete` command](/influxdb/v2.7/reference/cli/influx/auth/delete)
to delete a token.
Provide the following flags:
- `--token`: API token with permission to delete authorizations
- `--id`: Authorization ID to delete (available in the output of `influx auth find`)
{{% code-placeholders "(API|AUTHORIZATION)_(TOKEN|ID)" %}}
```sh
influx auth delete \
--token API_TOKEN \
--id AUTHORIZATION_ID
```
{{% /code-placeholders %}}
{{% /tab-content %}}
<!---------------------------------- END CLI ---------------------------------->
<!--------------------------------- BEGIN API --------------------------------->
{{% tab-content %}}
## Delete a token using the InfluxDB API
Use the `/api/v2/authorizations` InfluxDB API endpoint to delete a token.
{{< api-endpoint method="DELETE" endpoint="https://cloud2.influxdata.com/api/v2/authorizations/{AUTH_ID}" api-ref="/influxdb/v2.7/api/#operation/DeleteAuthorizationsID" >}}
Include the following in your request:
- **Headers**:
- **Authorization**: `Token API_TOKEN`
(API token with the [`write: authorizations`](/influxdb/cloud-serverless/api/#operation/PostAuthorizations) permission)
- **Content-type**: `application/json`
- **Path parameters**:
- **authID**: Authorization ID to delete
{{% code-placeholders "API_TOKEN" %}}
```sh
# Delete the first authorization listed for the user.
curl --request GET \
https://cloud2.influxdata.com/api/v2/authorizations?user=user2 \
--header "Authorization: Token API_TOKEN" \
--header 'Content-type: application/json' \
| jq .authorizations[0].id \
| xargs -I authid curl --request DELETE \
https://cloud2.influxdata.com/api/v2/authorizations/authid \
--header "Authorization: Token API_TOKEN" \
--header 'Content-type: application/json'
```
{{% /code-placeholders %}}
{{% /tab-content %}}
<!---------------------------------- END API ---------------------------------->
{{< /tabs-wrapper >}}

View File

@ -0,0 +1,147 @@
---
title: Update a token
seotitle: Update API tokens in InfluxDB
description: Update API tokens' descriptions in InfluxDB using the InfluxDB UI.
menu:
influxdb_cloud_serverless:
name: Update a token
parent: Manage tokens
weight: 203
---
Update an API token's description and status using the InfluxDB user interface (UI),
`influx` CLI, or InfluxDB API.
- [Update a token in the InfluxDB UI](#update-a-token-in-the-influxdb-ui)
- [Enable or disable a token in the InfluxDB UI](#enable-or-disable-a-token-in-the-influxdb-ui)
- [Enable a token using the influx CLI](#enable-a-token-using-the-influx-cli)
- [Disable a token using the influx CLI](#disable-a-token-using-the-influx-cli)
- [Update a token using the InfluxDB API](#update-a-token-using-the-influxdb-api)
{{< tabs-wrapper >}}
{{% tabs %}}
[InfluxDB UI](#)
[influx CLI](#)
[InfluxDB API](#)
{{% /tabs %}}
<!---------------------------------- BEGIN UI --------------------------------->
{{% tab-content %}}
## Update a token in the InfluxDB UI
To update tokens in the InfluxDB UI, navigate to the **API Tokens** management page.
In the navigation menu on the left, select **Load Data** > **API Tokens**.
{{< nav-icon "load-data" >}}
- [Update a token's description](#update-a-tokens-description)
- [Enable or disable a token in the InfluxDB UI](#enable-or-disable-a-token-in-the-influxdb-ui)
### Update a token's description
1. On the [token management page](#update-a-token-in-the-influxdb-ui), click the
pencil icon ({{< icon "pencil" >}}) next to the token's description.
2. Update the token description, and then click anywhere else to save.
### Enable or disable a token in the InfluxDB UI
1. On the [token management page](#update-a-token-in-the-influxdb-ui), find the
token that you would like to enable or disable.
2. Click the token description.
3. Click the **{{< icon "toggle-blue" >}} Active** toggle.
{{% /tab-content %}}
<!----------------------------------- END UI ---------------------------------->
<!--------------------------------- BEGIN CLI --------------------------------->
{{% tab-content %}}
## Enable a token using the influx CLI
Use the [`influx auth active` command](/influxdb/cloud-serverless/reference/cli/influx/auth/active)
to activate a token.
Provide the following flags:
- `--token`: API token with permission to update authorizations
- `--id`: Authorization ID to enable (available in the output of
[`influx auth list`](/influxdb/cloud-serverless/reference/cli/influx/auth/list))
{{% code-placeholders "(API|AUTHORIZATION)_(TOKEN|ID)" %}}
```sh
influx auth active \
--token API_TOKEN \
--id AUTHORIZATION_ID
```
{{% /code-placeholders %}}
### Disable a token using the influx CLI
Use the [`influx auth inactive` command](/influxdb/cloud-serverless/reference/cli/influx/auth/active)
to deactivate a token.
Provide the following flags:
- `--token`: API token with permission to update authorizations
- `--id`: Authorization ID to disable (available in the output of
[`influx auth list`](/influxdb/cloud-serverless/reference/cli/influx/auth/list))
{{% code-placeholders "(API|AUTHORIZATION)_(TOKEN|ID)" %}}
```sh
influx auth inactive \
--token API_TOKEN \
--id AUTHORIZATION_ID
```
{{% /code-placeholders %}}
{{% /tab-content %}}
<!---------------------------------- END CLI ---------------------------------->
<!--------------------------------- BEGIN API --------------------------------->
{{% tab-content %}}
## Update a token using the InfluxDB API
Use the `/api/v2/authorizations` InfluxDB API endpoint to update the description
and status of a token.
{{< api-endpoint method="PATCH" endpoint="https://cloud2.influxdata.com/api/v2/authorizations/{AUTH_ID}" api-ref="/influxdb/v2.7/api/#operation/PatchAuthorizationsID" >}}
Include the following in your request:
- **Headers**:
- **Authorization**: `Token API_TOKEN`
(API token with the [`write: authorizations`](/influxdb/cloud-serverless/api/#operation/PostAuthorizations) permission)
- **Content-type**: `application/json`
- **Path parameters**:
- **authID**: Authorization ID to update
- **Request body**: JSON object with
[authorization properties](/influxdb/cloud-serverless/admin/tokens/create-token/?t=InfluxDB+API#create-a-token-using-the-influxdb-api)
to update
### Disable a token
{{% code-placeholders "API_TOKEN" %}}
```sh
# Update the description and status of the first authorization listed for the user.
curl --request GET \
https://cloud2.influxdata.com/api/v2/authorizations?user=user2 \
--header "Authorization: Token API_TOKEN" \
--header 'Content-type: application/json' \
| jq .authorizations[0].id \
| xargs -I authid curl --request PATCH \
https://cloud2.influxdata.com/api/v2/authorizations/authid \
--header "Authorization: Token API_TOKEN" \
--header 'Content-type: application/json' \
--data '{
"description": "deactivated_auth",
"status": "inactive"
}' | jq .
```
{{% /code-placeholders %}}
{{% /tab-content %}}
<!---------------------------------- END API ---------------------------------->
{{< /tabs-wrapper >}}

View File

@ -0,0 +1,33 @@
---
title: Use tokens
seotitle: Use an API token in InfluxDB
description: Use an API token in the InfluxDB UI, the `influx` CLI, or the InfluxDB API.
menu:
influxdb_cloud_serverless:
name: Use tokens
parent: Manage tokens
weight: 204
---
Use tokens to authenticate requests to InfluxDB, including requests to write,
query, and manage data and resources.
Authenticate requests using the [`influx` CLI](/influxdb/v2.7/reference/cli/influx/),
API requests made with client libraries, and tools like cURL.
### Add a token to a CLI request
```sh
influx write \
--token API_TOKEN \
# ...
```
### Use environment variables
The `influx` CLI automatically uses the `INFLUX_TOKEN` variable when defined in
the current session.
### Use CLI configurations
Create [`influx` CLI connection configurations](/influxdb/cloud-serverless/reference/cli/influx/config/)
to automatically add your token and other required credentials to each CLI command execution.

View File

@ -0,0 +1,137 @@
---
title: View tokens
seotitle: View API tokens in InfluxDB
description: View API tokens in InfluxDB using the InfluxDB UI, the `influx` CLI, or the InfluxDB API.
menu:
influxdb_cloud_serverless:
name: View tokens
parent: Manage tokens
weight: 202
---
View API tokens and permissions using the InfluxDB user interface (UI),
the `influx` command line interface (CLI), or the InfluxDB API.
{{% note %}}
To follow best practices for secure API token generation and retrieval, {{% cloud-name %}} enforces access restrictions on API tokens.
- InfluxDB UI only allows access to the API token value immediately after the token is created.
- You can't change access (**read/write**) permissions for an API token after it's created.
- Tokens stop working when the user who created the token is deleted.
We recommend the following for managing your tokens:
- Create a generic user to create and manage tokens for writing data.
- Store your tokens in a secure password vault for future access.
{{% /note %}}
{{< tabs-wrapper >}}
{{% tabs %}}
[InfluxDB UI](#)
[influx CLI](#)
[InfluxDB API](#)
{{% /tabs %}}
<!---------------------------------- BEGIN UI --------------------------------->
{{% tab-content %}}
## View tokens in the InfluxDB UI
1. In the navigation menu on the left, select **Load Data** > **API Tokens**.
{{< nav-icon "load-data" >}}
2. Click a token description in the list to view the token status and a list of
access permissions.
{{% /tab-content %}}
<!----------------------------------- END UI ---------------------------------->
<!--------------------------------- BEGIN CLI --------------------------------->
{{% tab-content %}}
## View tokens using the influx CLI
Use the [`influx auth list` command](/influxdb/cloud-serverless/reference/cli/influx/auth/list)
to view tokens.
Provide the following flags:
- `--token`: API token with permission to read authorizations
{{% code-placeholders "API_TOKEN" %}}
```sh
influx auth list --token API_TOKEN
```
{{% /code-placeholders %}}
Filtering options such as filtering by authorization ID, username, or user ID are available.
See the [`influx auth list` documentation](/influxdb/cloud-serverless/reference/cli/influx/auth/list)
for information about other available flags.
{{% /tab-content %}}
<!---------------------------------- END CLI ---------------------------------->
<!--------------------------------- BEGIN API --------------------------------->
{{% tab-content %}}
## View tokens using the InfluxDB API
Use the `/api/v2/authorizations` InfluxDB API endpoint to view tokens and permissions.
{{< api-endpoint method="GET" endpoint="https://cloud2.influxdata.com/api/v2/authorizations" api-ref="/influxdb/cloud-serverless/api/#operation/GetAuthorizations" >}}
- [View a single token](#view-a-single-token)
- [Filter the token list](#filter-the-token-list)
Include the following in your request:
- **Headers**:
- **Authorization**: `Token API_TOKEN`
(API token with the [`read: authorizations`](/influxdb/cloud-serverless/api/#operation/PostAuthorizations) permission)
- **Content-type**: `application/json`
{{% code-placeholders "API_TOKEN" %}}
```sh
{{% get-shared-text "api/cloud-serverless/auth/tokens-view.sh" %}}
```
{{% /code-placeholders %}}
### View a single token
To view a specific authorization and token, include the authorization ID in the URL path.
{{% api-endpoint method="GET" endpoint="https://cloud2.influxdata.com/api/v2/authorizations/{authID}" api-ref="/influxdb/cloud-serverless/api/#operation/GetAuthorizationsID" %}}
Include the following in your request:
- **Headers**:
- **Authorization**: `Token API_TOKEN`
(API token with the [`read: authorizations`](/influxdb/cloud-serverless/api/#operation/PostAuthorizations) permission)
- **Content-type**: `application/json`
{{% code-placeholders "(API|AUTHORIZATION)_(TOKEN|ID)" %}}
```sh
curl --request GET \
"https://us-west-2-1.aws.cloud2.influxdata.com/api/v2/authorizations/AUTHORIZATION_ID" \
--header "Authorization: Token API_TOKEN" \
--header 'Content-type: application/json'
```
{{% /code-placeholders %}}
### Filter the token list
InfluxDB returns authorizations from the same organization as the token used in the request.
To filter tokens by user, include `userID` as a query parameter in your request.
{{% code-placeholders "API_TOKEN" %}}
```sh
{{% get-shared-text "api/cloud-serverless/auth/tokens-view-filter.sh" %}}
```
{{% /code-placeholders %}}
See the [`/authorizations` endpoint documentation](/influxdb/cloud-serverless/api/#tag/Authorizations-(API-tokens))
for more information about available parameters.
{{% /tab-content %}}
<!---------------------------------- END API ---------------------------------->
{{< /tabs-wrapper >}}

View File

@ -1,15 +0,0 @@
---
title: Execute queries
seotitle: Execute queries for data in InfluxDB Cloud Serverless
description: Use tools and libraries to query data stored in InfluxDB Cloud Serverless
weight: 103
menu:
influxdb_cloud_serverless:
name: Execute queries
parent: Query data
influxdb/cloud-serverless/tags: [query]
---
There are multiple ways to execute queries with InfluxDB. Choose from the following options:
{{< children >}}

View File

@ -1,29 +0,0 @@
---
title: Query with Flight SQL
seotitle: Query InfluxDB with Arrow Flight SQL
description: >
Query your data using Apache Arrow Flight SQL protocol and clients.
weight: 201
menu:
influxdb_cloud_serverless:
name: Query with Flight SQL
parent: Execute queries
influxdb/cloud-serverless/tags: [query, flightsql]
aliases:
- /influxdb/cloud-serverless/query-data/execute-queries/influx-api/
---
Use [Apache Arrow Flight SQL](https://arrow.apache.org/) to query data
stored in an InfluxDB Cloud Serverless bucket.
> Arrow Flight SQL is a protocol for interacting with SQL databases using the
> [Arrow in-memory format](https://arrow.apache.org/docs/format/Columnar.html)
> and the [Flight RPC](https://arrow.apache.org/docs/format/Flight.html) framework.
>
> {{% cite %}}-- [Apache Arrow Flight SQL documentation](https://arrow.apache.org/docs/format/FlightSql.html){{% /cite %}}
Data platforms and clients that support the Flight SQL protocol can query data
stored in an InfluxDB Cloud Serverless bucket.
Learn how to connect to InfluxDB and query your data using the following tools:
{{< children >}}

View File

@ -1,304 +0,0 @@
---
title: Use Python and the Flight SQL library to query data
description: >
Use Python and the `flightsql-dbapi` Flight SQL library to query data
stored in an InfluxDB Cloud Serverless bucket.
weight: 101
menu:
influxdb_cloud_serverless:
parent: Query with Flight SQL
name: Use Python
identifier: query_with_python
influxdb/cloud-serverless/tags: [query, flightsql, python]
related:
- /influxdb/cloud-serverless/query-data/tools/pandas/
- /influxdb/cloud-serverless/query-data/tools/pyarrow/
- /influxdb/cloud-serverless/query-data/sql/
list_code_example: |
```py
from flightsql import FlightSQLClient
client = FlightSQLClient(host='cloud2.influxdata.com',
token='INFLUX_READ_WRITE_TOKEN',
metadata={'database': 'BUCKET_NAME'},
features={'metadata-reflection': 'true'})
info = client.execute("SELECT * FROM home")
ticket = info.endpoints[0].ticket
reader = client.do_get(ticket)
```
---
Use Python and the Flight SQL library to query data stored in an InfluxDB Cloud
Serverless bucket.
- [Get started using Python to query InfluxDB](#get-started-using-python-to-query-influxdb)
- [Create a Python virtual environment](#create-a-python-virtual-environment)
- [Install Python](#install-python)
- [Create a project virtual environment](#create-a-project-virtual-environment)
- [Install Anaconda](#install-anaconda)
- [Query InfluxDB using Flight SQL](#query-influxdb-using-flight-sql)
- [Install the Flight SQL Python Library](#install-the-flight-sql-python-library)
- [Create a query client](#create-a-query-client)
- [Execute a query](#execute-a-query)
- [Retrieve data for Flight SQL query results](#retrieve-data-for-flight-sql-query-results)
## Get started using Python to query InfluxDB
This guide follows the recommended practice of using Python _virtual environments_.
If you don't want to use virtual environments and you have Python installed,
continue to [Query InfluxDB using Flight SQL](#query-influxdb-using-flight-sql).
## Create a Python virtual environment
Python [virtual environments](https://docs.python.org/3/library/venv.html) keep the Python interpreter and dependencies for your project self-contained and isolated from other projects.
To install Python and create a virtual environment, choose one of the following options:
- [Python venv](?t=venv#venv-install): The [`venv` module](https://docs.python.org/3/library/venv.html) comes standard in Python as of version 3.5.
- [Anaconda® Distribution](?t=Anaconda#conda-install): A Python/R data science distribution that provides Python and the **conda** package and environment manager.
{{< code-tabs-wrapper >}}
{{% code-tabs %}}
[venv](#venv-install)
[Anaconda](#conda-install)
{{% /code-tabs %}}
{{% code-tab-content %}}
<!-- Begin venv -->
### Install Python
1. Follow the [Python installation instructions](https://wiki.python.org/moin/BeginnersGuide/Download)
to install a recent version of the Python programming language for your system.
2. Check that you can run `python` and `pip` commands.
`pip` is a package manager included in most Python distributions.
In your terminal, enter the following commands:
```sh
python --version
```
```sh
pip --version
```
Depending on your system, you may need to use version-specific commands--for example.
```sh
python3 --version
```
```sh
pip3 --version
```
If neither `pip` nor `pip<PYTHON_VERSION>` works, follow one of the [Pypa.io Pip installation](https://pip.pypa.io/en/stable/installation/) methods for your system.
### Create a project virtual environment
1. Create a directory for your Python project and change to the new directory--for example:
```sh
mkdir ./PROJECT_DIRECTORY && cd $_
```
2. Use the Python `venv` module to create a virtual environment--for example:
```sh
python -m venv envs/virtualenv-1
```
`venv` creates the new virtual environment directory in your project.
3. To activate the new virtual environment in your terminal, run the `source` command and pass the file path of the virtual environment `activate` script:
```sh
source envs/VIRTUAL_ENVIRONMENT_NAME/bin/activate
```
For example:
```sh
source envs/virtualenv-1/bin/activate
```
<!-- End venv -->
{{% /code-tab-content %}}
{{% code-tab-content %}}
<!-- Begin conda -->
### Install Anaconda
1. Follow the [Anaconda installation instructions](https://docs.continuum.io/anaconda/install/) for your system.
2. Check that you can run the `conda` command:
```sh
conda
```
3. Use `conda` to create a virtual environment--for example:
```sh
conda create --prefix envs/virtualenv-1
```
`conda` creates a virtual environment in a directory named `./envs/virtualenv-1`.
4. To activate the new virtual environment, use the `conda activate` command and pass the directory path of the virtual environment:
```sh
conda activate envs/VIRTUAL_ENVIRONMENT_NAME
```
For example:
```sh
conda activate ./envs/virtualenv-1
```
{{% /code-tab-content %}}
{{< /code-tabs-wrapper >}}
When a virtual environment is activated, the name displays at the beginning of your terminal command line--for example:
{{% code-callout "(virtualenv-1)"%}}
```sh
(virtualenv-1) $ PROJECT_DIRECTORY
```
{{% /code-callout %}}
## Query InfluxDB using Flight SQL
1. [Install the Flight SQL Python Library](#install-the-flight-sql-python-library)
2. [Create a query client](#create-a-query-client)
3. [Execute a query](#execute-a-query)
### Install the Flight SQL Python Library
The [`flightsql-dbapi`](https://github.com/influxdata/flightsql-dbapi) Flight SQL library for Python provides a
[DB API 2](https://peps.python.org/pep-0249/) interface and
[SQLAlchemy](https://www.sqlalchemy.org/) dialect for
[Flight SQL](https://arrow.apache.org/docs/format/FlightSql.html).
Installing `flightsql-dbapi` also installs the [`pyarrow`](https://arrow.apache.org/docs/python/index.html) library that you'll use for working with Arrow data.
In your terminal, use `pip` to install `flightsql-dbapi`:
```sh
pip install flightsql-dbapi
```
With `flightsql-dbapi` and `pyarrow` installed, you're ready to query and analyze data stored in an InfluxDB bucket.
### Create a query client
The following example shows how to use Python with `flightsql-dbapi`
and the _DB API 2_ interface to instantiate a Flight SQL client configured for an InfluxDB bucket.
1. In your editor, copy and paste the following sample code to a new file--for example, `query-example.py`:
```py
# query-example.py
from flightsql import FlightSQLClient
# Instantiate a FlightSQLClient configured for your bucket
client = FlightSQLClient(host='cloud2.influxdata.com',
token='INFLUX_READ_WRITE_TOKEN',
metadata={'database': 'BUCKET_NAME'},
features={'metadata-reflection': 'true'})
```
2. Replace the following configuration values:
- **`INFLUX_READ_WRITE_TOKEN`**: An InfluxDB token with _read_ permission to the bucket.
- **`BUCKET_NAME`**: The name of the InfluxDB bucket to query.
### Execute a query
To execute an SQL query, call the query client's `execute(query)` method and pass the query as a string.
#### Syntax {#execute-query-syntax}
```py
execute(query: str, call_options: Optional[FlightSQLCallOptions] = None)
```
#### Example {#execute-query-example}
```py
# query-example.py
from flightsql import FlightSQLClient
client = FlightSQLClient(host='cloud2.influxdata.com',
token='INFLUX_READ_WRITE_TOKEN',
metadata={'database': 'BUCKET_NAME'},
features={'metadata-reflection': 'true'})
# Execute the query
info = client.execute("SELECT * FROM home")
```
Replace the following:
- **`INFLUX_READ_WRITE_TOKEN`**: An InfluxDB token with _read_ permission to the bucket.
- **`BUCKET_NAME`**: The name of the InfluxDB bucket to query.
The response contains a `flight.FlightInfo` object that contains metadata and an `endpoints: [...]` list. Each endpoint contains the following:
- A list of addresses where you can retrieve the data.
- A `ticket` value that identifies the data to retrieve.
Next, use the ticket to [retrieve data for Flight SQL query results](#retrieve-data-for-flight-sql-query-results)
### Retrieve data for Flight SQL query results
To retrieve Arrow data for a query result, call the client's `do_get(ticket)` method.
#### Syntax {#retrieve-data-syntax}
```py
do_get(ticket, call_options: Optional[FlightSQLCallOptions] = None)
```
#### Example {#retrieve-data-example}
The following sample shows how to use Python with `flightsql-dbapi` and `pyarrow` to query InfluxDB and retrieve data.
```py
# query-example.py
from flightsql import FlightSQLClient
# Instantiate a FlightSQLClient configured for a bucket
client = FlightSQLClient(host='cloud2.influxdata.com',
token='INFLUX_READ_WRITE_TOKEN',
metadata={'database': 'BUCKET_NAME'},
features={'metadata-reflection': 'true'})
# Execute the query to retrieve FlightInfo
info = client.execute("SELECT * FROM home")
# Extract the token for retrieving data
ticket = info.endpoints[0].ticket
# Use the ticket to request the Arrow data stream.
# Return a FlightStreamReader for streaming the results.
reader = client.do_get(ticket)
# Read all data to a pyarrow.Table
table = reader.read_all()
```
`do_get(ticket)` returns a [`pyarrow.flight.FlightStreamReader`](https://arrow.apache.org/docs/python/generated/pyarrow.flight.FlightStreamReader.html) for streaming Arrow [record batches](https://arrow.apache.org/docs/python/data.html#record-batches).
To read data from the stream, call one of the following `FlightStreamReader` methods:
- `read_all()`: Read all record batches as a [`pyarrow.Table`](https://arrow.apache.org/docs/python/generated/pyarrow.Table.html).
- `read_chunk()`: Read the next RecordBatch and metadata.
- `read_pandas()`: Read all record batches and convert them to a [`pandas.DataFrame`](https://pandas.pydata.org/docs/reference/frame.html).
Next, learn how to use Python tools to work with time series data:
- [Use PyArrow](/influxdb/cloud-serverless/query-data/tools/pyarrow/)
- [Use pandas](/influxdb/cloud-serverless/query-data/tools/pandas/)

View File

@ -0,0 +1,22 @@
---
title: Query data with InfluxQL
description: >
Learn to use InfluxQL to query data stored in InfluxDB Cloud Serverless.
menu:
influxdb_cloud_serverless:
name: Query with InfluxQL
parent: Query data
weight: 102
influxdb/cloud-serverless/tags: [query, influxql]
cascade:
related:
- /influxdb/cloud-serverless/reference/influxql
---
Learn to use InfluxQL to query data stored in InfluxDB Cloud Serverless.
{{< children type="anchored-list" >}}
---
{{< children readmore=true hr=true >}}

View File

@ -0,0 +1,355 @@
---
title: Map databases and retention policies to buckets
description: >
To query an an InfluxDB Cloud Serverless bucket with InfluxQL, first map each
database and retention policy (DBRP) combination to a bucket.
menu:
influxdb_cloud_serverless:
name: DBRP mappings
parent: Query with InfluxQL
weight: 101
---
InfluxQL requires a database and retention policy (DBRP) combination in order to query data.
In {{< cloud-name >}}, databases and retention policies are
combined and replaced by InfluxDB [buckets](/influxdb/cloud-serverless/reference/glossary/#bucket).
To query an {{< cloud-name >}} bucket with InfluxQL, first map each DBRP
combination to a bucket.
- [Automatic DBRP mapping](#automatic-dbrp-mapping)
- [Create DBRP mappings](#create-dbrp-mappings)
- [List DBRP mappings](#list-dbrp-mappings)
- [Update a DBRP mapping](#update-a-dbrp-mapping)
- [Delete a DBRP mapping](#delete-a-dbrp-mapping)
## Automatic DBRP mapping
{{< cloud-name >}} automatically creates DBRP mappings for you during the
following operations:
- Writing to the [`/write` v1 compatibility endpoint](/influxdb/cloud-servereless/reference/api/influxdb-1x/write/)
- [Upgrading from InfluxDB 1.x to InfluxDB Cloud](/influxdb/v2.7/upgrade/v1-to-cloud/)
For more information, see [Database and retention policy mapping](/influxdb/cloud-serverless/api/#tag/DBRPs).
## Create DBRP mappings
Use the [`influx` CLI](/influxdb/cloud-serverless/reference/cli/influx/) or the
[InfluxDB API](/influxdb/cloud-serverless/reference/api/) to create DBRP mappings.
{{% note %}}
#### A DBRP combination can only be mapped to a single bucket
Each unique DBRP combination can only be mapped to a single bucket.
If you map a DBRP combination that is already mapped to another bucket,
it will overwrite the existing DBRP mapping.
{{% /note %}}
{{< tabs-wrapper >}}
{{% tabs %}}
[influx CLI](#)
[InfluxDB API](#)
{{% /tabs %}}
{{% tab-content %}}
Use the [`influx v1 dbrp create` command](/influxdb/cloud-serverless/reference/cli/influx/v1/dbrp/create/)
to map a database and retention policy to a bucket.
Include the following:
{{< req type="key" >}}
- {{< req "\*" >}} **API token** to authenticate. We recommend setting your token to
your active InfluxDB connection configuration in the `influx` CLI, so you don't
have to add these parameters to each command.
To set up your active InfluxDB configuration, see
[`influx config set`](/influxdb/cloud-serverless/reference/cli/influx/config/set/).
- {{< req "\*" >}} **database name** to map
- {{< req "\*" >}} **retention policy** name to map
- {{< req "\*" >}} [Bucket ID](/influxdb/cloud-serverless/admin/buckets/view-buckets/#view-buckets-in-the-influxdb-ui) to map to
- **Default flag** to set the provided retention policy as the default retention policy for the database
{{% code-placeholders "(DATABASE|RETENTION_POLICY|BUCKET|API)_(NAME|TOKEN|ID)" %}}
```sh
influx v1 dbrp create \
--token API_TOKEN \
--db DATABASE_NAME \
--rp RETENTION_POLICY_NAME \
--bucket-id BUCKET_ID \
--default
```
{{% /code-placeholders %}}
{{% /tab-content %}}
{{% tab-content %}}
Use the [`/api/v2/dbrps` API endpoint](/influxdb/cloud-serverless/api/#operation/PostDBRP)
to create a new DBRP mapping.
{{< api-endpoint endpoint="https://cloud2.influxdata.com/api/v2/dbrps" method="POST" api-ref="/influxdb/cloud-serverless/api/#operation/PostDBRP" >}}
Include the following:
- **Request method:** `POST`
- **Headers:**
- **Authorization:** `Token` schema with your InfluxDB [API token](/influxdb/cloud-serverless/admin/tokens/)
- **Content-type:** `application/json`
- **Request body:** JSON object with the following fields:
{{< req type="key" >}}
- {{< req "\*" >}} **bucketID:** [bucket ID](/influxdb/cloud-serverless/admin/buckets/view-buckets/)
- {{< req "\*" >}} **database:** database name
- **default:** set the provided retention policy as the default retention policy for the database
- {{< req "\*" >}} **org** or **orgID:** organization name or [organization ID](/influxdb/cloud-serverless/admin/organizations/view-orgs/#view-your-organization-id)
- {{< req "\*" >}} **retention_policy:** retention policy name
{{% code-placeholders "(DATABASE|RETENTION_POLICY|BUCKET|API|ORG)_(NAME|TOKEN|ID)" %}}
```sh
curl --request POST https://cloud2.influxdata.com/api/v2/dbrps \
--header "Authorization: Token API_TOKEN" \
--header 'Content-type: application/json' \
--data '{
"bucketID": "BUCKET_ID",
"database": "DATABASE_NAME",
"default": true,
"orgID": "ORG_ID",
"retention_policy": "RETENTION_POLICY_NAME"
}'
```
{{% /code-placeholders %}}
{{% /tab-content %}}
{{< /tabs-wrapper >}}
## List DBRP mappings
Use the [`influx` CLI](/influxdb/cloud-serverless/reference/cli/influx/) or the
[InfluxDB HTTP API](/influxdb/cloud-serverless/reference/api/) to list all DBRP
mappings and verify the buckets you want to query are mapped to a database and
retention policy.
{{< tabs-wrapper >}}
{{% tabs %}}
[influx CLI](#)
[InfluxDB HTTP API](#)
{{% /tabs %}}
{{% tab-content %}}
Use the [`influx v1 dbrp list` command](/influxdb/cloud-serverless/reference/cli/influx/v1/dbrp/list/)
to list DBRP mappings.
##### View all DBRP mappings
{{% code-placeholders "(DATABASE|RETENTION_POLICY|BUCKET|API|ORG)_(NAME|TOKEN|ID)" %}}
```sh
influx v1 dbrp list --token API_TOKEN
```
##### Filter DBRP mappings by database
```sh
influx v1 dbrp list \
--token API_TOKEN \
--db DATABASE_NAME
```
##### Filter DBRP mappings by bucket ID
```sh
influx v1 dbrp list \
--token API_TOKEN \
--bucket-id BUCKET_ID
```
{{% /code-placeholders %}}
{{% /tab-content %}}
{{% tab-content %}}
Use the [`/api/v2/dbrps` API endpoint](/influxdb/cloud-serverless/api/#operation/GetDBRPs) to list DBRP mappings.
{{< api-endpoint endpoint="https://cloud2.influxdata.com/api/v2/dbrps" method="GET" api-ref="/influxdb/cloud-serverless/api/#operation/GetDBRPs" >}}
Include the following:
- **Request method:** `GET`
- **Headers:**
- **Authorization:** `Token` schema with your InfluxDB [API token](/influxdb/cloud-serverless/admin/tokens/)
- **Query parameters:**
{{< req type="key" >}}
- {{< req "\*" >}} **orgID:** [organization ID](/influxdb/cloud-serverless/admin/organizations/view-orgs/#view-your-organization-id)
- **bucketID:** [bucket ID](/influxdb/cloud-serverless/admin/buckets/view-buckets/) _(to list DBRP mappings for a specific bucket)_
- **database:** database name _(to list DBRP mappings with a specific database name)_
- **rp:** retention policy name _(to list DBRP mappings with a specific retention policy name)_
- **id:** DBRP mapping ID _(to list a specific DBRP mapping)_
{{% code-placeholders "(DATABASE|RETENTION_POLICY|BUCKET|API|ORG)_(NAME|TOKEN|ID)" %}}
##### View all DBRP mappings
```sh
curl --request GET \
https://cloud2.influxdata.com/api/v2/dbrps \
--header "Authorization: Token API_TOKEN" \
--data-urlencode "orgID=ORG_ID"
```
##### Filter DBRP mappings by database
```sh
curl --request GET \
https://cloud2.influxdata.com/api/v2/dbrps \
--header "Authorization: Token API_TOKEN" \
--data-urlencode "orgID=ORG_ID" \
--data-urlencode "db=DATABASE_NAME"
```
##### Filter DBRP mappings by bucket ID
```sh
curl --request GET \
https://cloud2.influxdata.com/api/v2/dbrps \
--header "Authorization: Token API_TOKEN" \
--data-urlencode "orgID=ORG_ID" \
--data-urlencode "bucketID=BUCKET_ID"
```
{{% /code-placeholders %}}
{{% /tab-content %}}
{{% /tabs-wrapper %}}
## Update a DBRP mapping
Use the [`influx` CLI](/influxdb/cloud-serverless/reference/cli/influx/) or the
[InfluxDB HTTP API](/influxdb/cloud-serverless/reference/api/) to update a DBRP mapping.
{{< tabs-wrapper >}}
{{% tabs %}}
[influx CLI](#)
[InfluxDB HTTP API](#)
{{% /tabs %}}
{{% tab-content %}}
Use the [`influx v1 dbrp update` command](/influxdb/cloud-serverless/reference/cli/influx/v1/dbrp/update/)
to update a DBRP mapping.
Include the following:
{{< req type="key" >}}
- {{< req "\*" >}} **API token** to authenticate. We recommend setting your token to
your active InfluxDB connection configuration in the influx CLI, so you don't
have to add these parameters to each command.
To set up your active InfluxDB configuration, see
[`influx config set`](/influxdb/cloud-serverless/reference/cli/influx/config/set/).
- {{< req "\*" >}} **DBRP mapping ID** to update
- **Retention policy** name to update to
- **Default flag** to set the retention policy as the default retention policy for the database
##### Update the default retention policy
{{% code-placeholders "(DBRP|RETENTION_POLICY|API)_(NAME|TOKEN|ID)" %}}
```sh
influx v1 dbrp update \
--token API_TOKEN \
--id DBRP_ID \
--rp RETENTION_POLICY_NAME \
--default
```
{{% /code-placeholders %}}
{{% /tab-content %}}
{{% tab-content %}}
Use the [`/api/v2/dbrps/{dbrpID}` API endpoint](/influxdb/cloud-serverless/api/#operation/GetDBRPs) to update DBRP mappings.
{{< api-endpoint endpoint="https://cloud2.influxdata.com/api/v2/dbrps/{dbrpID}" method="PATCH" api-ref="/influxdb/cloud-serverless/api/#operation/PatchDBRPID" >}}
Include the following:
{{< req type="key" >}}
- **Request method:** `PATCH`
- **Headers:**
- {{< req "\*" >}} **Authorization:** `Token` schema with your InfluxDB [API token](/influxdb/cloud-serverless/admin/tokens/)
- **Path parameters:**
- {{< req "\*" >}} **id:** DBRP mapping ID to update
- **Query parameters:**
- {{< req "\*" >}} **orgID:** [organization ID](/influxdb/cloud-serverless/admin/organizations/view-orgs/#view-your-organization-id)
- **Request body (JSON):**
- **rp:** retention policy name to update to
- **default:** set the retention policy as the default retention policy for the database
##### Update the default retention policy
{{% code-placeholders "(DBRP|RETENTION_POLICY|API|ORG)_(NAME|TOKEN|ID)" %}}
```sh
curl --request PATCH \
https://cloud2.influxdata.com/api/v2/dbrps/DBRP_ID \
--header "Authorization: Token API_TOKEN" \
--data-urlencode "orgID=ORG_ID" \
--data '{
"rp": "RETENTION_POLICY_NAME",
"default": true
}'
```
{{% /code-placeholders %}}
{{% /tab-content %}}
{{% /tabs-wrapper %}}
## Delete a DBRP mapping
Use the [`influx` CLI](/influxdb/cloud-serverless/reference/cli/influx/) or the
[InfluxDB API](/influxdb/cloud-serverless/reference/api/) to delete a DBRP mapping.
{{< tabs-wrapper >}}
{{% tabs %}}
[influx CLI](#)
[InfluxDB API](#)
{{% /tabs %}}
{{% tab-content %}}
Use the [`influx v1 dbrp delete` command](/influxdb/cloud-serverless/reference/cli/influx/v1/dbrp/delete/)
to delete a DBRP mapping.
Include the following:
{{< req type="key" >}}
- {{< req "\*" >}} **API token** to authenticate. We recommend setting your token to
your active InfluxDB connection configuration in the influx CLI, so you don't
have to add these parameters to each command.
To set up your active InfluxDB configuration, see
[`influx config set`](/influxdb/cloud-serverless/reference/cli/influx/config/set/).
- {{< req "\*" >}} **DBRP mapping ID** to delete
{{% code-placeholders "(DBRP|API)_(TOKEN|ID)" %}}
```sh
influx v1 dbrp delete \
--token API_TOKEN \
--id DBRP_ID
```
{{% /code-placeholders %}}
{{% /tab-content %}}
{{% tab-content %}}
Use the [`/api/v2/dbrps/{dbrpID}` API endpoint](/influxdb/cloud-serverless/api/#operation/DeleteDBRPID)
to delete a DBRP mapping.
{{< api-endpoint endpoint="https://cloud2.influxdata.com/api/v2/dbrps/{dbrpID}" method="DELETE" api-ref="/influxdb/cloud-serverless/api/#operation/DeleteDBRPID" >}}
Include the following:
{{< req type="key" >}}
- **Request method:** `PATCH`
- **Headers:**
- {{< req "\*" >}} **Authorization:** `Token` schema with your InfluxDB
[API token](/influxdb/cloud-serverless/admin/tokens/)
- **Path parameters:**
- {{< req "\*" >}} **id:** DBRP mapping ID to update
- **Query parameters:**
- {{< req "\*" >}} **orgID:** [organization ID](/influxdb/cloud-serverless/admin/organizations/view-orgs/#view-your-organization-id)
{{% code-placeholders "(DBRP|API|ORG)_(TOKEN|ID)" %}}
```sh
curl --request DELETE \
https://cloud2.influxdata.com/api/v2/dbrps/DBRP_ID \
--header "Authorization: Token API_TOKEN" \
--data-urlencode "orgID=ORG_ID"
```
{{% /code-placeholders %}}
{{% /tab-content %}}
{{% /tabs-wrapper %}}

View File

@ -0,0 +1,27 @@
---
title: Execute InfluxQL queries
description: >
Use tools and libraries to query data with InfluxQL stored in InfluxDB Cloud Serverless.
weight: 201
menu:
influxdb_cloud_serverless:
name: Execute InfluxQL queries
parent: Query with InfluxQL
identifier: influxql-execute-queries
influxdb/cloud-serverless/tags: [query, influxql]
---
There are multiple ways to execute InfluxQL queries with {{< cloud-name >}}.
Choose from the following options:
{{% note %}}
#### Map databases and retention policies to buckets
Before using InfluxQL, make sure database and retention policy (DBRP)
combinations are mapped to buckets. For more information, see
[Map databases and retention policies to buckets](/influxdb/cloud-serverless/query-data/influxql/dbrp/).
{{% /note %}}
---
{{< children readmore=true hr=true >}}

View File

@ -0,0 +1,135 @@
---
title: Use the InfluxDB v1 HTTP query API to query with InfluxQL
seotitle: Use InfluxQL and InfluxDB v1 HTTP query API
description: >
Use the InfluxDB v1 HTTP query API to query data in InfluxDB Cloud Serverless
with InfluxQL.
weight: 401
menu:
influxdb_cloud_serverless:
parent: influxql-execute-queries
name: Use the v1 query API
influxdb/cloud-serverless/tags: [query, influxql, python]
list_code_example: |
```sh
curl --get https://cloud2.influxdata.com/query \
--header "Authorization: Token API_TOKEN" \
--data-urlencode "db=BUCKET_NAME" \
--data-urlencode "q=SELECT * FROM home"
```
---
Use the InfluxDB v1 HTTP query API to query data in {{< cloud-name >}}
with InfluxQL.
The examples below use **cURL** to send HTTP requests to the InfluxDB v1 HTTP API,
but you can use any HTTP client.
{{% note %}}
#### Databases and retention policies map to InfluxDB buckets
InfluxQL **databases** and **retention policies** are used to route queries to
an InfluxDB **bucket** based on database and retention policy (DBRP) mappings.
For more information, see
[Map databases and retention policies to buckets](/influxdb/cloud-serverless/query-data/influxql/dbrp/).
{{% /note %}}
{{% warn %}}
#### InfluxQL feature support
InfluxQL is being rearchitected to work with the InfluxDB IOx 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 %}}
Use the v1 `/query` endpoint and the `GET` request method to query data with InfluxQL:
{{< api-endpoint endpoint="https://cloud2.influxdata.com/query" method="get" api-ref="/influxdb/cloud-serverless/api/#tag/Query" >}}
Provide the following with your request:
- **Headers:**
- **Authorization:** `Bearer API_TOKEN`
- **Query parameters:**
- **db**: Database to query
- **rp**: _(Optional)_ Retention policy to query
- **q**: URL-encoded InfluxQL query
{{% code-placeholders "DATABASE_NAME|API_TOKEN" %}}
```sh
curl --get https://cloud2.influxdata.com/query \
--header "Authorization: Token API_TOKEN" \
--data-urlencode "db=DATABASE_NAME" \
--data-urlencode "q=SELECT * FROM home"
```
{{% /code-placeholders %}}
Replace the following:
- {{% code-placeholder-key %}}`DATABASE_NAME`{{% /code-placeholder-key %}}:
Name of the database to query
- {{% code-placeholder-key %}}`API_TOKEN`{{% /code-placeholder-key %}}:
InfluxDB token with read permissions on the databases you want to query.
{{% note %}}
#### Authenticate with username and password
If using basic authentication or query string authentication (username and password)
to interact with the v1 HTTP query API, provide the following credentials:
- **username**: Arbitrary string _({{< cloud-name >}} ignores the username)_
- **password**: [API token](/influxdb/cloud-serverless/admin/tokens/) with read permission
on the database you want to query
{{< code-tabs-wrapper >}}
{{% code-tabs %}}
[Basic Auth](#)
[Query String Auth](#)
{{% /code-tabs %}}
{{% code-tab-content %}}
{{% code-placeholders "DATABASE_(NAME|TOKEN)" %}}
```sh
curl --get https://cloud2.influxdata.com/query \
--header "Authorization: Basic ignored:DATABASE_TOKEN" \
--data-urlencode "db=DATABASE_NAME" \
--data-urlencode "q=SELECT * FROM home"
```
{{% /code-placeholders %}}
{{% /code-tab-content %}}
{{% code-tab-content %}}
{{% code-placeholders "DATABASE_(NAME|TOKEN)" %}}
```sh
curl --get https://cloud2.influxdata.com/query \
--data-urlencode "u=ignored" \
--data-urlencode "p=DATABASE_TOKEN" \
--data-urlencode "db=DATABASE_NAME" \
--data-urlencode "q=SELECT * FROM home"
```
{{% /code-placeholders %}}
{{% /code-tab-content %}}
{{< /code-tabs-wrapper >}}
{{% /note %}}
## Return results as JSON or CSV
By default, the `/query` endpoint returns results in **JSON**, but it can also
return results in **CSV**. To return results as CSV, include the `Accept` header
with the `application/csv` or `text/csv` MIME type:
{{% code-placeholders "DATABASE_(NAME|TOKEN)" %}}
```sh
curl --get https://cloud2.influxdata.com/query \
--header "Authorization: Token DATABASE_TOKEN" \
--header "Accept: application/csv" \
--data-urlencode "db=DATABASE_NAME" \
--data-urlencode "q=SELECT * FROM home"
```
{{% /code-placeholders %}}
<!--
TO-DO: Explain how DBRP mappings work with bucket names
-->

View File

@ -0,0 +1,297 @@
---
title: Use Python to query data with InfluxQL
description: >
Use Python and the `influxdb3-python` library to query data stored in InfluxDB
with InfluxQL.
weight: 401
menu:
influxdb_cloud_serverless:
parent: influxql-execute-queries
name: Use Python
identifier: query-with-python-influxql
influxdb/cloud-serverless/tags: [query, influxql, python]
related:
- /influxdb/cloud-serverless/query-data/tools/pandas/
- /influxdb/cloud-serverless/query-data/tools/pyarrow/
- /influxdb/cloud-serverless/reference/influxql/
list_code_example: |
```py
from influxdb_client_3 import InfluxDBClient3
# Instantiate an InfluxDB client
client = InfluxDBClient3(
host='cloud2.influxdata.com',
org='ORG_NAME',
token='DATABASE_TOKEN',
database='DATABASE_NAME'
)
# Execute the query and return an Arrow table
table = client.query(
query="SELECT * FROM home",
language="influxql"
)
# Return query results as a markdown table
print(table.to_pandas().to_markdown())
```
---
Use the `influxdb3-python` client library to query data stored in InfluxDB with InfluxQL.
The `influxdb3-client` uses Flight SQL to query data from InfluxDB and return
results in Apache Arrow format.
- [Get started using Python to query InfluxDB](#get-started-using-python-to-query-influxdb)
- [Create a Python virtual environment](#create-a-python-virtual-environment)
- [Install Python](#install-python)
- [Create a project virtual environment](#venv-install)
- [Install Anaconda](?t=Anaconda#conda-install)
- [Query InfluxDB](#query-influxdb)
- [Install the influxdb3-python library](#install-the-influxdb3-python-library)
- [Create an InfluxDB client](#create-an-influxdb-client)
- [Execute a query](#execute-a-query)
{{% note %}}
#### Databases and retention policies map to InfluxDB buckets
InfluxQL **databases** and **retention policies** are used to route queries to
an InfluxDB **bucket** based on database and retention policy (DBRP) mappings.
For more information, see
[Map databases and retention policies to buckets](/influxdb/cloud-serverless/query-data/influxql/dbrp/).
{{% /note %}}
{{% warn %}}
#### InfluxQL feature support
InfluxQL is being rearchitected to work with the InfluxDB IOx 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 %}}
## Get started using Python to query InfluxDB
This guide follows the recommended practice of using Python _virtual environments_.
If you don't want to use virtual environments and you have Python installed,
continue to [Query InfluxDB](#query-influxdb).
## Create a Python virtual environment
Python [virtual environments](https://docs.python.org/3/library/venv.html) keep
the Python interpreter and dependencies for your project self-contained and isolated from other projects.
To install Python and create a virtual environment, choose one of the following options:
- [Python venv](?t=venv#venv-install): The [`venv` module](https://docs.python.org/3/library/venv.html) comes standard in Python as of version 3.5.
- [Anaconda® Distribution](?t=Anaconda#conda-install): A Python/R data science distribution that provides Python and the **conda** package and environment manager.
{{< tabs-wrapper >}}
{{% tabs "small" %}}
[venv]()
[Anaconda]()
{{% /tabs %}}
{{% tab-content %}}
<!--------------------------------- Begin venv -------------------------------->
### Install Python
1. Follow the [Python installation instructions](https://wiki.python.org/moin/BeginnersGuide/Download)
to install a recent version of the Python programming language for your system.
2. Check that you can run `python` and `pip` commands.
`pip` is a package manager included in most Python distributions.
In your terminal, enter the following commands:
```sh
python --version
```
```sh
pip --version
```
Depending on your system, you may need to use version-specific commands--for example.
```sh
python3 --version
```
```sh
pip3 --version
```
If neither `pip` nor `pip<PYTHON_VERSION>` works, follow one of the [Pypa.io Pip installation](https://pip.pypa.io/en/stable/installation/) methods for your system.
### Create a project virtual environment {#venv-install}
1. Create a directory for your Python project and change to the new directory--for example:
```sh
mkdir ./PROJECT_DIRECTORY && cd $_
```
2. Use the Python `venv` module to create a virtual environment--for example:
```sh
python -m venv envs/virtualenv-1
```
`venv` creates the new virtual environment directory in your project.
3. To activate the new virtual environment in your terminal, run the `source` command and pass the file path of the virtual environment `activate` script:
```sh
source envs/VIRTUAL_ENVIRONMENT_NAME/bin/activate
```
For example:
```sh
source envs/virtualenv-1/bin/activate
```
<!---------------------------------- End venv --------------------------------->
{{% /tab-content %}}
{{% tab-content %}}
<!-------------------------------- Begin conda -------------------------------->
### Install Anaconda {#conda-install}
1. Follow the [Anaconda installation instructions](https://docs.continuum.io/anaconda/install/) for your system.
2. Check that you can run the `conda` command:
```sh
conda
```
3. Use `conda` to create a virtual environment--for example:
```sh
conda create --prefix envs/virtualenv-1
```
`conda` creates a virtual environment in a directory named `./envs/virtualenv-1`.
4. To activate the new virtual environment, use the `conda activate` command and pass the directory path of the virtual environment:
```sh
conda activate envs/VIRTUAL_ENVIRONMENT_NAME
```
For example:
```sh
conda activate ./envs/virtualenv-1
```
<!--------------------------------- END conda --------------------------------->
{{% /tab-content %}}
{{< /tabs-wrapper >}}
When a virtual environment is activated, the name displays at the beginning of your terminal command line--for example:
{{% code-callout "(virtualenv-1)"%}}
```sh
(virtualenv-1) $ PROJECT_DIRECTORY
```
{{% /code-callout %}}
## Query InfluxDB
1. [Install the influxdb3-python library](#install-the-influxdb3-python-library)
2. [Create an InfluxDB client](#create-an-influxdb-client)
3. [Execute a query](#execute-a-query)
### Install the influxdb3-python library
The `influxdb_client_3` module provides a simple and convenient way to interact
with {{< cloud-name >}} using Python. This module supports both writing data to
InfluxDB and querying data using SQL or InfluxQL queries.
Installing `inflxudb3-python` also installs the
[`pyarrow`](https://arrow.apache.org/docs/python/index.html) library that you'll
use for working with Arrow data returned from queries.
In your terminal, use `pip` to install `influxdb3-python`:
```sh
pip install influxdb3-python
```
With `influxdb3-python` and `pyarrow` installed, you're ready to query and
analyze data stored in an InfluxDB database.
### Create an InfluxDB client
The following example shows how to use Python with `influxdb3-python`
and to instantiate a client configured for an InfluxDB database.
In your editor, copy and paste the following sample code to a new file--for
example, `query-example.py`:
{{% code-placeholders "(DATABASE|ORG)_(NAME|TOKEN)" %}}
```py
# query-example.py
from influxdb_client_3 import InfluxDBClient3
# Instantiate an InfluxDBClient3 client configured for your database
client = InfluxDBClient3(
host='cloud2.influxdata.com',
org='ORG_NAME',
token='DATABASE_TOKEN',
database='DATABASE_NAME'
)
```
{{% /code-placeholders %}}
Replace the following configuration values:
- {{% code-placeholder-key %}}`DATABASE_TOKEN`{{% /code-placeholder-key %}}:
Your InfluxDB token with read permissions on the databases you want to query.
- {{% code-placeholder-key %}}`DATABASE_NAME`{{% /code-placeholder-key %}}:
The name of your InfluxDB database.
### Execute a query
To execute an InfluxQL query, call the client's `query(query,language)` method
and specify the following arguments:
- **query**: InfluxQL query string to execute.
- **language**: `influxql`
#### Syntax {#execute-query-syntax}
```py
query(query: str, language: str)
```
#### Example {#execute-query-example}
{{% code-placeholders "(DATABASE|ORG)_(NAME|TOKEN)" %}}
```py
# query-example.py
from influxdb_client_3 import InfluxDBClient3
client = InfluxDBClient3(
host='cloud2.influxdata.com',
org='ORG_NAME',
token='DATABASE_TOKEN',
database='DATABASE_NAME'
)
# Execute the query and return an Arrow table
table = client.query(
query="SELECT * FROM home",
language="influxql"
)
# Return query results as a markdown table
print(table.to_pandas().to_markdown())
```
{{% /code-placeholders %}}
Next, learn how to use Python tools to work with time series data:
- [Use PyArrow](/influxdb/cloud-serverless/query-data/tools/pyarrow/)
- [Use pandas](/influxdb/cloud-serverless/query-data/tools/pandas/)

View File

@ -9,6 +9,9 @@ menu:
parent: Query data
weight: 101
influxdb/cloud-serverless/tags: [query, sql]
cascade:
related:
- /influxdb/cloud-serverless/reference/sql/
---
Use SQL to query data stored in an InfluxDB Cloud Serverless bucket.

View File

@ -0,0 +1,32 @@
---
title: Execute SQL queries
seotitle: Execute SQL queries for data in InfluxDB Cloud Serverless
description: >
Use tools and libraries to query data with SQL stored in InfluxDB Cloud Serverless.
weight: 103
menu:
influxdb_cloud_serverless:
name: Execute SQL queries
parent: Query with SQL
influxdb/cloud-serverless/tags: [query]
aliases:
- /influxdb/cloud-serverless/query-data/execute-queries/
---
The InfluxDB SQL implementation uses [Arrow DataFusion](https://arrow.apache.org/datafusion/)
and the [Apache Arrow Flight SQL](https://arrow.apache.org/) protocol to query
data stored in an InfluxDB database.
> Arrow Flight SQL is a protocol for interacting with SQL databases using the
> [Arrow in-memory format](https://arrow.apache.org/docs/format/Columnar.html)
> and the [Flight RPC](https://arrow.apache.org/docs/format/Flight.html) framework.
>
> {{% caption %}}[Apache Arrow Flight SQL documentation](https://arrow.apache.org/docs/format/FlightSql.html){{% /caption %}}
Data platforms and clients that support the Flight SQL protocol can query data
stored in an InfluxDB database.
Learn how to connect to InfluxDB and query your data using the following tools:
---
{{< children readmore=true hr=true hlevel="h2" >}}

View File

@ -1,13 +1,15 @@
---
title: Query in Data Explorer
title: Use the InfluxDB Data Explorer to query data
description: >
Query your data in the InfluxDB user interface (UI) Data Explorer.
weight: 201
menu:
influxdb_cloud_serverless:
name: Query with Data Explorer
parent: Execute queries
influxdb_cloud_serverless:
name: Use the Data Explorer
parent: Execute SQL queries
influxdb/cloud-serverless/tags: [query]
aliases:
- /influxdb/cloud-serverless/query-data/execute-queries/data-explorer/
related:
- /influxdb/cloud-serverless/query-data/sql/
- /influxdb/cloud-serverless/query-data/flux-sql/

View File

@ -6,12 +6,28 @@ description: >
menu:
influxdb_cloud_serverless:
name: Use Flux & SQL
parent: Query data
parent: Execute SQL queries
weight: 204
aliases:
- /influxdb/cloud-serverless/query-data/flux-sql/
related:
- /influxdb/cloud-serverless/get-started/query/
- /influxdb/cloud-serverless/query-data/sql/
influxdb/cloud-serverless/tags: [sql, flux, query]
list_code_example: |
```js
import "experimental/iox"
query = "
SELECT *
FROM home
WHERE
time >= '2022-01-01T08:00:00Z'
AND time < '2022-01-01T20:00:00Z'
"
iox.sql(bucket: "get-started", query: query)
```
---
InfluxDB Cloud Serverless supports both [Flux](/flux/v0.x/) and

View File

@ -6,10 +6,12 @@ description: >
weight: 101
menu:
influxdb_cloud_serverless:
parent: Query with Flight SQL
parent: Execute SQL queries
name: Use Java
identifier: query_with_java
influxdb/cloud-serverless/tags: [query, flightsql, java]
aliases:
- /influxdb/cloud-serverless/query-data/execute-queries/flight-sql/java/
related:
- /influxdb/cloud-serverless/query-data/sql/
list_code_example: |

View File

@ -0,0 +1,288 @@
---
title: Use Python to query data with SQL
description: >
Use Python and the `influxdb3-python` library to query data stored in InfluxDB
with SQL.
weight: 101
menu:
influxdb_cloud_serverless:
parent: Execute SQL queries
name: Use Python
identifier: query_with_python
aliases:
- content/influxdb/cloud-serverless/query-data/execute-queries/flight-sql/python/
influxdb/cloud-serverless/tags: [query, flightsql, python, sql]
related:
- /influxdb/cloud-serverless/query-data/tools/pandas/
- /influxdb/cloud-serverless/query-data/tools/pyarrow/
- /influxdb/cloud-serverless/query-data/sql/
list_code_example: |
```py
from influxdb_client_3 import InfluxDBClient3
# Instantiate an InfluxDB client
client = InfluxDBClient3(
host='cloud2.influxdata.com',
org='ORG_NAME',
token='DATABASE_TOKEN',
database='DATABASE_NAME'
)
# Execute the query and return an Arrow table
table = client.query(
query="SELECT * FROM home",
language="sql"
)
# Return query results as a markdown table
print(table.to_pandas().to_markdown())
```
---
Use the `influxdb3-python` client library to query data stored in InfluxDB with SQL.
The `influxdb3-client` uses Flight SQL to query data from InfluxDB and return
results in Apache Arrow format.
- [Get started using Python to query InfluxDB](#get-started-using-python-to-query-influxdb)
- [Create a Python virtual environment](#create-a-python-virtual-environment)
- [Install Python](#install-python)
- [Create a project virtual environment](#venv-install)
- [Install Anaconda](?t=Anaconda#conda-install)
- [Query InfluxDB](#query-influxdb)
- [Install the influxdb3-python library](#install-the-influxdb3-python-library)
- [Create an InfluxDB client](#create-an-influxdb-client)
- [Execute a query](#execute-a-query)
## Get started using Python to query InfluxDB
This guide follows the recommended practice of using Python _virtual environments_.
If you don't want to use virtual environments and you have Python installed,
continue to [Query InfluxDB](#query-influxdb).
## Create a Python virtual environment
Python [virtual environments](https://docs.python.org/3/library/venv.html) keep
the Python interpreter and dependencies for your project self-contained and isolated from other projects.
To install Python and create a virtual environment, choose one of the following options:
- [Python venv](?t=venv#venv-install): The [`venv` module](https://docs.python.org/3/library/venv.html) comes standard in Python as of version 3.5.
- [Anaconda® Distribution](?t=Anaconda#conda-install): A Python/R data science distribution that provides Python and the **conda** package and environment manager.
{{< tabs-wrapper >}}
{{% tabs "small" %}}
[venv]()
[Anaconda]()
{{% /tabs %}}
{{% tab-content %}}
<!--------------------------------- Begin venv -------------------------------->
### Install Python
1. Follow the [Python installation instructions](https://wiki.python.org/moin/BeginnersGuide/Download)
to install a recent version of the Python programming language for your system.
2. Check that you can run `python` and `pip` commands.
`pip` is a package manager included in most Python distributions.
In your terminal, enter the following commands:
```sh
python --version
```
```sh
pip --version
```
Depending on your system, you may need to use version-specific commands--for example.
```sh
python3 --version
```
```sh
pip3 --version
```
If neither `pip` nor `pip<PYTHON_VERSION>` works, follow one of the [Pypa.io Pip installation](https://pip.pypa.io/en/stable/installation/) methods for your system.
### Create a project virtual environment {#venv-install}
1. Create a directory for your Python project and change to the new directory--for example:
```sh
mkdir ./PROJECT_DIRECTORY && cd $_
```
2. Use the Python `venv` module to create a virtual environment--for example:
```sh
python -m venv envs/virtualenv-1
```
`venv` creates the new virtual environment directory in your project.
3. To activate the new virtual environment in your terminal, run the `source` command and pass the file path of the virtual environment `activate` script:
```sh
source envs/VIRTUAL_ENVIRONMENT_NAME/bin/activate
```
For example:
```sh
source envs/virtualenv-1/bin/activate
```
<!---------------------------------- End venv --------------------------------->
{{% /tab-content %}}
{{% tab-content %}}
<!-------------------------------- Begin conda -------------------------------->
### Install Anaconda {#conda-install}
1. Follow the [Anaconda installation instructions](https://docs.continuum.io/anaconda/install/) for your system.
2. Check that you can run the `conda` command:
```sh
conda
```
3. Use `conda` to create a virtual environment--for example:
```sh
conda create --prefix envs/virtualenv-1
```
`conda` creates a virtual environment in a directory named `./envs/virtualenv-1`.
4. To activate the new virtual environment, use the `conda activate` command and pass the directory path of the virtual environment:
```sh
conda activate envs/VIRTUAL_ENVIRONMENT_NAME
```
For example:
```sh
conda activate ./envs/virtualenv-1
```
<!--------------------------------- END conda --------------------------------->
{{% /tab-content %}}
{{< /tabs-wrapper >}}
When a virtual environment is activated, the name displays at the beginning of your terminal command line--for example:
{{% code-callout "(virtualenv-1)"%}}
```sh
(virtualenv-1) $ PROJECT_DIRECTORY
```
{{% /code-callout %}}
## Query InfluxDB
1. [Install the influxdb3-python library](#install-the-influxdb3-python-library)
2. [Create an InfluxDB client](#create-an-influxdb-client)
3. [Execute a query](#execute-a-query)
### Install the influxdb3-python library
The `influxdb_client_3` module provides a simple and convenient way to interact
with {{< cloud-name >}} using Python. This module supports both writing data to
InfluxDB and querying data using SQL or InfluxQL queries.
{{% note %}}
_To query data with **InfluxQL** and Python, see
[Use InfluxQL with Python](/influxdb/cloud-serverless/query-data/influxql/execute-queries/python/)._
{{% /note %}}
Installing `inflxudb3-python` also installs the
[`pyarrow`](https://arrow.apache.org/docs/python/index.html) library that you'll
use for working with Arrow data returned from queries.
In your terminal, use `pip` to install `influxdb3-python`:
```sh
pip install influxdb3-python
```
With `influxdb3-python` and `pyarrow` installed, you're ready to query and
analyze data stored in an InfluxDB database.
### Create an InfluxDB client
The following example shows how to use Python with `influxdb3-python`
and to instantiate a client configured for an InfluxDB database.
In your editor, copy and paste the following sample code to a new file--for
example, `query-example.py`:
{{% code-placeholders "(DATABASE|ORG)_(NAME|TOKEN)" %}}
```py
# query-example.py
from influxdb_client_3 import InfluxDBClient3
# Instantiate an InfluxDBClient3 client configured for your database
client = InfluxDBClient3(
host='cloud2.influxdata.com',
org='ORG_NAME'
token='DATABASE_TOKEN',
database='DATABASE_NAME'
)
```
{{% /code-placeholders %}}
Replace the following configuration values:
- {{% code-placeholder-key %}}`ORG_NAME`{{% /code-placeholder-key %}}:
Your InfluxDB organization name.
- {{% code-placeholder-key %}}`DATABASE_TOKEN`{{% /code-placeholder-key %}}:
Your InfluxDB token with read permissions on the databases you want to query.
- {{% code-placeholder-key %}}`DATABASE_NAME`{{% /code-placeholder-key %}}:
The name of your InfluxDB database.
### Execute a query
To execute an SQL query, call the client's `query(query,language)` method and
specify the following arguments:
- **query**: SQL query string to execute.
- **language**: `sql`
#### Syntax {#execute-query-syntax}
```py
query(query: str, language: str)
```
#### Example {#execute-query-example}
{{% code-placeholders "(DATABASE|ORG)_(NAME|TOKEN)" %}}
```py
# query-example.py
from influxdb_client_3 import InfluxDBClient3
client = InfluxDBClient3(
host='cloud2.influxdata.com',
org='ORG_NAME',
token='DATABASE_TOKEN',
database='DATABASE_NAME'
)
# Execute the query and return an Arrow table
table = client.query(
query="SELECT * FROM home",
language="sql"
)
# Return query results as a markdown table
print(table.to_pandas().to_markdown())
```
{{% /code-placeholders %}}
Next, learn how to use Python tools to work with time series data:
- [Use PyArrow](/influxdb/cloud-serverless/query-data/tools/pyarrow/)
- [Use pandas](/influxdb/cloud-serverless/query-data/tools/pandas/)

View File

@ -7,10 +7,12 @@ description: >
weight: 101
menu:
influxdb_cloud_serverless:
parent: Query with Flight SQL
parent: Execute SQL queries
name: Use Superset
identifier: query_with_superset
influxdb/cloud-serverless/tags: [query, flightsql, superset]
aliases:
- content/influxdb/cloud-serverless/query-data/execute-queries/flight-sql/superset/
related:
- /influxdb/cloud-serverless/visualize-data/superset/
---

View File

@ -0,0 +1,778 @@
---
title: InfluxQL reference
list_title: InfluxQL
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
---
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 IOx 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)
<!-- To learn more about InfluxQL, browse the following topics:
- [Explore your data with InfluxQL](/influxdb/v2.7/query-data/influxql/explore-data/)
- [Explore your schema with InfluxQL](/influxdb/v2.7/query-data/influxql/explore-schema/)
- [Database management](/influxdb/v2.7/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 (i.e. `\"`).
- 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.7/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 (i.e., `\'`).
```
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_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
- auxillary 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 curren
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 .
```
## 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

@ -0,0 +1,197 @@
---
title: InfluxQL feature support
description: >
InfluxQL is being rearchitected to work with the InfluxDB IOx 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.
menu:
influxdb_cloud_serverless:
parent: influxql-reference
weight: 220
---
InfluxQL is being rearchitected to work with the InfluxDB IOx 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)
- [Time zones](#time-zones)
- [Subqueries](#subqueries)
- [SLIMIT clause](#slimit-clause)
- [SOFFSET clause](#soffset-clause)
- [Project additional fields with selector functions](#project-additional-fields-with-selector-functions)
- [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
### Time zones
InfluxQL in {{< cloud-name >}} does not currently support the time zone clause,
which applies a time zone offset to UTC timestamps in query results.
**Tracking issue**: [influxdb_iox#6933](https://github.com/influxdata/influxdb_iox/issues/6933)
### Subqueries
InfluxQL in {{< cloud-name >}} does not currently support subqueries, which
let you query data from the results of another InfluxQL query.
**Tracking issue**: [influxdb_iox#6897](https://github.com/influxdata/influxdb_iox/issues/6897)
### SLIMIT clause
InfluxQL in {{< cloud-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 {{< cloud-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)
### Project additional fields with selector functions
InfluxQL in {{< cloud-name >}} does not currently let you project additional
fields when using [selector functions](/influxdb/cloud-serverless/reference/influxql/functions/selectors/).
Selector functions return specific rows with values that meets the criteria
of the function. Projecting other fields returns additional field values associated
with the selected row and timestamp. For example:
```sql
SELECT MAX(co), temp, hum FROM home
```
This query selects the row with the maximum `co` value and should return the
`temp` and `hum` value currently associated with that row.
This query currently returns an error.
**Tracking issue**: [influxdb_iox#7533](https://github.com/influxdata/influxdb_iox/issues/7533)
### 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
{{< cloud-name >}}:
| Metaquery | Supported |
| :------------------------------------------------------------ | :----------------------: |
| <span style="opacity: .5;">SHOW DATABASES</span> | |
| **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 IOx storage engine, series cardinality is no longer a limiting
factor for database performance.
Cardinality-related metaqueries will likely not be supported with the IOx
storage engine.
{{% /note %}}
## Function support
### Aggregate functions
| Function | Supported | Tracking Issue |
| :----------------------------------------------------------------------------------------- | :----------------------: | :-------------------------------------------------------------------------- |
| [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> | | [influxdb_iox#6937](https://github.com/influxdata/influxdb_iox/issues/6937) |
| [MEAN()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#mean) | **{{< icon "check" >}}** | |
| [MEDIAN()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#median) | **{{< icon "check" >}}** | |
| <span style="opacity: .5;">MODE()</span> | | [influxdb_iox#7334](https://github.com/influxdata/influxdb_iox/issues/7334) |
| <span style="opacity: .5;">SPREAD()</span> | | [influxdb_iox#6937](https://github.com/influxdata/influxdb_iox/issues/6937) |
| [STDDEV()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#stddev) | **{{< icon "check" >}}** | |
| [SUM()](/influxdb/cloud-serverless/reference/influxql/functions/aggregates/#sum) | **{{< icon "check" >}}** | |
### Selector functions
| Function | Supported | Tracking Issue |
| :---------------------------------------------------------------------------------- | :----------------------: | :-------------------------------------------------------------------------- |
| <span style="opacity: .5;">BOTTOM()</span> | | [influxdb_iox#6935](https://github.com/influxdata/influxdb_iox/issues/6935) |
| [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" >}}** | |
| <span style="opacity: .5;">PERCENTILE()</span> | | [influxdb_iox#7664](https://github.com/influxdata/influxdb_iox/issues/7664) |
| <span style="opacity: .5;">SAMPLE()</span> | | [influxdb_iox#6935](https://github.com/influxdata/influxdb_iox/issues/6935) |
| <span style="opacity: .5;">TOP()</span> | | [influxdb_iox#7650](https://github.com/influxdata/influxdb_iox/issues/7650) |
### Transformations
| Function | Supported | Tracking Issue |
| :---------------------------------------------------------------------------------------- | :----------------------: | :-------------------------------------------------------------------------- |
| [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" >}}** | |
| <span style="opacity: .5;">CUMULATIVE_SUM()<span> | | [influxdb_iox#7467](https://github.com/influxdata/influxdb_iox/issues/7467) |
| <span style="opacity: .5;">DERIVATIVE()<span> | | [influxdb_iox#7647](https://github.com/influxdata/influxdb_iox/issues/7647) |
| <span style="opacity: .5;">DIFFERENCE()<span> | | [influxdb_iox#7468](https://github.com/influxdata/influxdb_iox/issues/7468) |
| <span style="opacity: .5;">ELAPSED()<span> | | [influxdb_iox#6934](https://github.com/influxdata/influxdb_iox/issues/6934) |
| [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" >}}** | |
| <span style="opacity: .5;">MOVING_AVERAGE()<span> | | [influxdb_iox#7600](https://github.com/influxdata/influxdb_iox/issues/7600) |
| <span style="opacity: .5;">NON_NEGATIVE_DERIVATIVE()<span> | | [influxdb_iox#7649](https://github.com/influxdata/influxdb_iox/issues/7649) |
| <span style="opacity: .5;">NON_NEGATIVE_DIFFERENCE()<span> | | [influxdb_iox#7628](https://github.com/influxdata/influxdb_iox/issues/7628) |
| [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 | Tracking Issue |
| :-------------------------------------------------------------------- | :-------: | :-------------------------------------------------------------------------- |
| <span style="opacity: .5;">CHANDE_MOMENTUM_OSCILLATOR()</span> | | [influxdb_iox#6939](https://github.com/influxdata/influxdb_iox/issues/6939) |
| <span style="opacity: .5;">DOUBLE_EXPONENTIAL_MOVING_AVERAGE()</span> | | [influxdb_iox#6939](https://github.com/influxdata/influxdb_iox/issues/6939) |
| <span style="opacity: .5;">EXPONENTIAL_MOVING_AVERAGE()</span> | | [influxdb_iox#6939](https://github.com/influxdata/influxdb_iox/issues/6939) |
| <span style="opacity: .5;">HOLT_WINTERS()</span> | | [influxdb_iox#6939](https://github.com/influxdata/influxdb_iox/issues/6939) |
| <span style="opacity: .5;">HOLT_WINTERS_WITH_FIT()</span> | | [influxdb_iox#6939](https://github.com/influxdata/influxdb_iox/issues/6939) |
| <span style="opacity: .5;">KAUFMANS_EFFICIENCY_RATIO()</span> | | [influxdb_iox#6939](https://github.com/influxdata/influxdb_iox/issues/6939) |
| <span style="opacity: .5;">KAUFMANS_ADAPTIVE_MOVING_AVERAGE()</span> | | [influxdb_iox#6939](https://github.com/influxdata/influxdb_iox/issues/6939) |
| <span style="opacity: .5;">RELATIVE_STRENGTH_INDEX()</span> | | [influxdb_iox#6939](https://github.com/influxdata/influxdb_iox/issues/6939) |
| <span style="opacity: .5;">TRIPLE_EXPONENTIAL_MOVING_AVERAGE()</span> | | [influxdb_iox#6939](https://github.com/influxdata/influxdb_iox/issues/6939) |
| <span style="opacity: .5;">TRIPLE_EXPONENTIAL_DERIVATIVE()</span> | | [influxdb_iox#6939](https://github.com/influxdata/influxdb_iox/issues/6939) |
### Date and time functions
| Function | Supported | Tracking Issue |
| :-------------------------------------------------------------------------------- | :----------------------: | :-------------------------------------------------------------------------- |
| [now()](/influxdb/cloud-serverless/reference/influxql/functions/date-time/#now) | **{{< icon "check" >}}** | |
| [time()](/influxdb/cloud-serverless/reference/influxql/functions/date-time/#time) | **{{< icon "check" >}}** | |
| <span style="opacity: .5;">tz()</span> | | [influxdb_iox#6933](https://github.com/influxdata/influxdb_iox/issues/6933) |
### Miscellaneous functions
| Function | Supported | Tracking Issue |
| :-------------------------------------------------------------------------- | :----------------------: | :------------- |
| [fill()](/influxdb/cloud-serverless/reference/influxql/functions/misc/#fill) | **{{< icon "check" >}}** | |

View File

@ -0,0 +1,86 @@
---
title: View InfluxQL functions
description: >
Aggregate, select, transform, and predict data with InfluxQL functions.
menu:
influxdb_cloud_serverless:
name: InfluxQL functions
parent: influxql-reference
identifier: influxql-functions
weight: 208
---
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 IOx 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/)
- [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)
<!-- - [BOTTOM()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#bottom) -->
<!-- - [PERCENTILE()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#percentile) -->
<!-- - [SAMPLE()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#sample) -->
<!-- - [TOP()](/influxdb/cloud-serverless/reference/influxql/functions/selectors/#top) -->
- [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)
- [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)
- [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)
<!-- - [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) -->
<!-- - [ELAPSED()](/influxdb/cloud-serverless/reference/influxql/functions/transformations/#elapsed) -->
<!-- - [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) -->
- [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

@ -0,0 +1,927 @@
---
title: InfluxQL aggregate functions
list_title: Aggregate functions
description: >
Use InfluxQL aggregate functions to aggregate your time series data.
menu:
influxdb_cloud_serverless:
name: Aggregates
parent: influxql-functions
weight: 205
---
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)
- [STDDEV()](#stddev)
- [SUM()](#sum)
<!-- When implemented, place back in alphabetical order -->
<!-- - [INTEGRAL()](#integral) -->
<!-- - [MODE()](#mode) -->
<!-- - [SPREAD()](#spread) -->
{{% note %}}
#### Missing InfluxQL functions
Some InfluxQL functions are in the process of being rearchitected to work with
the InfluxDB IOx 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

@ -0,0 +1,145 @@
---
title: InfluxQL date and time functions
list_title: Date and time functions
description: >
Use InfluxQL date and time functions to perform time-related operations.
menu:
influxdb_cloud_serverless:
name: Date and time
parent: influxql-functions
weight: 206
---
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

@ -0,0 +1,246 @@
---
title: InfluxQL miscellaneous functions
list_title: Miscellaneous functions
description: >
Use InfluxQL miscellaneous functions to perform different operations in
InfluxQL queries.
menu:
influxdb_cloud_serverless:
name: Miscellaneous
identifier: influxql-misc-functions
parent: influxql-functions
weight: 206
---
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 >}} -->

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,612 @@
---
title: GROUP BY clause
description: >
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.
menu:
influxdb_cloud_serverless:
name: GROUP BY clause
identifier: influxql-group-by
parent: influxql-reference
weight: 203
list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] GROUP BY group_expression[, ..., group_expression_n]
```
---
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.
- [Syntax](#syntax)
- [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)
- [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)
- [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)
## 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](/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/v2.7/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 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 >}}
## 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
When grouping by tags and no time range is specified in the
[`WHERE` clause](/influxdb/cloud-serverless/reference/influxql/where/), results
use the [Unix epoch](/influxdb/cloud-serverless/reference/glossary/#unix-epoch) as the default timestamp for the aggregate timestamp.
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 |
### 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

@ -0,0 +1,164 @@
---
title: InfluxQL internals
description: Read about the implementation of InfluxQL.
menu:
influxdb_cloud_serverless:
name: InfluxQL internals
parent: influxql-reference
weight: 219
---
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

@ -0,0 +1,261 @@
---
title: LIMIT and SLIMIT clauses
description: >
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.
menu:
influxdb_cloud_serverless:
name: LIMIT and SLIMIT clauses
parent: influxql-reference
weight: 206
list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] LIMIT row_N SLIMIT series_N
```
---
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 IOx 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

@ -0,0 +1,281 @@
---
title: InfluxQL math operators
descriptions: >
Use InfluxQL mathematical operators to perform mathematical operations in
InfluxQL queries.
menu:
influxdb_cloud_serverless:
name: Math operators
parent: influxql-reference
identifier: influxql-mathematical-operators
weight: 215
---
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`, i.e. 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`, i.e. 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/query-data/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.7/query-data/influxql/explore-data/subqueries/) which offer similar functionality to using mathematical operators inside a function call.
{{% /note %}} -->

View File

@ -0,0 +1,249 @@
---
title: OFFSET and SOFFSET clauses
description: >
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.
menu:
influxdb_cloud_serverless:
name: OFFSET and SOFFSET clauses
parent: influxql-reference
weight: 207
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
```
---
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 IOx 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

@ -0,0 +1,109 @@
---
title: ORDER BY clause
list_title: ORDER BY clause
description: >
Use the `ORDER BY` clause to sort data by time in ascending or descending order.
menu:
influxdb_cloud_serverless:
name: ORDER BY clause
identifier: influxql-order-by
parent: influxql-reference
weight: 204
list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] ORDER BY time [DESC|ASC]
```
---
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

@ -0,0 +1,63 @@
---
title: Quotation
description: >
Single quotation marks (`'`) are used in the string literal syntax.
Double quotation marks (`"`) are used to quote identifiers.
menu:
influxdb_cloud_serverless:
name: Quotation
identifier: influxql-quotation
parent: influxql-reference
weight: 214
list_code_example: |
```sql
-- String literal
'I am a string'
-- Quoted identifier
"this-is-an-identifier"
```
---
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 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

@ -0,0 +1,210 @@
---
title: Regular expressions
list_title: Regular expressions
description: >
Use `regular expressions` to match patterns in your data.
menu:
influxdb_cloud_serverless:
name: Regular expressions
identifier: influxql-regular-expressions
parent: influxql-reference
weight: 213
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>/
```
---
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

@ -0,0 +1,449 @@
---
title: SELECT statement
list_title: SELECT statement
description: >
Use the `SELECT` statement to query data from one or more
[measurements](/influxdb/cloud-serverless/reference/glossary/#measurement).
menu:
influxdb_cloud_serverless:
name: SELECT statement
identifier: influxql-select-statement
parent: influxql-reference
weight: 201
list_code_example: |
```sql
SELECT <field_key>[,<field_key>,<tag_key>] FROM <measurement_name>[,<measurement_name>]
```
---
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](/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) to query.
It requires one or more comma-delimited **measurement expressions**.
- **measurement_expression**: Expression to identify one or more measurements to query.
Can be a measurement name, fully-qualified measurement, constant, or
[regular expression](/influxdb/cloud-serverless/reference/influxql/regular-expressions/).
- ##### Measurement name
```sql
FROM measurement
```
- ##### Fully-qualified measurement
```sql
FROM database.retention_policy.measurement
-- Fully-qualified measurement with default retention policy
FROM database..measurement
```
{{% note %}}
#### InfluxDB retention policies
In {{< cloud-name >}}, **retention policies** are not part of the data model like
they are in InfluxDB 1.x.
Each {{< cloud-name >}} bucket has a **retention period** which defines the
maximum age of data to retain in the bucket. To use fully-qualified
measurements in InfluxQL queries, use the following naming convention when
[creating a bucket](/influxdb/cloud-serverless/admin/buckets/create-bucket/):
```
database_name/retention_policy
```
{{% /note %}}
## 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](/{{< latest "enterprise_influxdb" >}}/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

@ -0,0 +1,374 @@
---
title: Time and time zones
description: >
Explore InfluxQL features used specifically for working with time.
Use the `tz` (time zone) clause to return the UTC offset for the specified
time zone.
menu:
influxdb_cloud_serverless:
name: Time and time zones
parent: influxql-reference
weight: 208
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>')
```
---
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)
## 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
{{% warn %}}
InfluxQL in {{< cloud-name >}} does not currently support the time zone clause,
which applies a time zone offset to UTC timestamps in query results.
**Tracking issue**: [influxdb_iox#6933](https://github.com/influxdata/influxdb_iox/issues/6933)
{{% /warn %}}
<!-- 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 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.

View File

@ -0,0 +1,371 @@
---
title: WHERE clause
description: >
Use the `WHERE` clause to filter data based on [fields](/influxdb/cloud-serverless/reference/glossary/#field), [tags](/influxdb/cloud-serverless/reference/glossary/#tag), and/or [timestamps](/influxdb/cloud-serverless/reference/glossary/#timestamp).
menu:
influxdb_cloud_serverless:
name: WHERE clause
identifier: influxql-where-clause
parent: influxql-reference
weight: 202
list_code_example: |
```sql
SELECT_clause FROM_clause WHERE <conditional_expression> [(AND|OR) <conditional_expression> [...]]
```
---
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 is not defined in the `WHERE` clause, the default time range is
the Unix epoch (`1970-01-01T00:00:00Z`) to _now_.
Timestamps are stored in the `time` columns.
Use comparison operators to compare the value of the `time` column to a
timestamp literal, integer (Unix nanosecond timestamp), or function.
{{< code-tabs-wrapper >}}
{{% code-tabs %}}
[Timestamp](#)
[Integer](#)
[Function](#)
{{% /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

@ -0,0 +1,435 @@
---
title: Sample data
description: >
Sample datasets are used throughout the the InfluxDB Cloud Dedicated
documentation to demonstrate functionality.
Use the following sample datasets to replicate provided examples.
menu:
influxdb_cloud_serverless:
name: Sample data
parent: Reference
weight: 110
---
Sample datasets are used throughout the {{< cloud-name >}} documentation to
demonstrate functionality.
Use the following sample datasets to replicate provided examples.
- [Get started home sensor data](#get-started-home-sensor-data)
- [NOAA Bay Area weather data](#noaa-bay-area-weather-data)
- [Bitcoin price data](#bitcoin-price-data)
- [Random numbers sample data](#random-numbers-sample-data)
## Get started home sensor data
Includes hourly home sensor data used in the
[Get started with {{< cloud-name >}}](/influxdb/cloud-serverless/get-started/) guide.
This dataset includes anomalous sensor readings and helps to demonstrate
processing and alerting on time series data.
To customize timestamps in the dataset, use the {{< icon "clock" >}} button in
the lower right corner of the page.
This lets you modify the sample dataset to stay within the retention period of
the bucket you write it to.
##### Time Range
**{{% influxdb/custom-timestamps-span %}}2022-01-01T08:00:00Z{{% /influxdb/custom-timestamps-span %}}**
to
**{{% influxdb/custom-timestamps-span %}}2022-01-01T20:00:00Z{{% /influxdb/custom-timestamps-span %}}**
<em style="opacity: .5">(Customizable)</em>
##### Schema
- home <em style="opacity: .5">(measurement)</em>
- **tags**:
- room
- Kitchen
- Living Room
- **fields**:
- co <em style="opacity: .5">(integer)</em>
- temp <em style="opacity: .5">(float)</em>
- hum <em style="opacity: .5">(float)</em>
{{< expand-wrapper >}}
{{% expand "Write home sensor data to InfluxDB" %}}
#### Write the home sensor data to InfluxDB
Use the InfluxDB v2 or v1 API to write the Get started home sensor sample data
to {{< cloud-name >}}.
{{< code-tabs-wrapper >}}
{{% code-tabs %}}
[v2 API](#)
[v1 API](#)
{{% /code-tabs %}}
{{% code-tab-content %}}
{{% influxdb/custom-timestamps %}}
{{% code-placeholders "API_TOKEN|BUCKET_NAME" "magenta" %}}
```sh
export INFLUX_HOST=https://cloud2.influxdata.com
export INFLUX_TOKEN=API_TOKEN
INFLUX_BUCKET=BUCKET_NAME
curl --request POST \
"$INFLUX_HOST/api/v2/write?bucket=$INFLUX_BUCKET&precision=s" \
--header "Authorization: Bearer $INFLUX_TOKEN" \
--header "Content-Type: text/plain; charset=utf-8" \
--header "Accept: application/json" \
--data-binary "
home,room=Living\ Room temp=21.1,hum=35.9,co=0i 1641024000
home,room=Kitchen temp=21.0,hum=35.9,co=0i 1641024000
home,room=Living\ Room temp=21.4,hum=35.9,co=0i 1641027600
home,room=Kitchen temp=23.0,hum=36.2,co=0i 1641027600
home,room=Living\ Room temp=21.8,hum=36.0,co=0i 1641031200
home,room=Kitchen temp=22.7,hum=36.1,co=0i 1641031200
home,room=Living\ Room temp=22.2,hum=36.0,co=0i 1641034800
home,room=Kitchen temp=22.4,hum=36.0,co=0i 1641034800
home,room=Living\ Room temp=22.2,hum=35.9,co=0i 1641038400
home,room=Kitchen temp=22.5,hum=36.0,co=0i 1641038400
home,room=Living\ Room temp=22.4,hum=36.0,co=0i 1641042000
home,room=Kitchen temp=22.8,hum=36.5,co=1i 1641042000
home,room=Living\ Room temp=22.3,hum=36.1,co=0i 1641045600
home,room=Kitchen temp=22.8,hum=36.3,co=1i 1641045600
home,room=Living\ Room temp=22.3,hum=36.1,co=1i 1641049200
home,room=Kitchen temp=22.7,hum=36.2,co=3i 1641049200
home,room=Living\ Room temp=22.4,hum=36.0,co=4i 1641052800
home,room=Kitchen temp=22.4,hum=36.0,co=7i 1641052800
home,room=Living\ Room temp=22.6,hum=35.9,co=5i 1641056400
home,room=Kitchen temp=22.7,hum=36.0,co=9i 1641056400
home,room=Living\ Room temp=22.8,hum=36.2,co=9i 1641060000
home,room=Kitchen temp=23.3,hum=36.9,co=18i 1641060000
home,room=Living\ Room temp=22.5,hum=36.3,co=14i 1641063600
home,room=Kitchen temp=23.1,hum=36.6,co=22i 1641063600
home,room=Living\ Room temp=22.2,hum=36.4,co=17i 1641067200
home,room=Kitchen temp=22.7,hum=36.5,co=26i 1641067200
"
```
{{% /code-placeholders %}}
{{% /influxdb/custom-timestamps %}}
{{% /code-tab-content %}}
{{% code-tab-content %}}
{{% influxdb/custom-timestamps %}}
{{% code-placeholders "API_TOKEN|BUCKET_NAME" "magenta" %}}
```sh
export INFLUX_HOST=https://cloud2.influxdata.com
export INFLUX_TOKEN=API_TOKEN
INFLUX_BUCKET=BUCKET_NAME
curl --request POST \
"$INFLUX_HOST/write?db=$INFLUX_BUCKET&precision=s" \
--header "Authorization: Bearer $INFLUX_TOKEN" \
--header "Content-type: text/plain; charset=utf-8" \
--data-binary "
home,room=Living\ Room temp=21.1,hum=35.9,co=0i 1641024000
home,room=Kitchen temp=21.0,hum=35.9,co=0i 1641024000
home,room=Living\ Room temp=21.4,hum=35.9,co=0i 1641027600
home,room=Kitchen temp=23.0,hum=36.2,co=0i 1641027600
home,room=Living\ Room temp=21.8,hum=36.0,co=0i 1641031200
home,room=Kitchen temp=22.7,hum=36.1,co=0i 1641031200
home,room=Living\ Room temp=22.2,hum=36.0,co=0i 1641034800
home,room=Kitchen temp=22.4,hum=36.0,co=0i 1641034800
home,room=Living\ Room temp=22.2,hum=35.9,co=0i 1641038400
home,room=Kitchen temp=22.5,hum=36.0,co=0i 1641038400
home,room=Living\ Room temp=22.4,hum=36.0,co=0i 1641042000
home,room=Kitchen temp=22.8,hum=36.5,co=1i 1641042000
home,room=Living\ Room temp=22.3,hum=36.1,co=0i 1641045600
home,room=Kitchen temp=22.8,hum=36.3,co=1i 1641045600
home,room=Living\ Room temp=22.3,hum=36.1,co=1i 1641049200
home,room=Kitchen temp=22.7,hum=36.2,co=3i 1641049200
home,room=Living\ Room temp=22.4,hum=36.0,co=4i 1641052800
home,room=Kitchen temp=22.4,hum=36.0,co=7i 1641052800
home,room=Living\ Room temp=22.6,hum=35.9,co=5i 1641056400
home,room=Kitchen temp=22.7,hum=36.0,co=9i 1641056400
home,room=Living\ Room temp=22.8,hum=36.2,co=9i 1641060000
home,room=Kitchen temp=23.3,hum=36.9,co=18i 1641060000
home,room=Living\ Room temp=22.5,hum=36.3,co=14i 1641063600
home,room=Kitchen temp=23.1,hum=36.6,co=22i 1641063600
home,room=Living\ Room temp=22.2,hum=36.4,co=17i 1641067200
home,room=Kitchen temp=22.7,hum=36.5,co=26i 1641067200
"
```
{{% /code-placeholders %}}
{{% /influxdb/custom-timestamps %}}
{{% /code-tab-content %}}
{{< /code-tabs-wrapper >}}
Replace the following in the script above:
- {{% code-placeholder-key %}}`BUCKET_NAME`{{% /code-placeholder-key %}}:
your InfluxDB Cloud Serverless bucket
- {{% code-placeholder-key %}}`API_TOKEN`{{% /code-placeholder-key %}}:
an [API token](/influxdb/cloud-serverless/admin/tokens/) with _write_ pe
mission to the bucket
{{% /expand %}}
{{< /expand-wrapper >}}
## NOAA Bay Area weather data
Includes daily weather metrics from three San Francisco Bay Area airports from
**January 1, 2020 to December 31, 2022**.
This sample dataset includes seasonal trends and is good for exploring time
series use cases that involve seasonality.
##### Time Range
**2020-01-01T00:00:00Z** to **2022-12-31T00:00:00Z**
##### Schema
- weather <em style="opacity: .5">(measurement)</em>
- **tags**:
- location
- Concord
- Hayward
- San Francisco
- **fields**
- precip <em style="opacity: .5">(float)</em>
- temp_avg <em style="opacity: .5">(float)</em>
- temp_max <em style="opacity: .5">(float)</em>
- temp_min <em style="opacity: .5">(float)</em>
- wind_avg <em style="opacity: .5">(float)</em>
{{< expand-wrapper >}}
{{% expand "Write the NOAA Bay Area weather data to InfluxDB" %}}
#### Write the NOAA Bay Area weather data to InfluxDB
Use the InfluxDB v2 or v1 API to write the NOAA Bay Area weather sample data to
{{< cloud-name >}}.
{{< code-tabs-wrapper >}}
{{% code-tabs %}}
[v2 API](#)
[v1 API](#)
{{% /code-tabs %}}
{{% code-tab-content %}}
{{% code-placeholders "API_TOKEN|BUCKET_NAME" %}}
```sh
export INFLUX_HOST=https://cloud2.influxdata.com
export INFLUX_TOKEN=API_TOKEN
INFLUX_BUCKET=BUCKET_NAME
curl --request POST \
"$INFLUX_HOST/api/v2/write?bucket=$INFLUX_BUCKET" \
--header "Authorization: Bearer $INFLUX_TOKEN" \
--header "Content-Type: text/plain; charset=utf-8" \
--header "Accept: application/json" \
--data-binary "$(curl --request GET https://docs.influxdata.com/downloads/bay-area-weather.lp)"
```
{{% /code-placeholders %}}
{{% /code-tab-content %}}
{{% code-tab-content %}}
{{% code-placeholders "API_TOKEN|BUCKET_NAME" "magenta" %}}
```sh
export INFLUX_HOST=https://cloud2.influxdata.com
export INFLUX_TOKEN=API_TOKEN
INFLUX_BUCKET=BUCKET_NAME
curl --request POST \
"$INFLUX_HOST/write?db=$INFLUX_BUCKET" \
--header "Authorization: Bearer $INFLUX_TOKEN" \
--header "Content-type: text/plain; charset=utf-8" \
--data-binary "$(curl --request GET https://docs.influxdata.com/downloads/bay-area-weather.lp)"
```
{{% /code-placeholders %}}
{{% /code-tab-content %}}
{{< /code-tabs-wrapper >}}
Replace the following in the script above:
- {{% code-placeholder-key %}}`BUCKET_NAME`{{% /code-placeholder-key %}}:
your InfluxDB Cloud Serverless bucket
- {{% code-placeholder-key %}}`API_TOKEN`{{% /code-placeholder-key %}}:
an [API token](/influxdb/cloud-serverless/admin/tokens/) with sufficient
permissions to the bucket
{{% /expand %}}
{{< /expand-wrapper >}}
## Bitcoin price data
The Bitcoin price sample dataset provides Bitcoin prices from
**2023-05-01T00:00:00Z to 2023-05-15T00:00:00Z**—_[Powered by CoinDesk](https://www.coindesk.com/price/bitcoin)_.
##### Time Range
**2023-05-01T00:19:00Z** to **2023-05-14T23:48:00Z**
##### Schema
- bitcoin <em style="opacity: .5">(measurement)</em>
- **tags**:
- code
- EUR
- GBP
- USD
- crypto
- bitcoin
- description
- Euro
- British Pound Sterling
- United States Dollar
- symbol
- \&euro; <em style="opacity: .5">(&euro;)</em>
- \&pound; <em style="opacity: .5">(&pound;)</em>
- \&#36; <em style="opacity: .5">(&#36;)</em>
- **fields**
- price <em style="opacity: .5">(float)</em>
{{< expand-wrapper >}}
{{% expand "Write the Bitcoin sample data to InfluxDB" %}}
#### Write the Bitcoin price sample data to InfluxDB
Use the InfluxDB v2 or v1 API to write the Bitcoin price sample data to
{{< cloud-name >}}.
{{< code-tabs-wrapper >}}
{{% code-tabs %}}
[v2 API](#)
[v1 API](#)
{{% /code-tabs %}}
{{% code-tab-content %}}
{{% code-placeholders "API_TOKEN|BUCKET_NAME" "magenta" %}}
```sh
export INFLUX_HOST=https://cloud2.influxdata.com
export INFLUX_TOKEN=API_TOKEN
INFLUX_BUCKET=BUCKET_NAME
curl --request POST \
"$INFLUX_HOST/api/v2/write?bucket=$INFLUX_BUCKET" \
--header "Authorization: Bearer $INFLUX_TOKEN" \
--header "Content-Type: text/plain; charset=utf-8" \
--header "Accept: application/json" \
--data-binary "$(curl --request GET https://docs.influxdata.com/downloads/bitcoin.lp)"
```
{{% /code-placeholders %}}
{{% /code-tab-content %}}
{{% code-tab-content %}}
{{% code-placeholders "API_TOKEN|BUCKET_NAME" "magenta" %}}
```sh
export INFLUX_HOST=https://cloud2.influxdata.com
export INFLUX_TOKEN=API_TOKEN
INFLUX_BUCKET=BUCKET_NAME
curl --request POST \
"$INFLUX_HOST/write?db=$INFLUX_BUCKET" \
--header "Authorization: Bearer $INFLUX_TOKEN" \
--header "Content-type: text/plain; charset=utf-8" \
--data-binary "$(curl --request GET https://docs.influxdata.com/downloads/bitcoin.lp)"
```
{{% /code-placeholders %}}
{{% /code-tab-content %}}
{{< /code-tabs-wrapper >}}
Replace the following in the script above:
- {{% code-placeholder-key %}}`BUCKET_NAME`{{% /code-placeholder-key %}}:
your InfluxDB Cloud Serverless bucket
- {{% code-placeholder-key %}}`API_TOKEN`{{% /code-placeholder-key %}}:
an [API token](/influxdb/cloud-serverless/admin/tokens/) with sufficient
permissions to the bucket
{{% /expand %}}
{{< /expand-wrapper >}}
## Random numbers sample data
Includes two fields with randomly generated numbers reported every minute.
Each field has a specific range of randomly generated numbers.
This sample dataset is used to demonstrate mathematic operations and
transformation functions.
##### Time Range
**2023-01-01T00:00:00Z** to **2023-01-01T12:00:00Z**
##### Schema
- numbers <em style="opacity: .5">(measurement)</em>
- **fields**
- a <em style="opacity: .5">(float between -1 and 1)</em>
- b <em style="opacity: .5">(float between -3 and 3)</em>
{{< expand-wrapper >}}
{{% expand "Write the random number sample data to InfluxDB" %}}
#### Write the random number sample data to InfluxDB
Use the InfluxDB v2 or v1 API to write the random number sample data to
{{< cloud-name >}}.
{{< code-tabs-wrapper >}}
{{% code-tabs %}}
[v2 API](#)
[v1 API](#)
{{% /code-tabs %}}
{{% code-tab-content %}}
{{% code-placeholders "API_TOKEN|BUCKET_NAME" "magenta" %}}
```sh
export INFLUX_HOST=https://cloud2.influxdata.com
export INFLUX_TOKEN=API_TOKEN
INFLUX_BUCKET=BUCKET_NAME
curl --request POST \
"$INFLUX_HOST/api/v2/write?bucket=$INFLUX_BUCKET" \
--header "Authorization: Bearer $INFLUX_TOKEN" \
--header "Content-Type: text/plain; charset=utf-8" \
--header "Accept: application/json" \
--data-binary "$(curl --request GET https://docs.influxdata.com/downloads/random-numbers.lp)"
```
{{% /code-placeholders %}}
{{% /code-tab-content %}}
{{% code-tab-content %}}
{{% code-placeholders "API_TOKEN|BUCKET_NAME" "magenta" %}}
```sh
export INFLUX_HOST=https://cloud2.influxdata.com
export INFLUX_TOKEN=API_TOKEN
INFLUX_BUCKET=BUCKET_NAME
curl --request POST \
"$INFLUX_HOST/write?db=$INFLUX_BUCKET" \
--header "Authorization: Bearer $INFLUX_TOKEN" \
--header "Content-type: text/plain; charset=utf-8" \
--data-binary "$(curl --request GET https://docs.influxdata.com/downloads/random-numbers.lp)"
```
{{% /code-placeholders %}}
{{% /code-tab-content %}}
{{< /code-tabs-wrapper >}}
Replace the following in the script above:
- {{% code-placeholder-key %}}`BUCKET_NAME`{{% /code-placeholder-key %}}:
your InfluxDB Cloud Serverless bucket
- {{% code-placeholder-key %}}`API_TOKEN`{{% /code-placeholder-key %}}:
an [API token](/influxdb/cloud-serverless/admin/tokens/) with sufficient
permissions to the bucket
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -45,46 +45,46 @@
{{ end }}
{{ if or (eq $navIcon "profile") (eq $navIcon "account") }}
<div class="nav-items">
<div class="nav-item account small">
<div class="acct-inner">
<div class="acct-icon">
<span class="icon icon-user"></span>
</div>
</div>
</div>
<div class="nav-item account">
<div class="acct-inner">
<div class="acct-icon"><span class="icon icon-user"></span></div>
<div class="acct-label">
<div class="username">username</div>
<div class="orgname">org-name</div>
</div>
</div>
<div class="nav-items">
<div class="nav-item account small">
<div class="acct-inner">
<div class="acct-icon">
<span class="icon icon-user"></span>
</div>
</div>
</div>
<div class="nav-item account">
<div class="acct-inner">
<div class="acct-icon"><span class="icon icon-user"></span></div>
<div class="acct-label">
<div class="username">username</div>
<div class="orgname">org-name</div>
</div>
</div>
</div>
</div>
{{ else }}
{{ $icon := .Scratch.Get "icon" }}
{{ $title := .Scratch.Get "title" }}
{{ $shortTitle := .Scratch.Get "short_title" }}
<div class="nav-items">
<div class="nav-item">
<div class="nav-icon small">
<span class ="icon icon-{{ $icon }}"></span>
<div class="nav-icon-label">
{{ $shortTitle }}
</div>
</div>
</div>
<div class="nav-item">
<div class="nav-icon">
<span class ="icon icon-{{ $icon }}"></span>
<div class="nav-icon-label">
{{ $title }}
</div>
</div>
<div class="nav-items">
<div class="nav-item">
<div class="nav-icon small">
<span class ="icon icon-{{ $icon }}"></span>
<div class="nav-icon-label">
{{ $shortTitle }}
</div>
</div>
</div>
<div class="nav-item">
<div class="nav-icon">
<span class ="icon icon-{{ $icon }}"></span>
<div class="nav-icon-label">
{{ $title }}
</div>
</div>
</div>
</div>
{{ end }}
{{ else }}
@ -144,37 +144,37 @@
{{ end }}
{{ if or (eq $navIcon "profile") (eq $navIcon "account") }}
<div class="nav-items-{{ $version }}">
<div class="nav-item-{{ $version }} account">
<div class="acct-inner-{{ $version }}">
<div class="acct-icon-{{ $version }}"><span class="initial">u</span></div>
</div>
</div>
<div class="nav-item-{{ $version }} account">
<div class="acct-inner-{{ $version }}">
<div class="acct-icon-{{ $version }}"><span class="initial">u</span></div>
<div class="acct-label-{{ $version }}">
<div class="username">username</div>
<div class="orgname">org-name</div>
</div>
</div>
<div class="nav-items-{{ $version }}">
<div class="nav-item-{{ $version }} account">
<div class="acct-inner-{{ $version }}">
<div class="acct-icon-{{ $version }}"><span class="initial">u</span></div>
</div>
</div>
<div class="nav-item-{{ $version }} account">
<div class="acct-inner-{{ $version }}">
<div class="acct-icon-{{ $version }}"><span class="initial">u</span></div>
<div class="acct-label-{{ $version }}">
<div class="username">username</div>
<div class="orgname">org-name</div>
</div>
</div>
</div>
</div>
{{ else }}
{{ $icon := .Scratch.Get "icon" }}
{{ $title := .Scratch.Get "title" }}
<div class="nav-items-{{ $version }}">
<div class="nav-item-{{ $version }}">
<div class="nav-icon-{{ $version }}">
<span class="{{ $version }} cf-icon {{ $icon }}"></span>
</div>
</div>
<div class="nav-item-{{ $version }}">
<div class="nav-icon-{{ $version }}">
<span class="{{ $version }} cf-icon {{ $icon }}"></span>
</div>
<p class="nav-label-{{ $version }}">{{ $title }}</p>
</div>
</div>
<div class="nav-items-{{ $version }}">
<div class="nav-item-{{ $version }}">
<div class="nav-icon-{{ $version }}">
<span class="{{ $version }} cf-icon {{ $icon }}"></span>
</div>
</div>
<div class="nav-item-{{ $version }}">
<div class="nav-icon-{{ $version }}">
<span class="{{ $version }} cf-icon {{ $icon }}"></span>
</div>
<p class="nav-label-{{ $version }}">{{ $title }}</p>
</div>
</div>
{{ end }}
{{ end }}

View File

@ -0,0 +1,34 @@
curl --request POST \
https://cloud2.influxdata.com/api/v2/authorizations \
--header "Authorization: Token API_TOKEN" \
--header 'Content-type: application/json' \
--data '{
"status": "active",
"description": "AUTHORIZATION_DESCRIPTION",
"orgID": "ORG_ID",
"permissions": [
{
"action": "read",
"resource": {
"orgID": "ORG_ID",
"type": "authorizations"
}
},
{
"action": "read",
"resource": {
"orgID": "ORG_ID",
"type": "buckets"
}
},
{
"action": "write",
"resource": {
"orgID": "ORG_ID",
"type": "buckets",
"name": "iot-center"
}
}
]
}'

View File

@ -0,0 +1,43 @@
######################################################
# The example below uses common command-line tools
# `curl`, `jq` with the InfluxDB API to do the following:
# 1. Create a user.
# 2. Find the new or existing user by name.
# 3. If the user exists:
# a. Build an authorization object with the user ID.
# b. Create the new authorization.
# c. Return the new token.
######################################################
function create_token_with_user() {
curl --request POST \
"https://cloud2.influxdata.com/api/v2/users/" \
--header "Authorization: Token API_TOKEN" \
--header 'Content-type: application/json' \
--data "{\"name\": \"$1\"}"
curl --request GET \
"https://cloud2.influxdata.com/api/v2/users?name=$1" \
--header "Authorization: Token API_TOKEN" \
--header 'Content-type: application/json' | \
jq --arg USER $1 '.users[0] // error("User missing")
| {
"orgID": "ORG_ID",
"userID": .id,
"description": $USER,
"permissions": [
{"action": "read", "resource": {"type": "buckets"}}
]
}' | \
curl --request POST \
"https://cloud2.influxdata.com/api/v2/authorizations" \
--header "Authorization: Token API_TOKEN" \
--header 'Content-type: application/json' \
--data @- | \
jq '.token'
}
create_token_with_user 'iot_user_1'

View File

@ -0,0 +1,25 @@
# The example below uses the common `curl` and `jq` command-line tools
# with the InfluxDB API to do the following:
# 1. Find a user by username and extract the user ID.
# 2. Find the user's authorizations by user ID.
# 3. Filter for `active` authorizations that have `write` permission.
function list_write_auths() {
curl "https://cloud2.influxdata.com/api/v2/users/?name=$1" \
--header "Authorization: Token API_TOKEN" \
--header 'Content-type: application/json' | \
jq --arg USER $1 '.users[] | select(.name == $USER) | .id' | \
xargs -I '%' \
curl "https://cloud2.influxdata.com/api/v2/authorizations/?userID=%" \
--header "Authorization: Token API_TOKEN" \
--header 'Content-type: application/json' | \
jq '.authorizations[]
| select(.permissions[] | select(.action=="write"))
| select(.status=="active")'
}
list_write_auths 'iot_user_1'

View File

@ -0,0 +1,4 @@
curl --request GET \
"https://cloud2.influxdata.com/api/v2/authorizations" \
--header "Authorization: Token API_TOKEN" \
--header 'Content-type: application/json'