port influxql docs into 2.5 (#4621)

* moved InfluxQL to 2.4

* delete _index file in influxql 2.1

* Revert "delete _index file in influxql 2.1"

This reverts commit cf506408b7.

* Add InfluxQL functions (#4553)

* delete old functions file

* Link Fixes (#4554)

* 2.1 to 2.4

* 2.1 to 2.4

* update front matter

* add overview links on landing functions page

* updated _index.md page

* removed into clause in a few docs

* fix params formatting

* update intro and overview list

* updates to links, changed CLI to influxql shell

* edits

* fixed links

* update links (#4567)

* update links
* add missing note shortcode

* fixed links, made updates

* edits to examples

* remove into clause and edits

* fix dates/upd egs

* edits

* added dbrp doc, edited manage data doc

* Update Selectors

* updates to language and examples

* added another DELETE FROM example

* updates to functions

* updates

* updated 2.4 faq doc

* edits to manage-data

* misc edits manage-data

* InfluxQL syntax updates

* update glossary definitions

* upd glossary

* edits

* updated index for influxql syntax

* fixed index file

* made edits

* Edits to explore data

* edit

* Explore data edits

* SELECT statement edits

* SELECT statement edits

* moved influxql 2.4 into 2.5

* fix typo

* Delete FETCH_HEAD

* added updated faq doc

* updated frontmatter to and link to 2.5

* edits to query data with influxQL

* fix typo

* misc edits

* Edits to InfluxQL Explore data clauses

* misc edits

* InfluxQL Clause Edits-2

* Update content/influxdb/v2.4/query-data/influxql/_index.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-schema.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-schema.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-schema.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-schema.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/_index.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/_index.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/_index.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/_index.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/_index.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/_index.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/_index.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/_index.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/limit-and-slimit.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* PR edits

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* PR review

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* PR edits

* revert influxql 2.1 upd

* Update content/influxdb/v2.4/query-data/influxql/explore-data/offset-and-soffset.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* updated dates and mention InfluxQL in sample data

* update sample data query

* misc PR edits

* Update content/influxdb/v2.4/query-data/influxql/explore-data/_index.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* clarify group by requires an aggregate or selector

* Update content/influxdb/v2.4/query-data/influxql/explore-data/limit-and-slimit.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* Update content/influxdb/v2.4/query-data/influxql/explore-data/limit-and-slimit.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* PR edits

* Update content/influxdb/v2.4/query-data/influxql/explore-data/group-by.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* PR edits Influxql 2.4 (#4634)

* returned per query

* PR edits

* Update content/influxdb/v2.4/query-data/influxql/_index.md

Co-authored-by: kelseiv <47797004+kelseiv@users.noreply.github.com>

* Timezone edits

* Update content/influxdb/v2.4/query-data/influxql/explore-schema.md

Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>

* added identifier to regex doc

* added identifier to menu

* fixed typo

* made edits requested in PR

* missed a word

* Apply suggestions from code review

* updated explore schema

* updated manage data and added insert

* updated influxql math operators

* fixed influxql math TOC order

* added warning about DROP MESSURMENT

* reformatted influxql functions pages

* link audit for influxql docs

* reorder influxql nav

* ported influxql and other changes into 2.5

* fix 2.4 links in 2.5

Co-authored-by: Kelly <kelly@influxdata.com>
Co-authored-by: kelseiv <47797004+kelseiv@users.noreply.github.com>
Co-authored-by: peterreg <pregan@influxdata.com>
Co-authored-by: Scott Anderson <sanderson@users.noreply.github.com>
Co-authored-by: Scott Anderson <scott@influxdata.com>
pull/4641/head
lwandzura 2022-11-16 15:10:11 -06:00 committed by GitHub
parent 71a61c080d
commit d74b856bc0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
60 changed files with 26519 additions and 143 deletions

View File

@ -124,6 +124,7 @@
"article/flux",
"article/html-diagrams",
"article/influxdbu",
"article/influxql",
"article/keybinding",
"article/list-filters",
"article/lists",

View File

@ -0,0 +1,9 @@
.influxql-table-meta p {
font-size: .9rem;
line-height: 1.25rem;
&:last-child {margin-bottom: 0rem}
}
table + .influxql-table-meta {
margin-top:-1.5rem;
}

View File

@ -22,6 +22,7 @@ Because InfluxQL uses the 1.x data model, a bucket must be mapped to a database
{{% note %}}
#### InfluxQL reference documentation
For complete InfluxQL reference documentation, see
[Influx Query Language in the latest InfluxDB 1.x documentation](/{{< latest "influxdb" "v1" >}}/query_language/).
{{% /note %}}
@ -41,8 +42,7 @@ For more information, see [Database and retention policy mapping](/influxdb/v2.1
If you're not sure how data was written into a bucket, verify the bucket has a mapping.
{{% /note %}}
Use the [`influx` CLI](/influxdb/v2.1/reference/cli/influx/) or the [InfluxDB API](/influxdb/v2.1/reference/api/)
to verify the buckets you want to query are mapped to a database and retention policy.
Use the [`influx` CLI](/influxdb/v2.1/reference/cli/influx/) or the [InfluxDB API](/influxdb/v2.1/reference/api/) to verify the buckets you want to query are mapped to a database and retention policy.
{{< tabs-wrapper >}}
{{% tabs %}}
@ -116,13 +116,14 @@ If you **do not find a DBRP mapping for a bucket**, complete the next procedure
_For more information on the DBRP mapping API, see the [`/api/v2/dbrps` endpoint documentation](/influxdb/v2.1/api/#tag/DBRPs)._
## Map unmapped buckets
Use the [`influx` CLI](/influxdb/v2.1/reference/cli/influx/) or the [InfluxDB API](/influxdb/v2.1/reference/api/)
to manually create DBRP mappings for unmapped buckets.
Use the [`influx` CLI](/influxdb/v2.1/reference/cli/influx/) or the [InfluxDB API](/influxdb/v2.1/reference/api/) to manually create DBRP mappings for unmapped buckets.
{{< tabs-wrapper >}}
{{% tabs %}}
[influx CLI](#)
[InfluxDB API](#)
{{% /tabs %}}
{{% tab-content %}}
@ -245,6 +246,7 @@ To learn more about InfluxQL, see [Influx Query Language (InfluxQL)](/{{< latest
- `GRANT`
- `KILL`
- `REVOKE`
- `SHOW SERIES CARDINALITY`
{{% /warn %}}
{{< /flex-content >}}
{{< /flex >}}

View File

@ -9,44 +9,45 @@ menu:
influxdb_2_4:
name: Query with InfluxQL
parent: Query data
cascade:
related:
related:
- /influxdb/v2.4/reference/api/influxdb-1x/
- /influxdb/v2.4/reference/api/influxdb-1x/query
- /influxdb/v2.4/reference/api/influxdb-1x/dbrp
- /influxdb/v2.4/tools/influxql-shell/
---
Use InfluxQL (an SQL-like query language) to interact with InfluxDB, and query and analyze your times series data.
In InfluxDB 1.x, data is stored in [databases](/{{< latest "influxdb" "v1" >}}/concepts/glossary/#database)
and [retention policies](/{{< latest "influxdb" "v1" >}}/concepts/glossary/#retention-policy-rp).
InfluxDB {{< current-version >}} combines and replaces database and retention
policies with [buckets](/influxdb/v2.4/reference/glossary/#bucket).
Because InfluxQL uses the 1.x data model, a database and retention policy combination
(DBRP) must be mapped to a bucket before it can be queried using InfluxQL.
In InfluxDB OSS {{< current-version >}}, data is stored in [buckets](/influxdb/v2.4/reference/glossary/#bucket).
Because InfluxQL uses the 1.x data model, a bucket must be mapped to a database and retention policy (DBRP) before it can be queried using InfluxQL.
{{% note %}}
#### InfluxQL reference documentation
For complete InfluxQL reference documentation, see
[Influx Query Language in the latest InfluxDB 1.x documentation](/{{< latest "influxdb" "v1" >}}/query_language/).
{{% /note %}}
**To use InfluxQL to query bucket data, complete the following steps:**
**To query data with InfluxQL, complete the following steps:**
1. [Verify buckets have a mapping](#verify-buckets-have-a-mapping).
2. [Create DBRP mappings for unmapped buckets](#create-dbrp-mappings-for-unmapped-buckets).
3. [Query a mapped bucket with InfluxQL](#query-a-mapped-bucket-with-influxql).
{{% note %}}
#### InfluxQL reference documentation
For complete InfluxQL reference documentation, see the
[InfluxQL specification for InfluxDB 2.x](/influxdb/v2.4/reference/syntax/influxql/spec/).
{{% /note %}}
## Verify buckets have a mapping
Use the [`influx` CLI](/influxdb/v2.4/reference/cli/influx/) or the [InfluxDB API](/influxdb/v2.4/reference/api/)
to verify the buckets you want to query are mapped to a database and retention policy.
1. To verify the buckets you want to query are mapped to a database and retention policy, use the [`influx` CLI](/influxdb/v2.4/reference/cli/influx/) or the [InfluxDB API](/influxdb/v2.4/reference/api/).
_For examples, see [List DBRP mappings](/influxdb/v2.4/query-data/influxql/dbrp/#list-dbrp-mappings)._
If you **do not find a DBRP mapping for a bucket**, [create a new DBRP mapping]() to
2. If you **do not find a DBRP mapping for a bucket**, [create a new DBRP mapping](/influxdb/v2.4/query-data/influxql/dbrp/#create-dbrp-mappings) to
map the unmapped bucket.
## Create DBRP mappings for unmapped buckets
Use the [`influx` CLI](/influxdb/v2.4/reference/cli/influx/) or the [InfluxDB API](/influxdb/v2.4/reference/api/)
- Use the [`influx` CLI](/influxdb/v2.4/reference/cli/influx/) or the [InfluxDB API](/influxdb/v2.4/reference/api/)
to manually create DBRP mappings for unmapped buckets.
_For examples, see [Create DBRP mappings](/influxdb/v2.4/query-data/influxql/dbrp/#create-dbrp-mappings)._
@ -54,36 +55,32 @@ _For examples, see [Create DBRP mappings](/influxdb/v2.4/query-data/influxql/dbr
{{< tabs-wrapper >}}
{{% tabs %}}
[InfluxQL Shell](#)
[InfluxQL shell](#)
[InfluxDB API](#)
{{% /tabs %}}
{{% tab-content %}}
<!---------------------------- BEGIN InfluxQL shell --------------------------->
The [`influx` CLI](/influxdb/v2.4/tools/influx-cli/) provides an InfluxQL shell
where you can execute InfluxQL queries in an interactive Read-Eval-Print-Loop (REPL).
The [`influx` CLI](/influxdb/v2.4/reference/cli/influx/) provides an [InfluxQL shell](/influxdb/v2.4/tools/influxql-shell/) where you can execute InfluxQL queries in an interactive Read-Eval-Print-Loop (REPL).
{{% note %}}
If you haven't already, be sure to do the following:
1. If you haven't already, do the following:
- [Download and install the `influx` CLI](/influxdb/v2.4/tools/influx-cli/#install-the-influx-cli)
- [Configure your authentication credentials](/influxdb/v2.4/tools/influx-cli/#provide-required-authentication-credentials)
{{% /note %}}
- [Download and install the `influx` CLI](/influxdb/v2.4/tools/influx-cli/#install-the-influx-cli)
- [Configure your authentication credentials](/influxdb/v2.4/tools/influx-cli/#provide-required-authentication-credentials)
Use the following command to start an InfluxQL shell:
2. Use the following command to start an InfluxQL shell:
```sh
influx v1 shell
```
```sh
influx v1 shell
```
Execute an InfluxQL query inside the InfluxQL shell.
3. Execute an InfluxQL query inside the InfluxQL shell.
```sql
> SELECT used_percent FROM example-db.example-rp.example-measurement WHERE host=host1
```
```sql
SELECT used_percent FROM example-db.example-rp.example-measurement WHERE host=host1
```
For more information about using the InfluxQL shell, see
[Use the InfluxQL shell](/influxdb/v2.4/tools/influxql-shell/).
For more information, see how to [use the InfluxQL shell](/influxdb/v2.4/tools/influxql-shell/). For more information about DBRP mappings, see [Manage DBRP mappings](/influxdb/v2.4/query-data/influxql/dbrp/).
<!----------------------------- END InfluxQL shell ---------------------------->
{{% /tab-content %}}
@ -93,37 +90,36 @@ For more information about using the InfluxQL shell, see
The [InfluxDB 1.x compatibility API](/influxdb/v2.4/reference/api/influxdb-1x/) supports
all InfluxDB 1.x client libraries and integrations in InfluxDB {{< current-version >}}.
To query a mapped bucket with InfluxQL, use the [`/query` 1.x compatibility endpoint](/influxdb/v2.4/reference/api/influxdb-1x/query/).
Include the following in your request:
1. To query a mapped bucket with InfluxQL, use the [`/query` 1.x compatibility endpoint](/influxdb/v2.4/reference/api/influxdb-1x/query/), and include the following in your request:
- **Request method:** `GET`
- **Headers:**
- **Request method:** `GET`
- **Headers:**
- **Authorization:** _See [compatibility API authentication](/influxdb/v2.4/reference/api/influxdb-1x/#authentication)_
- **Query parameters:**
- **Query parameters:**
- **db**: 1.x database to query
- **rp**: 1.x retention policy to query _(if no retention policy is specified, InfluxDB uses the default retention policy for the specified database)_
- **q**: URL-encoded InfluxQL query
{{% api/url-encode-note %}}
{{% api/url-encode-note %}}
```sh
curl --get http://localhost:8086/query?db=example-db \
```sh
curl --get http://localhost:8086/query?db=example-db \
--header "Authorization: Token YourAuthToken" \
--data-urlencode "q=SELECT used_percent FROM example-db.example-rp.example-measurement WHERE host=host1"
```
```
By default, the `/query` compatibility endpoint returns results in **JSON**.
To return results as **CSV**, include the `Accept: application/csv` header.
By default, the `/query` compatibility endpoint returns results in **JSON**.
2. (Optional) To return results as **CSV**, include the `Accept: application/csv` header.
For more information about DBRP mappings, see [Manage DBRP mappings](/influxdb/v2.4/query-data/influxql/dbrp/).
<!------------------------------ END InfluxDB API ----------------------------->
{{% /tab-content %}}
{{< /tabs-wrapper >}}
## InfluxQL support
InfluxDB {{< current-version >}} supports InfluxQL queries.
See supported and unsupported queries below.
To learn more about InfluxQL, see [Influx Query Language (InfluxQL)](/{{< latest "influxdb" "v1" >}}/query_language/).
InfluxDB OSS 2.x supports the following InfluxQL statements and clauses. See supported and unsupported queries below.
{{< flex >}}
{{< flex-content >}}
@ -135,10 +131,13 @@ To learn more about InfluxQL, see [Influx Query Language (InfluxQL)](/{{< latest
- `EXPLAIN ANALYZE`
- `SELECT` _(read-only)_
- `SHOW DATABASES`
- `SHOW SERIES`
- `SHOW MEASUREMENTS`
- `SHOW TAG KEYS`
- `SHOW TAG VALUES`
- `SHOW FIELD KEYS`
- `SHOW SERIES EXACT CARDINALITY`
- `SHOW TAG KEY CARDINALITY`
- `SHOW FIELD KEY CARDINALITY`
\* These commands delete data.
{{% /note %}}
@ -155,6 +154,7 @@ To learn more about InfluxQL, see [Influx Query Language (InfluxQL)](/{{< latest
- `GRANT`
- `KILL`
- `REVOKE`
- `SHOW SERIES CARDINALITY`
{{% /warn %}}
{{< /flex-content >}}
{{< /flex >}}

View File

@ -7,14 +7,14 @@ description: >
menu:
influxdb_2_4:
parent: Query with InfluxQL
weight: 202
weight: 201
influxdb/v2.4/tags: [influxql, dbrp]
---
InfluxQL requires a database and retention policy (DBRP) combination to query data from.
InfluxQL requires a database and retention policy (DBRP) combination in order to query data.
In InfluxDB {{< current-version >}}, databases and retention policies have been
combined and replaced by InfluxDB [buckets](/influxdb/v2.4/reference/glossary/#bucket).
To query an InfluxDB {{< current-version >}} with InfluxQL, the specified DBRP
To query InfluxDB {{< current-version >}} with InfluxQL, the specified DBRP
combination must be mapped to a bucket.
- [Automatic DBRP mapping](#automatic-dbrp-mapping)

View File

@ -0,0 +1,73 @@
---
title: Explore data using InfluxQL
description: >
Explore time series data using InfluxQL, InfluxData's SQL-like query language.
Use the `SELECT` statement to query data from measurements, tags, and fields.
menu:
influxdb_2_4:
name: Explore data
parent: Query with InfluxQL
weight: 202
---
To start exploring data with InfluxQL, do the following:
1. Verify your bucket has a database and retention policy (DBRP) mapping by [listing DBRP mappings for your bucket](/influxdb/v2.4/query-data/influxql/dbrp/#list-dbrp-mappings). If not, [create a new DBRP mapping](/influxdb/v2.4/query-data/influxql/dbrp/#create-dbrp-mappings).
2. [Configure timestamps in the InfluxQL shell](/influxdb/v2.4/query-data/influxql/explore-data/time-and-timezone/).
3. _(Optional)_ If you would like to use the data used in the examples below, [download the NOAA sample data](#download-sample-data).
4. Use the InfluxQL `SELECT` statement with other key clauses to explore your data.
{{< children type="anchored-list" >}}
{{< children readmore=true hr=true >}}
## Download sample data
The example InfluxQL queries in this documentation use publicly available [National Oceanic and Atmospheric Administration (NOAA)](https://www.noaa.gov/) data.
To download a subset of NOAA data used in examples, run the script under [NOAA water sample data](/influxdb/v2.4/reference/sample-data/#noaa-water-sample-data) (for example, copy and paste the script into your Data Explorer - Script Editor), and replace "example-org" in the script with the name of your InfluxDB organization.
Let's get acquainted with this subsample of the data in the `h2o_feet` measurement:
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
|time | level description | location | water_level |
| :------------------- | :------------------ | :----------------------- |----------------------:|
| 2019-08-18T00:00:00Z | between 6 and 9 feet |coyote_creek | 8.1200000000 |
| 2019-08-18T00:00:00Z | below 3 feet | santa_monica | 2.0640000000 |
| 2019-08-18T00:06:00Z | between 6 and 9 feet | coyote_creek | 8.0050000000 |
| 2019-08-18T00:06:00Z | below 3 feet| santa_monica | 2.1160000000 |
| 2019-08-18T00:12:00Z | between 6 and 9 feet| coyote_creek | 7.8870000000 |
| 2019-08-18T00:12:00Z | below 3 feet | santa_monica | 2.0280000000 |
The data in the `h2o_feet` [measurement](/influxdb/v2.4/reference/glossary/#measurement)
occurs at six-minute time intervals.
This measurement has one [tag key](/influxdb/v2.4/reference/glossary/#tag-key)
(`location`) which has two [tag values](/influxdb/v2.4/reference/glossary/#tag-value):
`coyote_creek` and `santa_monica`.
The measurement also has two [fields](/influxdb/v2.4/reference/glossary/#field):
`level description` stores string [field values](/influxdb/v2.4/reference/glossary/#field-value)
and `water_level` stores float field values.
### Configure timestamps in the InfluxQL shell
By default, the [InfluxQL shell](/influxdb/v2.4/tools/influxql-shell/) returns timestamps in
nanosecond UNIX epoch format by default.
To return human-readable RFC3339 timestamps instead of Unix nanosecond timestamps,
use the [precision helper command](/influxdb/v2.4/tools/influxql-shell/#precision) ` to configure
the timestamp format:
```sql
precision rfc3339
```
The [InfluxDB API](/influxdb/v2.4/reference/api/influxdb-1x/) returns timestamps
in [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) format by default.
Specify alternative formats with the [`epoch` query string parameter](/influxdb/v2.4/reference/api/influxdb-1x/).

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,241 @@
---
title: LIMIT and SLIMIT clauses
description: >
Use the `LIMIT` and `SLIMIT` clauses to limit the number of [points](/influxdb/v2.4/reference/glossary/#point) and [series](/influxdb/v2.4/reference/glossary/#series) returned in queries.
menu:
influxdb_2_4:
name: LIMIT and SLIMIT clauses
parent: Explore data
weight: 305
list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] LIMIT <N>
```
---
Use `LIMIT` and `SLIMIT` to limit the number of [points](/influxdb/v2.4/reference/glossary/#point) and [series](/influxdb/v2.4/reference/glossary/#series) returned per query.
- [LIMIT clause](#limit-clause)
- [Syntax](#syntax)
- [Examples](#examples)
- [SLIMIT clause](#slimit-clause)
- [Syntax](#syntax-1)
- [Examples](#examples-2)
- [Use LIMIT and SLIMIT together](#use-limit-and-slimit-together)
## LIMIT clause
`LIMIT <N>` returns the first `N` points from the specified [measurement](/influxdb/v2.4/reference/glossary/#measurement).
### Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] LIMIT <N>
```
`N` specifies the number of points to return from the specified measurement . If `N` is greater than the number of points in a measurement, InfluxDB returns all points from the measurement.
{{% note %}}
**IMPORTANT:** The `LIMIT` clause must appear in the order outlined in the syntax above.
{{% /note %}}
### Examples
{{< expand-wrapper >}}
{{% expand "Limit the number of points returned" %}}
```sql
SELECT "water_level","location" FROM "h2o_feet" LIMIT 3
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level | location |
| :-------------- | :-------------------| ------------------:|
| 2019-08-17T00:00:00Z | 8.1200000000 | coyote_creek|
| 2019-08-17T00:00:00Z | 2.0640000000 |santa_monica |
| 2019-08-17T00:06:00Z | 8.0050000000 |coyote_creek |
The query returns the three oldest points, determined by timestamp, from the `h2o_feet` [measurement](/influxdb/v2.4/reference/glossary/#measurement).
{{% /expand %}}
{{% expand "Limit the number of points returned and include a `GROUP BY` clause" %}}
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:42:00Z' GROUP BY *,time(12m) LIMIT 2
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | :-------------------------- |
| 2019-08-18T00:00:00Z | 8.4615000000 |
| 2019-08-18T00:12:00Z | 8.2725000000 |
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=santa_monica
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | :-------------------------- |
| 2019-08-18T00:00:00Z | 2.3655000000 |
| 2019-08-18T00:12:00Z | 2.3360000000 |
This query uses the InfluxQL [MEAN() function](/influxdb/v2.4/query-data/influxql/functions/aggregates/#mean) and a `GROUP BY` clause to calculate the average `water_level` for each [tag](/influxdb/v2.4/reference/glossary/#tag) and for each 12-minute interval in the queried time range. `LIMIT 2` requests the two oldest 12-minute averages (determined by timestamp).
Note that without `LIMIT 2`, the query would return four points per series; one for each 12-minute interval in the queried time range.
{{% /expand %}}
{{< /expand-wrapper >}}
## SLIMIT clause
`SLIMIT <N>` returns every [point](/influxdb/v2.4/reference/glossary/#point) from `N` [series](//influxdb/v2.4/reference/glossary/#series) in the specified [measurement](/influxdb/v2.4/reference/glossary/#measurement).
### Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] GROUP BY *[,time(<time_interval>)] [ORDER_BY_clause] SLIMIT <N>
```
`N` specifies the number of series to return from the specified measurement. If `N` is greater than the number of series in a measurement, InfluxDB returns all series from that measurement.
`SLIMIT` queries must include `GROUP BY *`. Note that the `SLIMIT` clause must appear in the order outlined in the syntax above.
### Examples
{{< expand-wrapper >}}
{{% expand "Limit the number of series returned" %}}
```sql
SELECT "water_level" FROM "h2o_feet" GROUP BY * SLIMIT 1
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------ | ---------------------:|
| 2019-08-17T00:00:00Z | 8.1200000000|
| 2019-08-17T00:06:00Z | 8.0050000000|
| 2019-08-17T00:12:00Z | 7.8870000000|
| 2019-08-17T00:18:00Z | 7.7620000000|
| 2019-08-17T00:24:00Z | 7.6350000000|
| 2019-08-17T00:30:00Z | 7.5000000000|
| 2019-08-17T00:36:00Z | 7.3720000000|
The results above include only the first few rows, as the data set is quite large. The query returns all `water_level` [points](/influxdb/v2.4/reference/glossary/#point) from one of the [series](/influxdb/v2.4/reference/glossary/#series) associated with the `h2o_feet` [measurement](/influxdb/v2.4/reference/glossary/#measurement).
{{% /expand %}}
{{% expand "Limit the number of series returned and include a `GROUP BY time()` clause" %}}
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:42:00Z' GROUP BY *,time(12m) SLIMIT 1
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 2019-08-18T00:00:00Z | 8.4615000000|
| 2019-08-18T00:12:00Z | 8.2725000000|
| 2019-08-18T00:24:00Z | 8.0710000000|
| 2019-08-18T00:36:00Z | 7.8330000000|
The query uses the InfluxQL [MEAN() function](/influxdb/v2.4/query-data/influxql/functions/aggregates/#mean)
and a time interval in the [GROUP BY clause](/influxdb/v2.4/query-data/influxql/explore-data/group-by/)
to calculate the average `water_level` for each 12-minute
interval in the queried time range.
`SLIMIT 1` requests a single series associated with the `h2o_feet` measurement.
Note that without `SLIMIT 1`, the query would return results for the two series
associated with the `h2o_feet` measurement: `location=coyote_creek` and
`location=santa_monica`.
{{% /expand %}}
{{< /expand-wrapper >}}
## Use LIMIT and SLIMIT together
`LIMIT <N>` followed by `SLIMIT <2>` returns the first `N1` [points](/influxdb/v2.4/reference/glossary/#point) from `N2` series in the specified measurement.
### Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] GROUP BY *[,time(<time_interval>)] [ORDER_BY_clause] LIMIT <N1> SLIMIT <N2>
```
`N1` specifies the number of points to return per measurement. If `N1` is greater than the number of points in a measurement, InfluxDB returns all points from that measurement.
`N2` specifies the number of series to return from the specified measurement. If `N2` is greater than the number of series in a measurement, InfluxDB returns all series from that measurement.
`SLIMIT` queries must include `GROUP BY *`. Note that the `SLIMIT` clause must appear in the order outlined in the syntax above.
### Examples
{{< expand-wrapper >}}
{{% expand "Limit the number of points and series returned" %}}
```sql
SELECT "water_level" FROM "h2o_feet" GROUP BY * LIMIT 3 SLIMIT 1
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
Tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------ | ---------------------:|
| 2019-08-17T00:00:00Z | 8.1200000000|
| 2019-08-17T00:06:00Z | 8.0050000000|
| 2019-08-17T00:12:00Z | 7.8870000000|
The query returns the three oldest points, determined by timestamp, from one of the series associated with the measurement `h2o_feet`.
{{% /expand %}}
{{% expand "Limit the number of points and series returned and include a `GROUP BY time()` clause" %}}
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:42:00Z' GROUP BY *,time(12m) LIMIT 2 SLIMIT 1
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
Tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 2019-08-18T00:00:00Z | 8.4615000000|
| 2019-08-18T00:12:00Z | 8.2725000000|
The query uses the InfluxQL function MEAN() and a time interval in the GROUP BY clause to calculate the average `water_level` for each 12-minute interval in the queried time range. `LIMIT 2` requests the two oldest 12-minute averages (determined by
timestamp) and `SLIMIT 1` requests a single series associated with the `h2o_feet` measurement.
Note that without `LIMIT 2 SLIMIT 1`, the query would return four points for each of the two series associated with the `h2o_feet` measurement.
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -0,0 +1,206 @@
---
title: OFFSET and SOFFSET clauses
description: >
Use the `OFFSET` and `SOFFSET` clauses to paginate [points](/influxdb/v2.4/reference/glossary/#point) and [series](/influxdb/v2.4/reference/glossary/#series).
menu:
influxdb_2_4:
name: OFFSET and SOFFSET clauses
parent: Explore data
weight: 306
list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] LIMIT_clause OFFSET <N> [SLIMIT_clause]
```
---
Use `OFFSET` and `SOFFSET` to paginate [points](/influxdb/v2.4/reference/glossary/#point) and [series](/influxdb/v2.4/reference/glossary/#series) returned.
- [OFFSET clause](#offset-clause)
- [Syntax](#syntax)
- [Examples](#examples)
- [The SOFFSET clause](#soffset-clause)
- [Syntax](#syntax-1)
- [Examples](#examples-1)
## `OFFSET` clause
`OFFSET <N>` paginates `N` [points](/influxdb/v2.4/reference/glossary/#point) in the query results.
### Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] LIMIT_clause OFFSET <N> [SLIMIT_clause]
```
`N` specifies the number of points to paginate. The `OFFSET` clause requires a [`LIMIT` clause](/influxdb/v2.4/query-data/influxql/explore-data/limit-and-slimit/#limit-clause).
{{% note %}}
**Note:** InfluxDB returns no results if the `WHERE clause` includes a time range and the `OFFSET clause` would cause InfluxDB to return points with timestamps outside of that time range.
{{% /note %}}
### Examples
{{< expand-wrapper >}}
{{% expand "Paginate points" %}}
```sql
SELECT "water_level","location" FROM "h2o_feet" LIMIT 3 OFFSET 3
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level | location |
| :-------------- | -------------------:| :------------------|
| 2019-08-17T00:06:00Z | 2.1160000000 | santa_monica|
| 2019-08-17T00:12:00Z | 7.8870000000 | coyote_creek|
| 2019-08-17T00:12:00Z | 2.0280000000 | santa_monica|
The query returns the fourth, fifth, and sixth points from the `h2o_feet` [measurement](/influxdb/v2.4/reference/glossary/#measurement). If the query did not include `OFFSET 3`, it would return the first, second,
and third points from that measurement.
{{% /expand %}}
{{% expand "Paginate points and include several clauses" %}}
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:42:00Z' GROUP BY *,time(12m) ORDER BY time DESC LIMIT 2 OFFSET 2 SLIMIT 1
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 2019-08-18T00:12:00Z | 8.2725000000 |
| 2019-08-18T00:00:00Z | 8.4615000000 |
In this example:
- The [`SELECT clause`](/influxdb/v2.4/query-data/influxql/explore-data/select/) specifies the InfluxQL [MEAN() function](/influxdb/v2.4/query-data/influxql/functions/aggregates/#mean).
- The [`FROM clause`] (/influxdb/v2.4/query-data/influxql/explore-data/select/#from-clause) specifies a single measurement.
- The [`WHERE` clause](/influxdb/v2.4/query-data/influxql/explore-data/where/) specifies the time range for the query.
- The [`GROUP BY` clause](/influxdb/v2.4/query-data/influxql/explore-data/group-by/) groups results by all tags (`*`) and into 12-minute intervals.
- The [`ORDER BY time DESC` clause](/influxdb/v2.4/query-data/influxql/explore-data/order-by/#order-by-time-desc) returns results in descending timestamp order.
- The [`LIMIT 2` clause](/influxdb/v2.4/query-data/influxql/explore-data/limit-and-slimit/) limits the number of points returned to two.
- The `OFFSET 2` clause excludes the first two averages from the query results.
- The [`SLIMIT 1` clause](/influxdb/v2.4/query-data/influxql/explore-data/limit-and-slimit/) limits the number of series returned to one.
Without `OFFSET 2`, the query would return the first two averages of the query results:
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 2019-08-18T00:36:00Z | 7.8330000000 |
| 2019-08-18T00:24:00Z | 8.0710000000 |
{{< /expand >}}
{{< /expand-wrapper >}}
## `SOFFSET` clause
`SOFFSET <N>` paginates `N` [series](/influxdb/v2.4/reference/glossary/#series) in the query results.
### Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] GROUP BY *[,time(time_interval)] [ORDER_BY_clause] [LIMIT_clause] [OFFSET_clause] SLIMIT_clause SOFFSET <N>
```
`N` specifies the number of [series](/influxdb/v2.4/reference/glossary/#series) to paginate.
The `SOFFSET` clause requires an [`SLIMIT` clause](/influxdb/v2.4/query-data/influxql/explore-data/limit-and-slimit/.
Using the `SOFFSET` clause without an `SLIMIT` clause can cause [inconsistent
query results](https://github.com/influxdata/influxdb/issues/7578).
`SLIMIT` queries must include `GROUP BY *`.
{{% note %}}
**Note:** InfluxDB returns no results if the `SOFFSET` clause paginates through more than the total number of series.
{{% /note %}}
### Examples
{{% expand-wrapper %}}
{{% expand "Paginate series" %}}
#### Paginate series
```sql
SELECT "water_level" FROM "h2o_feet" GROUP BY * SLIMIT 1 SOFFSET 1
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=santa_monica
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------ | ---------------------:|
| 2019-08-17T00:00:00Z | 2.0640000000|
| 2019-08-17T00:06:00Z | 2.1160000000|
| 2019-08-17T00:12:00Z | 2.0280000000|
| 2019-08-17T00:18:00Z | 2.1260000000|
| 2019-08-17T00:24:00Z | 2.0410000000|
| 2019-08-17T00:30:00Z | 2.0510000000|
| 2019-08-17T00:36:00Z | 2.0670000000|
| 2019-08-17T00:42:00Z | 2.0570000000|
The results above are partial, as the data set is quite large. The query returns data for the series associated with the `h2o_feet`
measurement and the `location = santa_monica` tag. Without `SOFFSET 1`, the query returns data for the series associated with the `h2o_feet` measurement and the `location = coyote_creek` tag.
{{% /expand %}}
{{% expand "Paginate points and include several clauses" %}}
#### Paginate series and include all clauses
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:42:00Z' GROUP BY *,time(12m) ORDER BY time DESC LIMIT 2 OFFSET 2 SLIMIT 1 SOFFSET 1
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=santa_monica
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 2019-08-18T00:12:00Z | 2.3360000000|
| 2019-08-18T00:00:00Z | 2.3655000000|
In this example:
- The [`SELECT` clause](/influxdb/v2.4/query-data/influxql/explore-data/select/) specifies an InfluxQL [function](/influxdb/v2.4/query-data/influxql/functions/).
- The [`FROM` clause](/influxdb/v2.4/query-data/influxql/explore-data/select/#from-clause) specifies a single measurement.
- The [`WHERE` clause](/influxdb/v2.4/query-data/influxql/explore-data/where/) specifies the time range for the query.
- The [`GROUP BY` clause](/influxdb/v2.4/query-data/influxql/explore-data/group-by/) groups results by all tags (`*`) and into 12-minute intervals.
- The [`ORDER BY time DESC` clause](/influxdb/v2.4/query-data/influxql/explore-data/order-by/#order-by-time-desc) returns results in descending timestamp order.
- The [`LIMIT 2` clause](/influxdb/v2.4/query-data/influxql/explore-data/limit-and-slimit/) limits the number of points returned to two.
- The [`OFFSET 2` clause](/influxdb/v2.4/query-data/influxql/explore-data/offset-and-soffset/) excludes the first two averages from the query results.
- The [`SLIMIT 1` clause](/influxdb/v2.4/query-data/influxql/explore-data/limit-and-slimit/) limits the number of series returned to one.
- The [`SOFFSET 1`](/influxdb/v2.4/query-data/influxql/explore-data/offset-and-soffset/) clause paginates the series returned.
Without `SOFFSET 1`, the query would return the results for a different series:
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
| time | mean |
| :------------------ | ---------------------:|
| 2019-08-18T00:12:00Z | 8.2725000000 |
| 2019-08-18T00:00:00Z | 8.4615000000 |
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -0,0 +1,119 @@
---
title: ORDER BY clause
list_title: ORDER BY clause
description: >
Use the `ORDER BY` clause to sort data in ascending or descending order.
menu:
influxdb_2_4:
name: ORDER BY clause
parent: Explore data
weight: 304
list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] ORDER BY time DESC
```
---
Use the `ORDER BY` clause to sort data.
- [Syntax](#syntax)
- [Examples](#examples)
## ORDER BY time DESC
By default, InfluxDB returns results in ascending time order; the first [point](/influxdb/v2.4/reference/glossary/#point)
returned has the oldest [timestamp](/influxdb/v2.4/reference/glossary/#timestamp) and
the last point returned has the most recent timestamp.
`ORDER BY time DESC` reverses that order such that InfluxDB returns the points
with the most recent timestamps first.
### Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] ORDER BY time DESC
```
If the query includes a `GROUP BY` clause, `ORDER by time DESC` must appear **after** the `GROUP BY` clause.
If the query includes a `WHERE` clause and no `GROUP BY` clause, `ORDER by time DESC` must appear **after** the `WHERE` clause.
### Examples
{{< expand-wrapper >}}
{{% expand "Return the newest points first" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" = 'santa_monica' ORDER BY time DESC
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :-------------- | ------------------:|
| 2019-09-17T21:42:00Z | 4.9380000000|
| 2019-09-17T21:36:00Z | 5.0660000000|
| 2019-09-17T21:30:00Z | 5.0100000000|
| 2019-09-17T21:24:00Z | 5.0130000000|
| 2019-09-17T21:18:00Z | 5.0720000000|
The query returns the points with the most recent timestamps from the
`h2o_feet` [measurement](/influxdb/v2.4/reference/glossary/#measurement) first.
Without `ORDER by time DESC`, the query would return the following output:
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :-------------- | ------------------:|
| 2019-08-17T00:00:00Z | 2.0640000000|
| 2019-08-17T00:06:00Z | 2.1160000000|
| 2019-08-17T00:12:00Z | 2.0280000000|
| 2019-08-17T00:18:00Z | 2.1260000000|
{{% /expand %}}
{{% expand "Return the newest points first and include a `GROUP BY time()` clause" %}}
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:42:00Z' GROUP BY time(12m) ORDER BY time DESC
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | mean |
| :-------------- | ------------------:|
| 2019-08-18T00:36:00Z | 4.9712860355|
| 2019-08-18T00:24:00Z | 5.1682500000|
| 2019-08-18T00:12:00Z | 5.3042500000|
| 2019-08-18T00:00:00Z | 5.4135000000|
The query uses the InfluxQL [MEAN() function](/influxdb/v2.4/query-data/influxql/functions/aggregates/#mean)
and a time interval in the [GROUP BY clause](/influxdb/v2.4/query-data/influxql/explore-data/group-by/)
to calculate the average `water_level` for each 12-minute
interval in the queried time range.
[`ORDER BY time DESC`](/influxdb/v2.4/query-data/influxql/explore-data/order-by/#order-by-time-desc) returns the most recent 12-minute time intervals
first.
Without `ORDER BY time DESC`, the query would return the following output:
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | mean |
| :-------------- | ------------------:|
| 2019-08-18T00:00:00Z | 5.4135000000|
| 2019-08-18T00:12:00Z | 5.3042500000|
| 2019-08-18T00:24:00Z | 5.1682500000|
| 2019-08-18T00:36:00Z | 4.9712860355|
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -0,0 +1,216 @@
---
title: Regular expressions
list_title: Regular expressions
description: >
Use `regular expressions` to match patterns in your data.
menu:
influxdb_2_4:
name: Regular expressions
identifier: influxql-regular-expressions
parent: Explore data
weight: 313
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>/
```
---
InfluxQL supports using regular expressions when specifying:
- [field keys](/influxdb/v2.4/reference/glossary/#field-key) and [tag keys](/influxdb/v2.4/reference/glossary/#tag-key) in the [`SELECT` clause](/influxdb/v2.4/query-data/influxql/explore-data/select/).
- [measurements](/influxdb/v2.4/reference/glossary/#measurement) in the [`FROM` clause](/influxdb/v2.4/query-data/influxql/explore-data/select/#from-clause).
- [tag values](/influxdb/v2.4/reference/glossary/#tag-value) and string [field values](/influxdb/v2.4/reference/glossary/#field-value) in the [`WHERE` clause](/influxdb/v2.4/query-data/influxql/explore-data/where/).
- [tag keys](/influxdb/v2.4/reference/glossary/#tag-key) in the [`GROUP BY` clause](/influxdb/v2.4/query-data/influxql/explore-data/group-by/)
Regular expressions in InfluxQL only support string comparisons and can only evaluate [fields](/influxdb/v2.4/reference/glossary/#field) with string values.
{{% note %}}
**Note:** Regular expression comparisons are more computationally intensive than exact
string comparisons. Queries with regular expressions are not as performant
as those without.
{{% /note %}}
- [Syntax](#syntax)
- [Examples](#examples)
## Syntax
```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 surrounded by `/` characters and use
[Golang's regular expression syntax](http://golang.org/pkg/regexp/syntax/).
## Supported operators
`=~`: matches against
`!~`: doesn't match against
### Examples
{{< expand-wrapper >}}
{{% expand "Use a regular expression to specify field keys and tag keys in the SELECT clause" %}}
```sql
SELECT /l/ FROM "h2o_feet" LIMIT 1
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level|
| :------------ | :----------------| :--------------| --------------:|
| 2019-08-17T00:00:00Z | below 3 feet | santa_monica | 2.0640000000|
The query selects all field keys and tag keys that include an `l`.
Note that the regular expression in the `SELECT` clause must match at least one
field key in order to return results for a tag key that matches the regular
expression.
Currently, there is no syntax to distinguish between regular expressions for
field keys and regular expressions for tag keys in the `SELECT` clause.
The syntax `/<regular_expression>/::[field | tag]` is not supported.
{{% /expand %}}
{{% expand "Use a regular expression to specify measurements in the FROM clause" %}}
```sql
SELECT MEAN("degrees") FROM /temperature/
```
Output:
{{% influxql/table-meta %}}
Name: average_temperature
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 1970-01-01T00:00:00Z | 79.9847293223 |
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 1970-01-01T00:00:00Z | 64.9980273540 |
This query uses the InfluxQL [MEAN() function](/influxdb/v2.4/query-data/influxql/functions/aggregates/#mean) to calculate the average `degrees` for every [measurement](/influxdb/v2.4/reference/glossary/#measurement) in the [NOAA sample data] that contains the word `temperature`.
{{% /expand %}}
{{% expand "Use a regular expression to specify tag values in the WHERE clause" %}}
```sql
SELECT MEAN(water_level) FROM "h2o_feet" WHERE "location" =~ /[m]/ AND "water_level" > 3
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 1970-01-01T00:00:00Z | 4.4710766395|
This query uses the InfluxQL [MEAN() function](/influxdb/v2.4/query-data/influxql/functions/aggregates/#mean) to calculate the average `water_level` where the [tag value](/influxdb/v2.4/reference/glossary/#measurement) of `location` includes an `m` and `water_level` is greater than three.
{{% /expand %}}
{{% expand "Use a regular expression to specify a tag with no value in the WHERE clause" %}}
```sql
SELECT * FROM "h2o_feet" WHERE "location" !~ /./
>
```
The query selects all data from the `h2o_feet` measurement where the `location`
[tag](/influxdb/v2.4/reference/glossary/#tag) has no value.
Every data [point](/influxdb/v2.4/reference/glossary/#point) in the [NOAA water sample data](/influxdb/v2.4/reference/sample-data/#noaa-water-sample-data) has a tag value for `location`.
It's possible to perform this same query without a regular expression.
See the [Frequently Asked Questions](/influxdb/v2.4/reference/faq/#how-do-i-query-data-by-a-tag-with-a-null-value)
document for more information.
{{% /expand %}}
{{% expand "Use a regular expression to specify a tag with a value in the WHERE clause" %}}
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE "location" =~ /./
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 1970-01-01T00:00:00Z | 4.4418434585|
This query uses the InfluxQL [MEAN() function](/influxdb/v2.4/query-data/influxql/functions/aggregates/#mean) to calculate the average `water_level` across all data with a tag value for `location`.
{{% /expand %}}
{{% expand "Use a regular expression to specify a field value in the WHERE clause" %}}
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE "location" = 'santa_monica' AND "level description" =~ /between/
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 1970-01-01T00:00:00Z | 4.4713666916
This query uses the InfluxQL [MEAN() function](/influxdb/v2.4/query-data/influxql/functions/aggregates/#mean)
to calculate the average `water_level` for all data where the field value of `level description` includes the word `between`.
{{% /expand %}}
{{% expand "Use a regular expression to specify tag keys in the GROUP BY clause" %}}
```sql
SELECT FIRST("index") FROM "h2o_quality" GROUP BY /l/
```
Output:
{{% influxql/table-meta %}}
name: h2o_quality
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ |-------------------:|
| 2019-08-17T00:00:00Z | 41.0000000000 |
{{% influxql/table-meta %}}
name: h2o_quality
tags: location=santa_monica
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ |-------------------:|
| 2019-08-17T00:00:00Z | 99.0000000000 |
This query uses the InfluxQL [FIRST() function](/influxdb/v2.4/query-data/influxql/functions/selectors/#first)
to select the first value of `index` for every tag that includes the letter `l`
in its tag key.
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -0,0 +1,681 @@
---
title: SELECT statement
list_title: SELECT statement
description: >
Use the `SELECT` statement to query data from a particular [measurement](/influxdb/v2.4/reference/glossary/#measurement) or measurements.
menu:
influxdb_2_4:
name: SELECT statement
parent: Explore data
weight: 301
list_code_example: |
```sql
SELECT <field_key>[,<field_key>,<tag_key>] FROM <measurement_name>[,<measurement_name>]
```
---
Use the `SELECT` statement to query data from a particular [measurement](/influxdb/v2.4/reference/glossary/#measurement) or measurements.
- [Syntax](#syntax)
- [Examples](#examples)
- [Common issues](#common-issues-with-the-select-statement)
- [Regular expressions](#regular-expressions)
- [Data types and cast operations](#data-types-and-cast-operations)
- [Merge behavior](#merge-behavior)
- [Multiple statements](#multiple-statements)
## Syntax
```sql
SELECT <field_key>[,<field_key>,<tag_key>] FROM <measurement_name>[,<measurement_name>]
```
{{% note %}}
**Note:** The `SELECT` statement **requires** a `SELECT` clause and a `FROM` clause.
{{% /note %}}
### `SELECT` clause
The `SELECT` clause supports several formats for specifying data:
- `SELECT *` - Returns all [fields](/influxdb/v2.4/reference/glossary/#field) and [tags](/influxdb/v2.4/reference/glossary/#tag).
- `SELECT "<field_key>"` - Returns a specific field.
- `SELECT "<field_key>","<field_key>"` - Returns more than one field.
- `SELECT "<field_key>","<tag_key>"` - Returns a specific field and tag. The `SELECT` clause must specify at least one field when it includes a tag.
- `SELECT "<field_key>"::field,"<tag_key>"::tag` - Returns a specific field and tag.
The `::[field | tag]` syntax specifies the [identifier's](/influxdb/v2.4/reference/syntax/influxql/spec/#identifiers) type.
Use this syntax to differentiate between field keys and tag keys with the same name.
Other supported features include:
- [Functions](/influxdb/v2.4/query-data/influxql/functions/)
- [Basic cast operations](#data-types-and-cast-operations)
- [Regular expressions](/influxdb/v2.4/query-data/influxql/explore-data/regular-expressions/)
{{% note %}}
**Note:** The SELECT statement cannot include an aggregate function **and** a non-aggregate function, field key, or tag key. For more information, see [error about mixing aggregate and non-aggregate queries](/enterprise_influxdb/v1.9/troubleshooting/errors/#error-parsing-query-mixing-aggregate-and-non-aggregate-queries-is-not-supported).
{{% /note %}}
### `FROM` clause
The `SELECT` clause specifies the measurement to query.
This clause supports several formats for specifying a [measurement(s)](/influxdb/v2.4/reference/glossary/#measurement):
- `FROM <measurement_name>` - Returns data from a measurement.
- `FROM <measurement_name>,<measurement_name>` - Returns data from more than one measurement.
- `FROM <database_name>.<retention_policy_name>.<measurement_name>` - Returns data from a fully qualified measurement.
- `FROM <database_name>..<measurement_name>` - Returns data from a measurement.
#### Quoting
[Identifiers](/influxdb/v2.4/reference/syntax/influxql/spec/#identifiers) **must** be double quoted if they contain characters other than `[A-z,0-9,_]`,
begin with a digit, or are an [InfluxQL keyword](https://github.com/influxdata/influxql/blob/master/README.md#keywords).
While not always necessary, we recommend that you double quote identifiers.
{{% note %}}
**Note:** InfluxQL quoting guidelines differ from [line protocol quoting guidelines](/influxdb/v2.4/reference/syntax/line-protocol/#quotes).
Please review the [rules for single and double-quoting](/influxdb/v2.4/reference/syntax/line-protocol/#quotes) in queries.
{{% /note %}}
### Examples
{{< expand-wrapper >}}
{{% expand "Select all fields and tags from a measurement" %}}
```sql
SELECT * FROM "h2o_feet"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level |
| :-------------- |:----------------------| :-------------------| ------------------:|
| 2019-08-17T00:00:00Z | below 3 feet |santa_monica | 2.0640000000|
| 2019-08-17T00:00:00Z | between 6 and 9 feet | coyote_creek | 8.1200000000|
| 2019-08-17T00:06:00Z | below 3 feet| santa_monica | 2.1160000000|
| 2019- 08-17T00:06:00Z | between 6 and 9 feet |coyote_creek |8.0050000000|
| 2019-08-17T00:12:00Z | below 3 feet | santa_monica | 2.0280000000|
| 2019-08-17T00:12:00Z | between 6 and 9 feet | coyote_creek | 7.8870000000|
| 2019-08-17T00:18:00Z | below 3 feet |santa_monica | 2.1260000000|
The data above is a partial listing of the query output, as the result set is quite large. The query selects all [fields](/influxdb/v2.4/reference/glossary/#field) and
[tags](/influxdb/v2.4/reference/glossary/#tag) from the `h2o_feet`
[measurement](/influxdb/v2.4/reference/glossary/#measurement).
{{% /expand %}}
{{% expand "Select specific tags and fields from a measurement" %}}
```sql
SELECT "level description","location","water_level" FROM "h2o_feet"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level |
| :-------------- |:----------------------| :-------------------| ------------------:|
| 2019-08-17T00:00:00Z | below 3 feet |santa_monica | 2.0640000000|
| 2019-08-17T00:00:00Z | between 6 and 9 feet | coyote_creek | 8.1200000000|
The query selects the `level description` field, the `location` tag, and the
`water_level` field.
{{% note %}}
**Note:** The `SELECT` clause must specify at least one field when it includes
a tag.
{{% /note %}}
{{% /expand %}}
{{% expand "Select specific tags and fields from a measurement and provide their identifier type" %}}
```sql
SELECT "level description"::field,"location"::tag,"water_level"::field FROM "h2o_feet"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level |
| :-------------- |:----------------------| :-------------------| ------------------:|
| 2019-08-17T00:24:00Z | between 6 and 9 feet | coyote_creek | 7.6350000000|
| 2019-08-17T00:30:00Z | below 3 feet | santa_monica | 2.0510000000|
| 2019-08-17T00:30:00Z | between 6 and 9 feet | coyote_creek | 7.5000000000|
| 2019-08-17T00:36:00Z | below 3 feet | santa_monica | 2.0670000000 |
| 2019-08-17T00:36:00Z | between 6 and 9 feet | coyote_creek | 7.3720000000 |
| 2019-08-17T00:42:00Z | below 3 feet | santa_monica | 2.0570000000 |
The query selects the `level description` field, the `location` tag, and the
`water_level` field from the `h2o_feet` measurement.
The `::[field | tag]` syntax specifies if the
[identifier](/influxdb/v2.4/reference/syntax/influxql/spec/#identifiers) is a field or tag.
Use `::[field | tag]` to differentiate between [an identical field key and tag key ](/v2.4/reference/faq/#how-do-i-query-data-with-an-identical-tag-key-and-field-key).
That syntax is not required for most use cases.
{{% /expand %}}
{{% expand "Select all fields from a measurement" %}}
```sql
SELECT *::field FROM "h2o_feet"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description| water_level |
| :-------------- | :-------------------| ------------------:|
| 2019-08-17T00:00:00Z | below 3 feet | 2.0640000000 |
| 2019-08-17T00:00:00Z | between 6 and 9 feet | 8.1200000000|
| 2019-08-17T00:06:00Z | below 3 feet | 2.1160000000|
| 2019-08-17T00:06:00Z | between 6 and 9 feet | 8.0050000000|
| 2019-08-17T00:12:00Z | below 3 feet | 2.0280000000|
| 2019-08-17T00:12:00Z | between 6 and 9 feet | 7.8870000000|
The query selects all fields from the `h2o_feet` measurement.
The `SELECT` clause supports combining the `*` syntax with the `::` syntax.
{{% /expand %}}
{{% expand "Select a specific field from a measurement and perform basic arithmetic" %}}
```sql
SELECT ("water_level" * 2) + 4 FROM "h2o_feet"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :-------------- | ------------------:|
| 2019-08-17T00:00:00Z | 20.2400000000 |
| 2019-08-17T00:00:00Z | 8.1280000000 |
| 2019-08-17T00:06:00Z | 20.0100000000 |
| 2019-08-17T00:06:00Z | 8.2320000000 |
| 2019-08-17T00:12:00Z | 19.7740000000 |
| 2019-08-17T00:12:00Z | 8.0560000000 |
The query multiplies `water_level`'s field values by two and adds four to those
values.
{{% note %}}
**Note:** InfluxDB follows the standard order of operations.
See [InfluxQL mathematical operators](/influxdb/v2.4/query-data/influxql/math-operators/)
for more on supported operators.
{{% /note %}}
{{% /expand %}}
{{% expand "Select all data from more than one measurement" %}}
```sql
SELECT * FROM "h2o_feet","h2o_pH"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | pH | water_level |
| :-------------- |:-------------| :----------------| :-------------| --------------:|
| 2019-08-17T00:00:00Z | below 3 feet | santa_monica | <nil> | 2.0640000000|
| 2019-08-17T00:00:00Z | between 6 and 9 feet | coyote_creek | <nil> | 8.1200000000|
| 2019-08-17T00:06:00Z | below 3 feet | santa_monica | <nil> | 2.1160000000|
| 2019-08-17T00:06:00Z | between 6 and 9 feet | coyote_creek | <nil> | 8.0050000000|
| 2019-08-17T00:12:00Z | below 3 feet | santa_monica | <nil> | 2.0280000000 |
| 2019-08-17T00:12:00Z | between 6 and 9 feet | coyote_creek | <nil> | 7.8870000000|
| 2019-08-17T00:18:00Z | below 3 feet | santa_monica | <nil> | 2.1260000000|
| 2019-08-17T00:18:00Z | between 6 and 9 feet | coyote_creek | <nil> | 7.7620000000|
{{% influxql/table-meta %}}
Name: h2o_pH
{{% /influxql/table-meta %}}
| time | level description | location | pH | water_level |
| :-------------- |:-------------| :----------------| :-------------| --------------:|
| 2019-08-17T00:00:00Z | <nil> | coyote_creek | 7.00| <nil> |
| 2019-08-17T00:06:00Z | <nil> |coyote_creek | 8.00 | <nil> |
| 2019-08-17T00:06:00Z | <nil> |santa_monica | 6.00 | <nil> |
| 2019-08-17T00:12:00Z | <nil> |coyote_creek |8.00 | <nil> |
The query selects all fields and tags from two measurements: `h2o_feet` and
`h2o_pH`.
Separate multiple measurements with a comma (`,`).
{{% /expand %}}
{{% expand "Select all data from a measurement in a particular database" %}}
```sql
SELECT * FROM noaa.."h2o_feet"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level |
| :-------------- |:----------------------| :-------------------| ------------------:|
| 2019-08-17T00:00:00Z | below 3 feet |santa_monica | 2.0640000000|
| 2019-08-17T00:00:00Z | between 6 and 9 feet | coyote_creek | 8.1200000000|
| 2019-08-17T00:06:00Z | below 3 feet| santa_monica | 2.1160000000|
| 2019- 08-17T00:06:00Z | between 6 and 9 feet |coyote_creek |8.0050000000|
| 2019-08-17T00:12:00Z | below 3 feet | santa_monica | 2.0280000000|
| 2019-08-17T00:12:00Z | between 6 and 9 feet | coyote_creek | 7.8870000000|
The query selects data from the `h2o_feet` measurement in the `noaa` database.
The `..` indicates the `DEFAULT` retention policy for the specified database.
{{% /expand %}}
{{< /expand-wrapper >}}
## Common issues with the SELECT statement
### Selecting tag keys in the SELECT statement
A query requires at least one [field key](/influxdb/v2.4/reference/glossary/#field-key)
in the `SELECT` clause to return data.
If the `SELECT` clause only includes a single [tag key](/influxdb/v2.4/reference/glossary/#tag-key) or several tag keys, the
query returns an empty response.
#### Example
The following query returns no data because it specifies a single tag key (`location`) in
the `SELECT` clause:
```sql
SELECT "location" FROM "h2o_feet"
> No results
```
To return any data associated with the `location` tag key, the query's `SELECT`
clause must include at least one field key (`water_level`):
```sql
SELECT "water_level","location" FROM "h2o_feet"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level | location |
| :-------------- | :-------------------| ------------------:|
| 2019-08-17T00:00:00Z | 8.1200000000 | coyote_creek |
| 2019-08-17T00:00:00Z | 2.0640000000 | santa_monica |
| 2019-08-17T 00:06:00Z | 8.0050000000 | coyote_creek |
| 2019-08-17T00:06:00Z | 2.1160000000 | santa_monica |
| 2019-08-17T00:12:00Z | 7.8870000000 | coyote_creek |
| 2019-08-17T00:12:00Z | 2.0280000000 | santa_monica |
| 2019-08-17T00:18:00Z | 7.7620000000 | coyote_creek |
| 2019-08-17T00:18:00Z | 2.1260000000 | santa_monica |
## Regular expressions
InfluxQL supports using regular expressions when specifying:
- [field keys](/influxdb/v2.4/reference/glossary/#field-key) and [tag keys](/influxdb/v2.4/reference/glossary/#tag-key) in the [`SELECT` clause](/influxdb/v2.4/query-data/influxql/explore-data/select/)
- [measurements](/influxdb/v2.4/reference/glossary/#measurement) in the [`FROM` clause](/influxdb/v2.4/query-data/influxql/explore-data/select/#from-clause)
- [tag values](/influxdb/v2.4/reference/glossary/#tag-value) and string [field values](/influxdb/v2.4/reference/glossary/#field-value) in the [`WHERE` clause](/influxdb/v2.4/query-data/influxql/explore-data/where/).
- [tag keys](/influxdb/v2.4/reference/glossary/#tag-key) in the [`GROUP BY` clause](/influxdb/v2.4/query-data/influxql/explore-data/group-by/)
Currently, InfluxQL does not support using regular expressions to match
non-string field values in the
`WHERE` clause,
[databases](/influxdb/v2.4/reference/glossary/#database), and
[retention policies](/influxdb/v2.4/reference/glossary/#retention-policy-rp).
{{% note %}}
**Note:** Regular expression comparisons are more computationally intensive than exact
string comparisons. Queries with regular expressions are not as performant
as those without.
{{% /note %}}
## Syntax
```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 surrounded by `/` characters and use
[Golang's regular expression syntax](http://golang.org/pkg/regexp/syntax/).
## Supported operators
`=~`: matches against
`!~`: doesn't match against
## Examples
{{< expand-wrapper >}}
{{% expand "Use a regular expression to specify field keys and tag keys in the SELECT statement" %}}
#### Use a regular expression to specify field keys and tag keys in the SELECT statement
```sql
SELECT /l/ FROM "h2o_feet" LIMIT 1
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level |
| :-------------- |:----------------------| :-------------------| ------------------:|
| 2019-08-17T00:00:00Z | below 3 feet | santa_monica | 2.0640000000 |
The query selects all [field keys](/influxdb/v2.4/reference/glossary/#field-key)
and [tag keys](/influxdb/v2.4/reference/glossary/#tag-key) that include an `l`.
Note that the regular expression in the `SELECT` clause must match at least one
field key in order to return results for a tag key that matches the regular
expression.
Currently, there is no syntax to distinguish between regular expressions for
field keys and regular expressions for tag keys in the `SELECT` clause.
The syntax `/<regular_expression>/::[field | tag]` is not supported.
{{% /expand %}}
{{% expand "Use a regular expression to specify measurements in the FROM clause" %}}
```sql
SELECT MEAN("degrees") FROM /temperature/
```
Output:
{{% influxql/table-meta %}}
Name: average_temperature
{{% /influxql/table-meta %}}
| time | mean|
| :-------------- |----------------------:|
| 1970-01-01T00:00:00Z | 79.9847293223
{{% influxql/table-meta %}}
Name: h2o_temperature
{{% /influxql/table-meta %}}
| time | mean|
| :-------------- |----------------------:|
| 1970-01-01T00:00:00Z | 64.9980273540 |
This query uses the InfluxQL [MEAN() function](/influxdb/v2.4/query-data/influxql/functions/aggregates/#mean) to calculate the average `degrees` for every [measurement](/influxdb/v2.4/reference/glossary/#measurement) in the `noaa` database that contains the word `temperature`.
{{% /expand %}}
{{< /expand-wrapper >}}
## Data types and cast operations
The [`SELECT` clause](#select-clause) supports specifying a [field's](/influxdb/v2.4/reference/glossary/#field) type and basic cast operations with the `::` syntax.
- [Data types](#data-types)
- [Cast operations](#cast-operations)
### Data types
[Field values](/influxdb/v2.4/reference/glossary/#field-value) can be floats, integers, strings, or booleans.
The `::` syntax allows users to specify the field's type in a query.
{{% note %}}
**Note:** Generally, it is not necessary to specify the field value type in the [`SELECT` clause](/influxdb/v2.4/query-data/influxql/explore-data/select/). In most cases, InfluxDB rejects any writes that attempt to write a [field value](/influxdb/v2.4/reference/glossary/#field-value) to a field that previously accepted field values of a different type.
{{% /note %}}
It is possible for field value types to differ across [shard groups](/influxdb/v2.4/reference/glossary/#shard-group).
In these cases, it may be necessary to specify the field value type in the
`SELECT` clause.
Please see the
[Frequently Asked Questions](/influxdb/v2.4/reference/faq/#how-does-influxdb-handle-field-type-discrepancies-across-shards)
document for more information on how InfluxDB handles field value type discrepancies.
### Syntax
```sql
SELECT_clause <field_key>::<type> FROM_clause
```
`type` can be `float`, `integer`, `string`, or `boolean`.
In most cases, InfluxDB returns no data if the `field_key` does not store data of the specified
`type`. See [Cast Operations](#cast-operations) for more information.
### Example
```sql
SELECT "water_level"::float FROM "h2o_feet" LIMIT 4
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
|time | water_level |
| :------------------ |-------------------:|
| 2019-08-17T00:00:00Z | 8.1200000000 |
| 2019-08-17T00:00:00Z | 2.0640000000 |
| 2019-08-17T00:06:00Z | 8.0050000000 |
| 2019-08-17T00:06:00Z | 2.1160000000 |
The query returns values of the `water_level` field key that are floats.
## Cast operations
The `::` syntax allows users to perform basic cast operations in queries.
Currently, InfluxDB supports casting [field values](/influxdb/v2.4/reference/glossary/#field-value) from integers to
floats or from floats to integers.
### Syntax
```sql
SELECT_clause <field_key>::<type> FROM_clause
```
`type` can be `float` or `integer`.
InfluxDB returns no data if the query attempts to cast an integer or float to a string or boolean.
### Examples
{{< expand-wrapper >}}
{{% expand "Cast float field values to integers" %}}
```sql
SELECT "water_level"::integer FROM "h2o_feet" LIMIT 4
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
|time | water_level |
| :------------------ |-------------------:|
| 2019-08-17T00:00:00Z | 8.0000000000 |
| 2019-08-17T00:00:00Z | 2.0000000000 |
| 2019-08-17T00:06:00Z | 8.0000000000 |
| 2019-08-17T00:06:00Z | 2.0000000000 |
The query returns the integer form of `water_level`'s float [field values](/influxdb/v2.4/reference/glossary/#field-value).
{{% /expand %}}
{{% expand "Cast float field values to strings (this functionality is not supported)" %}}
```sql
SELECT "water_level"::string FROM "h2o_feet" LIMIT 4
> No results
```
The query returns no data as casting a float field value to a string is not yet supported.
{{% /expand %}}
{{< /expand-wrapper >}}
## Merge behavior
InfluxQL merges [series](/influxdb/v2.4/reference/glossary/#series) automatically.
### Example
{{< expand-wrapper >}}
{{% expand "Merge behavior" %}}
The `h2o_feet` [measurement](/influxdb/v2.4/reference/glossary/#measurement) in the `noaa` is part of two [series](/influxdb/v2.4/reference/glossary/#series).
The first series is made up of the `h2o_feet` measurement and the `location = coyote_creek` [tag](/influxdb/v2.4/reference/glossary/#tag). The second series is made of up the `h2o_feet` measurement and the `location = santa_monica` tag.
The following query automatically merges those two series when it calculates the average `water_level` using the [MEAN() function](/influxdb/v2.4/query-data/influxql/functions/aggregates/#mean):
```sql
SELECT MEAN("water_level") FROM "h2o_feet"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
|time | mean |
| :------------------ |-------------------:|
| 1970-01-01T00:00:00Z | 4.4419314021 |
If you want the average `water_level` for the first series only, specify the relevant tag in the [`WHERE` clause](/influxdb/v2.4/query-data/influxql/explore-data/where/):
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE "location" = 'coyote_creek'
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
|time | mean |
| :------------------ |-------------------:|
| 1970-01-01T00:00:00Z | 5.3591424203 |
If you want the average `water_level` for each individual series, include a [`GROUP BY` clause](/influxdb/v2.4/query-data/influxql/explore-data/group-by/):
```sql
SELECT MEAN("water_level") FROM "h2o_feet" GROUP BY "location"
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ |-------------------:|
| 1970-01-01T00:00:00Z | 5.3591424203 |
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=santa_monica
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ |-------------------:|
| 1970-01-01T00:00:00Z | 3.5307120942 |
{{% /expand %}}
{{< /expand-wrapper >}}
## Multiple statements
Separate multiple `SELECT` statements in a query with a semicolon (`;`).
### Examples
{{< tabs-wrapper >}}
{{% tabs %}}
[InfluxQL shell](#)
[InfluxDB API](#)
{{% /tabs %}}
{{% tab-content %}}
In the [InfluxQL shell](/influxdb/v2.4/tools/influxql-shell/):
```sql
SELECT MEAN("water_level") FROM "h2o_feet"; SELECT "water_level" FROM "h2o_feet" LIMIT 2
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
|time | mean |
| :------------------ |-------------------:|
| 1970-01-01T00:00:00Z | 4.4419314021 |
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
|time | water_level |
| :------------------ |-------------------:|
| 2019-08-17T00:00:00Z | 8.12 |
| 2015-08-18T00:00:00Z | 2.064 |
{{% /tab-content %}}
{{% tab-content %}}
With the [InfluxDB API](/influxdb/v2.4/reference/api/influxdb-1x/):
```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
]
]
}
]
}
]
}
```
{{% /tab-content %}}
{{< /tabs-wrapper >}}

View File

@ -0,0 +1,294 @@
---
title: Subqueries
description: >
Use a `subquery` to apply a query as a condition in the enclosing query.
menu:
influxdb_2_4:
name: Subqueries
parent: Explore data
weight: 310
list_code_example: |
```sql
SELECT_clause FROM ( SELECT_statement ) [...]
```
---
A subquery is a query that is nested in the `FROM` clause of another query. Use a subquery to apply a query as a condition in the enclosing query. Subqueries offer functionality similar to nested functions and the SQL [`HAVING` clause](https://en.wikipedia.org/wiki/Having_%28SQL%29).
{{% note %}}
**Note:** InfluxQL does not support a `HAVING` clause.
{{% /note %}}
- [Syntax](#syntax)
- [Examples](#examples)
- [Common Issues](#common-issues-with-subqueries)
### Syntax
```sql
SELECT_clause FROM ( SELECT_statement ) [...]
```
InfluxDB **performs the subquery first** and the main query second.
The main query surrounds the subquery and requires at least the [`SELECT` clause](/influxdb//v2.4/query-data/influxql/explore-data/select/) and the [`FROM` clause](/influxdb/v2.4/query-data/influxql/explore-data/select/#from-clause).
The main query supports all clauses listed in InfluxQL 2.x documentation.
The subquery appears in the main query's `FROM` clause, and it requires surrounding parentheses.
The subquery also supports all clauses listed in InfluxQL 2.x documentation.
InfluxQL supports multiple nested subqueries per main query.
Sample syntax for multiple subqueries:
```sql
SELECT_clause FROM ( SELECT_clause FROM ( SELECT_statement ) [...] ) [...]
```
{{% note %}}
**Note:** #### Improve performance of time-bound subqueries
To improve the performance of InfluxQL queries with time-bound subqueries,
apply the `WHERE time` clause to the outer query instead of the inner query.
For example, the following queries return the same results, but **the query with
time bounds on the outer query is more performant than the query with time
bounds on the inner query**:
##### Time bounds on the outer query (recommended)
```sql
SELECT inner_value AS value FROM (SELECT raw_value as inner_value)
WHERE time >= '2022-07-19T21:00:00Z'
AND time <= '2022-07-20T22:00:00Z'
```
##### Time bounds on the inner query
```sql
SELECT inner_value AS value FROM (
SELECT raw_value as inner_value
WHERE time >= '2022-07-19T21:00:00Z'
AND time <= '2022-07-20T22:00:00Z'
)
```
{{% /note %}}
### Examples
{{< expand-wrapper >}}
{{% expand "Calculate the SUM() of several MAX() values" %}}
```sql
SELECT SUM("max") FROM (SELECT MAX("water_level") FROM "h2o_feet" GROUP BY "location")
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | sum |
| :--------------| ------------------:|
|1970-01-01T00:00:00Z | 17.169 |
The query returns the sum of the maximum `water_level` values across every tag value of `location`.
InfluxDB first performs the subquery; it calculates the maximum value of `water_level` for each tag value of `location`:
```sql
SELECT MAX("water_level") FROM "h2o_feet" GROUP BY "location"
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | max |
| :--------------------------- | ------------------: |
| 2015-08-29T07:24:00Z | 9.9640000000 |
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=santa_monica
{{% /influxql/table-meta %}}
| time | max |
| :--------------------------- | ------------------: |
| 2015-08-29T03:54:00Z | 7.2050000000 |
Next, InfluxDB performs the main query and calculates the sum of those maximum values: `9.9640000000` + `7.2050000000` = `17.169`.
Notice that the main query specifies `max`, not `water_level`, as the field key in the `SUM()` function.
{{% /expand %}}
{{% expand "Calculate the MEAN() difference between two fields" %}}
```sql
SELECT MEAN("difference") FROM (SELECT "cats" - "dogs" AS "difference" FROM "pet_daycare")
```
Output:
{{% influxql/table-meta %}}
Name: pet_daycare
{{% /influxql/table-meta %}}
| time | max |
| :--------------------------- | ------------------: |
| 1970-01-01T00:00:00Z | 1.75 |
The query returns the average of the differences between the number of `cats` and `dogs` in the `pet_daycare` measurement.
InfluxDB first performs the subquery.
The subquery calculates the difference between the values in the `cats` field and the values in the `dogs` field,
and it names the output column `difference`:
```sql
SELECT "cats" - "dogs" AS "difference" FROM "pet_daycare"
```
Output:
{{% influxql/table-meta %}}
Name: pet_daycare
{{% /influxql/table-meta %}}
| time | difference |
| :--------------------------- | ------------------: |
| 2017-01-20T00:55:56Z | -1 |
2017-01-21T00:55:56Z | -49 |
2017-01-22T00:55:56Z | 66 |
2017-01-23T00:55:56Z | -9 |
Next, InfluxDB performs the main query and calculates the average of those differences.
Notice that the main query specifies `difference` as the field key in the [`MEAN()`](/influxdb/v2.4/query-data/influxql/functions/aggregates/#mean) function.
{{% /expand %}}
{{% expand "Calculate several MEAN() values and place a condition on those mean values" %}}
```sql
SELECT "all_the_means" FROM (SELECT MEAN("water_level") AS "all_the_means" FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:30:00Z' GROUP BY time(12m) ) WHERE "all_the_means" > 5
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | all_the_means |
| :--------------------------- | ------------------: |
| 2019-08-18T00:00:00Z | 5.4135000000 |
| 2019-08-18T00:12:00Z | 5.3042500000 |
| 2019-08-18T00:24:00Z | 5.1682500000 |
The query returns all mean values of the `water_level` field that are greater than five.
InfluxDB first performs the subquery.
The subquery calculates `MEAN()` values of `water_level` from `2019-08-18T00:00:00Z` through `2019-08-18T00:30:00Z` and groups the results into 12-minute intervals. It also names the output column `all_the_means`:
```sql
SELECT MEAN("water_level") AS "all_the_means" FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:30:00Z' GROUP BY time(12m)
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | all_the_means |
| :--------------------------- | ------------------: |
| 2019-08-18T00:00:00Z | 5.4135000000 |
| 2019-08-18T00:12:00Z | 5.3042500000 |
| 2019-08-18T00:24:00Z | 5.1682500000 |
Next, InfluxDB performs the main query and returns only those mean values that are greater than five.
Notice that the main query specifies `all_the_means` as the field key in the `SELECT` clause.
{{% /expand %}}
{{% expand "Calculate the SUM() of several DERIVATIVE() values" %}}
```sql
SELECT SUM("water_level_derivative") AS "sum_derivative" FROM (SELECT DERIVATIVE(MEAN("water_level")) AS "water_level_derivative" FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:30:00Z' GROUP BY time(12m),"location") GROUP BY "location"
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | sum_derivative |
| :--------------------------- | ------------------: |
| 1970-01-01T00:00:00Z | -0.5315000000 |
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=santa_monica
{{% /influxql/table-meta %}}
| time | sum_derivative |
| :--------------------------- | ------------------: |
| 1970-01-01T00:00:00Z | -0.2375000000 |
The query returns the sum of the derivative of average `water_level` values for each tag value of `location`.
InfluxDB first performs the subquery.
The subquery calculates the derivative of average `water_level` values taken at 12-minute intervals.
It performs that calculation for each tag value of `location` and names the output column `water_level_derivative`:
```sql
SELECT DERIVATIVE(MEAN("water_level")) AS "water_level_derivative" FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:30:00Z' GROUP BY time(12m),"location"
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | water_level_derivative |
| :--------------------------- | ------------------: |
| 2019-08-18T00:00:00Z | -0.1410000000 |
| 2019-08-18T00:12:00Z | -0.1890000000 |
| 2019-08-18T00:24:00Z | -0.2015000000 |
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=santa_monica
{{% /influxql/table-meta %}}
| time | water_level_derivative |
| :--------------------------- | ------------------: |
| 2019-08-18T00:00:00Z | -0.1375000000 |
| 2019-08-18T00:12:00Z | -0.0295000000 |
| 2019-08-18T00:24:00Z | -0.0705000000 |
Next, InfluxDB performs the main query and calculates the sum of the `water_level_derivative` values for each tag value of `location`.
Notice that the main query specifies `water_level_derivative`, not `water_level` or `derivative`, as the field key in the [`SUM()`](/influxdb/v2.4/query-data/influxql/functions/aggregates/#sum) function.
{{% /expand %}}
{{< /expand-wrapper >}}
### Common issues with subqueries
#### Multiple statements in a subquery
InfluxQL supports multiple nested subqueries per main query:
```sql
SELECT_clause FROM ( SELECT_clause FROM ( SELECT_statement ) [...] ) [...]
------------------ ----------------
Subquery 1 Subquery 2
```
InfluxQL does not support multiple [`SELECT` statements](/influxdb/v2.4/query-data/influxql/explore-data/select/) per subquery:
```sql
SELECT_clause FROM (SELECT_statement; SELECT_statement) [...]
```
The system returns a parsing error if a subquery includes multiple `SELECT` statements.

View File

@ -0,0 +1,441 @@
---
title: Time and timezone queries
list_title: Time and timezone queries
description: >
Explore InfluxQL features used specifically for working with time. Use the `tz` (timezone) clause to return the UTC offset for the specified timezone.
menu:
influxdb_2_4:
name: Time and timezone
parent: Explore data
weight: 308
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:
- [Configuring returned timestamps](#configuring-returned-timestamps)
- [Time syntax](#time-syntax)
- [Absolute time](#absolute-time)
- [Relative time](#relative-time)
- [The Time Zone clause](#the-time-zone-clause)
- [Common issues with time syntax](#common-issues-with-time-syntax)
## Configuring returned timestamps
The [InfluxQL shell](/influxdb/v2.4/tools/influxql-shell/) returns timestamps in
nanosecond UNIX epoch format by default.
Specify alternative formats with the
[`precision <format>` command](/influxdb/v2.4/tools/influxql-shell/#precision).
If you are using the [InfluxQL shell](/influxdb/v2.4/tools/influxql-shell/), use the precision helper command `precision rfc3339` to view results in human readable format.
The [InfluxDB API](/influxdb/v2.4/reference/api/influxdb-1x/) returns timestamps
in [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) format by default.
Specify alternative formats with the
[`epoch` query string parameter](/influxdb/v2.4/reference/api/influxdb-1x/).
## Time syntax
For most `SELECT` statements, the default time range is between [`1677-09-21 00:12:43.145224194` and `2262-04-11T23:47:16.854775806Z` UTC](/influxdb/v2.4/reference/faq/#what-are-the-minimum-and-maximum-timestamps-that-influxdb-can-store).
For `SELECT` statements with a [`GROUP BY time()` clause](/influxdb/v2.4/query-data/influxql/explore-data/group-by/),
the default time range is between `1677-09-21 00:12:43.145224194` UTC and [`now()`](/influxdb/v2.4/reference/glossary/#now).
The following sections detail how to specify alternative time ranges in the `SELECT`
statement's [`WHERE` clause](/influxdb/v2.4/query-data/influxql/explore-data/where/).
Other supported features include:
[Absolute time](#absolute-time)
[Relative time](#relative-time)
## Absolute time
Specify absolute time with date-time strings and epoch time.
### Syntax
```sql
SELECT_clause FROM_clause WHERE time <operator> ['<rfc3339_date_time_string>' | '<rfc3339_like_date_time_string>' | <epoch_time>] [AND ['<rfc3339_date_time_string>' | '<rfc3339_like_date_time_string>' | <epoch_time>] [...]]
```
#### Supported 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 |
Currently, InfluxDB does not support using `OR` with absolute time in the `WHERE`
clause. See the [Frequently Asked Questions](/influxdb/v2.4/reference/faq/#why-is-my-query-with-a-where-or-time-clause-returning-empty-results)
document and the [GitHub Issue](https://github.com/influxdata/influxdb/issues/7530)
for more information.
#### `rfc3339_date_time_string`
```sql
'YYYY-MM-DDTHH:MM:SS.nnnnnnnnnZ'
```
`.nnnnnnnnn` is optional and is set to `.000000000` if not included.
The [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) date-time string requires single quotes.
#### `rfc3339_like_date_time_string`
```sql
'YYYY-MM-DD HH:MM:SS.nnnnnnnnn'
```
`HH:MM:SS.nnnnnnnnn.nnnnnnnnn` is optional and is set to `00:00:00.000000000` if not included.
The RFC3339-like date-time string requires single quotes.
#### `epoch_time`
Epoch time is the amount of time that has elapsed since 00:00:00
Coordinated Universal Time (UTC), Thursday, 1 January 1970.
By default, InfluxDB assumes that all epoch timestamps are in **nanoseconds**. Include a [duration literal](/influxdb/v2.4/reference/glossary/#duration) at the end of the epoch timestamp to indicate a precision other than nanoseconds.
#### Basic arithmetic
All timestamp formats support basic arithmetic.
Add (`+`) or subtract (`-`) a time from a timestamp with a [duration literal](/influxdb/v2.4/reference/glossary/#duration).
Note that InfluxQL requires a whitespace between the `+` or `-` and the
duration literal.
### Examples
{{< expand-wrapper >}}
{{% expand "Specify a time range with RFC3339 date-time strings" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" = 'santa_monica' AND time >= '2019-08-18T00:00:00.000000000Z' AND time <= '2019-08-18T00:12:00Z'
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------ | ------------------:|
| 2019-08-18T00:00:00Z | 2.3520000000|
| 2019-08-18T00:06:00Z | 2.3790000000|
| 2019-08-18T00:12:00Z | 2.3430000000|
The query returns data with timestamps between August 18, 2019 at 00:00:00.000000000 and
August 18, 2019 at 00:12:00.
Note that the single quotes around the RFC3339 date-time strings are required.
{{% /expand %}}
{{% expand "Specify a time range with RFC3339-like date-time strings" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" = 'santa_monica' AND time >= '2019-08-18' AND time <= '2019-08-18 00:12:00'
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------ | ------------------:|
| 2019-08-18T00:00:00Z | 2.3520000000|
| 2019-08-18T00:06:00Z | 2.3790000000|
| 2019-08-18T00:12:00Z | 2.3430000000|
The query returns data with timestamps between August 18, 2019 at 00:00:00 and August 18, 2019
at 00:12:00.
The first date-time string does not include a time; InfluxDB assumes the time
is 00:00:00.
Note that the single quotes around the RFC3339-like date-time strings are
required.
{{% /expand %}}
{{% expand "Specify a time range with epock timestamps" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" = 'santa_monica' AND time >= 1564635600000000000 AND time <= 1566190800000000000
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------ | ------------------:|
| 2019-08-17T00:00:00Z | 2.0640000000|
| 2019-08-17T00:06:00Z | 2.1160000000|
| 2019-08-17T00:12:00Z | 2.0280000000|
| 2019-08-17T00:18:00Z | 2.1260000000|
| 2019-08-17T00:24:00Z | 2.0410000000|
| 2019-08-17T00:30:00Z | 2.0510000000|
| 2019-08-17T00:36:00Z | 2.0670000000|
| 2019-08-17T00:42:00Z | 2.0570000000|
| 2019-08-17T00:48:00Z | 1.9910000000|
| 2019-08-17T00:54:00Z | 2.0540000000|
| 2019-08-17T01:00:00Z | 2.0180000000|
| 2019-08-17T01:06:00Z | 2.0960000000|
| 2019-08-17T01:12:00Z | 2.1000000000|
| 2019-08-17T01:18:00Z | 2.1060000000|
| 2019-08-17T01:24:00Z | 2.1261441460|
The query returns data with timestamps that occur between August 1, 2019
at 00:00:00 and August 19, 2019 at 00:12:00. By default InfluxDB assumes epoch timestamps are in nanoseconds.
{{% /expand %}}
{{% expand "Specify a time range with second-precision epoch timestamps" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" = 'santa_monica' AND time >= 1566190800s AND time <= 1566191520s
```
Output:
| time | water_level |
| :------------------ | ------------------:|
| 2019-08-19T05:00:00Z | 3.2320000000|
| 2019-08-19T05:06:00Z | 3.2320000000|
| 2019-08-19T05:12:00Z | 3.2910000000|
The query returns data with timestamps that occur between August 19, 2019
at 00:00:00 and August 19, 2019 at 00:12:00.
The `s` duration literal at the end of the epoch timestamps indicate that the epoch timestamps are in seconds.
{{% /expand %}}
{{% expand "Perform basic arithmetic on an RFC3339-like date-time string" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE time > '2019-09-17T21:24:00Z' + 6m
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------ | ------------------:|
| 2019-09-17T21:36:00Z | 5.0660000000|
| 2019-09-17T21:42:00Z | 4.9380000000|
The query returns data with timestamps that occur at least six minutes after
September 17, 2019 at 21:24:00.
Note that the whitespace between the `+` and `6m` is required.
{{% /expand %}}
{{% expand "Perform basic arithmetic on an epock timestamp" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE time > 24043524m - 6m
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------ | ------------------:|
| 2019-08-17T00:00:00Z | 8.1200000000|
| 2019-08-17T00:00:00Z | 2.0640000000|
| 2019-08-17T00:06:00Z | 8.0050000000|
| 2019-08-17T00:06:00Z | 2.1160000000|
| 2019-08-17T00:12:00Z | 7.8870000000|
| 2019-08-17T00:12:00Z | 2.0280000000|
| 2019-08-17T00:18:00Z | 7.7620000000|
| 2019-08-17T00:18:00Z | 2.1260000000|
The query returns data with timestamps that occur at least six minutes before
September 18, 2019 at 21:24:00. Note that the whitespace between the `-` and `6m` is required. Note that the results above are partial as the dataset is large.
{{% /expand %}}
{{< /expand-wrapper >}}
## Relative time
Use [`now()`](/influxdb/v2.4/reference/glossary/#now) to query data with [timestamps](/influxdb/v2.4/reference/glossary/#timestamp) relative to the server's current timestamp.
### Syntax
```sql
SELECT_clause FROM_clause WHERE time <operator> now() [[ - | + ] <duration_literal>] [(AND|OR) now() [...]]
```
`now()` is the Unix time of the server at the time the query is executed on that server.
The whitespace between `-` or `+` and the [duration literal](/influxdb/v2.4/reference/glossary/#duration) is required.
#### Supported 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 |
#### `duration_literal`
- microseconds: `u` or `µ`
- milliseconds: `ms`
- seconds`s`
- minutes`m`
- hours:`h`
- days:`d`
- weeks:`w`
### Examples
{{< expand-wrapper >}}
{{% expand "Specify a time range with relative time" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE time > now() - 1h
```
The query returns data with timestamps that occur within the past hour.
The whitespace between `-` and `1h` is required.
{{% /expand %}}
{{% expand "Specify a time range with absolute time and relative time" %}}
#### Specify a time range with absolute time and relative time
```sql
SELECT "level description" FROM "h2o_feet" WHERE time > '2019-09-17T21:18:00Z' AND time < now() + 1000d
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description |
| :------------------ |--------------------:|
|2019-09-17T21:24:00Z | between 3 and 6 feet |
|2019-09-17T21:30:00Z | between 3 and 6 feet |
|2019-09-17T21:36:00Z | between 3 and 6 feet |
|2019-09-17T21:42:00Z | between 3 and 6 feet |
The query returns data with timestamps that occur between September 17, 2019 at 21:18:00 and 1000 days from `now()`. The whitespace between `+` and `1000d` is required.
{{% /expand %}}
{{< /expand-wrapper >}}
## The Time Zone clause
Use the `tz()` clause to return the UTC offset for the specified timezone.
### Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] [LIMIT_clause] [OFFSET_clause] [SLIMIT_clause] [SOFFSET_clause] tz('<time_zone>')
```
By default, InfluxDB stores and returns timestamps in UTC.
The `tz()` clause includes the UTC offset or, if applicable, the UTC Daylight Savings Time (DST) offset to the query's returned timestamps. The returned timestamps must be in `RFC3339` format for the UTC offset or UTC DST to appear.
The `time_zone` parameter follows the TZ syntax in the [Internet Assigned Numbers Authority time zone database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List) and it requires single quotes.
### Examples
{{< expand-wrapper >}}
{{% expand "Return the UTC offset for Chicago's time zone" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" = 'santa_monica' AND time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:18:00Z' tz('America/Chicago')
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :-------------- | -------------------:|
| 2019-08-17T19:00:00-05:00 | 2.3520000000|
| 2019-08-17T19:06:00-05:00 | 2.3790000000|
| 2019-08-17T19:12:00-05:00 | 2.3430000000|
| 2019-08-17T19:18:00-05:00 | 2.3290000000|
The query results include the UTC offset (`-05:00`) for the `America/Chicago` time zone in the timestamps.
{{% /expand %}}
{{< /expand-wrapper >}}
## Common issues with time syntax
### Using `OR` to select time multiple time intervals
InfluxDB does not support using the `OR` operator in the `WHERE` clause to specify multiple time intervals.
For more information, see [Frequently asked questions](/influxdb/v2.4/reference/faq/#why-is-my-query-with-a-where-or-time-clause-returning-empty-results).
### Querying data that occur after `now()` with a `GROUP BY time()` clause
Most `SELECT` statements have a default time range between [`1677-09-21 00:12:43.145224194` and `2262-04-11T23:47:16.854775806Z` UTC](/influxdb/v2.4/reference/faq/#what-are-the-minimum-and-maximum-timestamps-that-influxdb-can-store).
For `SELECT` statements with a [`GROUP BY time()` clause](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-time-intervals),
the default time range is between `1677-09-21 00:12:43.145224194` UTC and [`now()`](/influxdb/v2.4/reference/glossary/#now).
To query data with timestamps that occur after `now()`, `SELECT` statements with
a `GROUP BY time()` clause must provide an alternative upper bound in the
`WHERE` clause.
<!-- #### Example
Use the [CLI](/enterprise_influxdb/v1.9/tools/influx-cli/use-influx/) to write a point to the `noaa` database that occurs after `now()`:
```sql
> INSERT h2o_feet,location=santa_monica water_level=3.1 1587074400000000000
```
Run a `GROUP BY time()` query that covers data with timestamps between
`2019-09-18T21:30:00Z` and `now()`:
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE "location"='santa_monica' AND time >= '2019-09-18T21:30:00Z' GROUP BY time(12m) fill(none)
name: h2o_feet
time mean
---- ----
2019-09-18T21:24:00Z 5.01
2019-09-18T21:36:00Z 5.002
```
Run a `GROUP BY time()` query that covers data with timestamps between
`2019-09-18T21:30:00Z` and 180 weeks from `now()`:
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE "location"='santa_monica' AND time >= '2019-09-18T21:30:00Z' AND time <= now() + 180w GROUP BY time(12m) fill(none)
name: h2o_feet
time mean
---- ----
2019-09-18T21:24:00Z 5.01
2019-09-18T21:36:00Z 5.002
2020-04-16T22:00:00Z 3.1
```
Note that the `WHERE` clause must provide an alternative **upper** bound to
override the default `now()` upper bound. The following query merely resets
the lower bound to `now()` such that the queried time range is between
`now()` and `now()`:
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE "location"='santa_monica' AND time >= now() GROUP BY time(12m) fill(none)
>
``` -->

View File

@ -0,0 +1,314 @@
---
title: The WHERE clause
list_title: WHERE clause
description: >
Use the `WHERE` clause to filter data based on [fields](/influxdb/v2.4/reference/glossary/#field), [tags](/influxdb/v2.4/reference/glossary/#tag), and/or [timestamps](/influxdb/v2.4/reference/glossary/#timestamp).
menu:
influxdb_2_4:
name: WHERE clause
parent: Explore data
weight: 302
list_code_example: |
```sql
SELECT_clause FROM_clause WHERE <conditional_expression> [(AND|OR) <conditional_expression> [...]]
```
---
Use the `WHERE` clause to filter data based on
[fields](/influxdb/v2.4/reference/glossary/#field),
[tags](/influxdb/v2.4/reference/glossary/#tag), and/or
[timestamps](/influxdb/v2.4/reference/glossary/#timestamp).
- [Syntax](#syntax)
- [Examples](#examples)
- [Common issues](#common-issues-with-the-where-clause)
### Syntax
```sql
SELECT_clause FROM_clause WHERE <conditional_expression> [(AND|OR) <conditional_expression> [...]]
```
The `WHERE` clause supports `conditional_expressions` on fields, tags, and timestamps.
{{% note %}}
**Note:** InfluxDB does not support using OR in the WHERE clause to specify multiple time ranges. For example, InfluxDB returns an empty response for the following query:
```sql
SELECT * FROM "mydb" WHERE time = '2020-07-31T20:07:00Z' OR time = '2020-07-31T23:07:17Z'`
```
{{% /note %}}
#### Fields
```
field_key <operator> ['string' | boolean | float | integer]
```
The `WHERE` clause supports comparisons against string, boolean, float, and integer [field values](/influxdb/v2.4/reference/glossary/#field-value).
Single quote string field values in the `WHERE` clause.
Queries with unquoted string field values or double quoted string field values will not return any data and, in most cases,
[will not return an error](#common-issues-with-the-where-clause).
#### Supported 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 |
InfluxQL also supports [Regular Expressions](/influxdb/v2.4/query-data/influxql/explore-data/regular-expressions/).
#### Tags
```sql
tag_key <operator> ['tag_value']
```
Single quote [tag values](/influxdb/v2.4/reference/glossary/#tag-value) in
the `WHERE` clause.
Queries with unquoted tag values or double quoted tag values will not return
any data and, in most cases,
[will not return an error](#common-issues-with-the-where-clause).
#### Supported operators
| Operator | Meaning |
|:--------:|:------- |
| `=` | equal to |
| `<>` | not equal to |
| `!=` | not equal to |
#### Timestamps
For most `SELECT` statements, the default time range is between [`1677-09-21 00:12:43.145224194` and `2262-04-11T23:47:16.854775806Z` UTC](/influxdb/v2.4/reference/faq/#what-are-the-minimum-and-maximum-integers-that-influxdb-can-store).
For `SELECT` statements with a [`GROUP BY time()` clause](/influxdb/v2.4/query-data/influxql/explore-data/group-by/), the default time
range is between `1677-09-21 00:12:43.145224194` UTC and [`now()`](/influxdb/v2.4/reference/glossary/#now).
See [Time Syntax](/influxdb/v2.4/query-data/influxql/explore-data/time-and-timezone/#time-syntax) for information on how to specify alternative time ranges in the `WHERE` clause.
### Examples
{{< expand-wrapper >}}
{{% expand "Select data with specific field key-values" %}}
```sql
SELECT * FROM "h2o_feet" WHERE "water_level" > 9
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level |
| :-------------- | :-------------------| :------------------| -------: |
| 2019-08-25T04:00:00Z | at or greater than 9 feet | coyote_creek | 9.0320000000|
| 2019-08-25T04:06:00Z | at or greater than 9 feet | coyote_creek | 9.0780000000|
| 2019-08-25T04:12:00Z | at or greater than 9 feet | coyote_creek | 9.1110000000|
| 2019-08-25T04:18:00Z | at or greater than 9 feet | coyote_creek | 9.1500000000|
| 2019-08-25T04:24:00Z | at or greater than 9 feet | coyote_creek | 9.1800000000|
The query returns data from the `h2o_feet` measurement with field values of `water_level` that are greater than nine.
This is a partial data set.
{{% /expand %}}
{{% expand "Select data with a specific string field key-value" %}}
```sql
SELECT * FROM "h2o_feet" WHERE "level description" = 'below 3 feet'
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level |
| :-------------- | :-------------------| :------------------| :------------------ |
| 2019-08-17T00:00:00Z | below 3 feet | santa_monica | 2.0640000000|
| 2019-08-17T00:06:00Z | below 3 feet | santa_monica | 2.1160000000|
| 2019-08-17T00:12:00Z | below 3 feet | santa_monica | 2.0280000000|
| 2019-08-17T00:18:00Z | below 3 feet | santa_monica | 2.1260000000|
| 2019-08-17T00:24:00Z | below 3 feet | santa_monica | 2.0410000000|
| 2019-08-17T00:30:00Z | below 3 feet | santa_monica | 2.0510000000|
The query returns data from the `h2o_feet` measurement with field values of `level description` that equal the `below 3 feet` string. InfluxQL requires single quotes around string field values in the `WHERE` clause.
{{% /expand %}}
{{% expand "Select data with a specific field key-value and perform basic arithmetic" %}}
```sql
SELECT * FROM "h2o_feet" WHERE "water_level" + 2 > 11.9
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level |
| :-------------- | :-------------------| :------------------|---------------: |
| 2019-08-28T07:06:00Z | at or greater than 9 feet | coyote_creek | 9.9020000000|
| 2019-08-28T07:12:00Z | at or greater than 9 feet | coyote_creek | 9.9380000000|
| 2019-08-28T07:18:00Z | at or greater than 9 feet | coyote_creek | 9.9570000000|
| 2019-08-28T07:24:00Z | at or greater than 9 feet | coyote_creek | 9.9640000000|
| 2019-08-28T07:30:00Z | at or greater than 9 feet | coyote_creek | 9.9540000000|
| 2019-08-28T07:36:00Z | at or greater than 9 feet | coyote_creek | 9.9410000000|
| 2019-08-28T07:42:00Z | at or greater than 9 feet | coyote_creek | 9.9250000000|
| 2019-08-28T07:48:00Z | at or greater than 9 feet | coyote_creek | 9.9020000000|
| 2019-09-01T23:30:00Z | at or greater than 9 feet | coyote_creek | 9.9020000000|
The query returns data from the `h2o_feet` measurement with field values of
`water_level` plus two that are greater than 11.9. Note that InfluxDB follows the standard order of operations.
See [Mathematical operators](/influxdb/v2.4/query-data/influxql/math-operators/)
for more on supported operators.
{{% /expand %}}
{{% expand "Select data with a specific tag key-value" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" = 'santa_monica'
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :-------------- | -------------------:|
| 2019-08-17T00:00:00Z | 2.0640000000|
| 2019-08-17T00:06:00Z | 2.1160000000|
| 2019-08-17T00:12:00Z | 2.0280000000|
| 2019-08-17T00:18:00Z | 2.1260000000|
| 2019-08-17T00:24:00Z | 2.0410000000|
<!-- name: h2o_feet
--------------
time water_level
2019-08-18T00:00:00Z 2.064
2019-08-18T00:06:00Z 2.116
[...]
2019-09-18T21:36:00Z 5.066
2019-09-18T21:42:00Z 4.938 -->
The query returns data from the `h2o_feet` measurement where the
[tag key](/influxdb/v2.4/reference/glossary/#tag-key) `location` is set to `santa_monica`.
InfluxQL requires single quotes around tag values in the `WHERE` clause.
{{% /expand %}}
{{% expand "Select data with specific field key-values and tag key-valuest" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" <> 'santa_monica' AND (water_level < -0.59 OR water_level > 9.95)
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------- | -----------: |
| 2019-08-28T07:18:00Z | 9.9570000000|
| 2019-08-28T07:24:00Z | 9.9640000000|
| 2019-08-28T07:30:00Z | 9.9540000000|
| 2019-08-28T14:30:00Z | -0.6100000000|
| 2019-08-28T14:36:00Z | -0.5910000000|
| 2019-08-29T15:18:00Z | -0.5940000000|
The query returns data from the `h2o_feet` measurement where the tag key
`location` is not set to `santa_monica` and where the field values of
`water_level` are either less than -0.59 or greater than 9.95.
The `WHERE` clause supports the operators `AND` and `OR`, and supports
separating logic with parentheses.
{{% /expand %}}
{{< /expand-wrapper >}}
```sql
SELECT * FROM "h2o_feet" WHERE time > now() - 7d
```
The query returns data from the `h2o_feet` measurement with [timestamps](/influxdb/v2.4/reference/glossary/#timestamp)
within the past seven days. See [Time Syntax](/influxdb/v2.4/query-data/influxql/explore-data/time-and-timezone/#time-syntax) for more in-depth information on supported time syntax in the `WHERE` clause.
### Common issues with the `WHERE` clause
#### A `WHERE` clause query unexpectedly returns no data
In most cases, this issue is the result of missing single quotes around
tag values or string field values.
Queries with unquoted or double quoted tag values or string field values will
not return any data and, in most cases, will not return an error.
The first two queries in the code block below attempt to specify the tag value
`santa_monica` without any quotes and with double quotes.
Those queries return no results.
The third query single quotes `santa_monica` (this is the supported syntax)
and returns the expected results.
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" = santa_monica
No results
SELECT "water_level" FROM "h2o_feet" WHERE "location" = "santa_monica"
No results
SELECT "water_level" FROM "h2o_feet" WHERE "location" = 'santa_monica'
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------- | -----------: |
| 2019-08-17T00:00:00Z | 2.0640000000 |
| 2019-08-17T00:06:00Z | 2.1160000000 |
| 2019-08-17T00:12:00Z | 2.0280000000 |
| 2019-08-17T00:18:00Z | 2.1260000000 |
| 2019-08-17T00:24:00Z | 2.0410000000 |
| 2019-08-17T00:30:00Z | 2.0510000000 |
The first two queries in the code block below attempt to specify the string
field value `at or greater than 9 feet` without any quotes and with double
quotes.
The first query returns an error because the string field value includes
white spaces.
The second query returns no results.
The third query single quotes `at or greater than 9 feet` (this is the
supported syntax) and returns the expected results.
```sql
SELECT "level description" FROM "h2o_feet" WHERE "level description" = at or greater than 9 feet
ERR: 400 Bad Request: failed to parse query: found than, expected ; at line 1, char 86
SELECT "level description" FROM "h2o_feet" WHERE "level description" = "at or greater than 9 feet"
No results
SELECT "level description" FROM "h2o_feet" WHERE "level description" = 'at or greater than 9 feet'
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level_description |
| :---------------------------| ------: |
| 2019-08-25T04:00:00Z | at or greater than 9 feet |
| 2019-08-25T04:06:00Z | at or greater than 9 feet |
| 019-08-25T04:12:00Z | at or greater than 9 feet |
| 2019-08-25T04:18:00Z | at or greater than 9 feet |
| 2019-08-25T04:24:00Z | at or greater than 9 feet |

View File

@ -0,0 +1,592 @@
---
title: Explore your schema using InfluxQL
description: >
Learn to use InfluxQL to explore the schema of your time series data.
menu:
influxdb_2_4:
name: Explore your schema
parent: Query with InfluxQL
identifier: explore-schema-influxql
weight: 202
---
Use InfluxQL to explore the schema of your time series data.
Use the following InfluxQL commands to explore your schema:
- [SHOW SERIES](#show-series)
- [SHOW MEASUREMENTS](#show-measurements)
- [SHOW TAG KEYS](#show-tag-keys)
- [SHOW TAG VALUES](#show-tag-values)
- [SHOW FIELD KEYS](#show-field-keys)
- [SHOW FIELD KEY CARDINALITY](#show-field-key-cardinality)
- [SHOW TAG KEY CARDINALITY](#show-tag-key-cardinality)
{{% note %}}
Command examples use the [NOAA water sample data](/influxdb/v2.4/reference/sample-data/#noaa-water-sample-data).
{{% /note %}}
## SHOW SERIES
Return a list of [series](/influxdb/v2.4/reference/glossary/#series) for
the specified [database](/influxdb/v2.4/reference/glossary/#database).
### Syntax
```sql
SHOW SERIES [ON <database_name>] [FROM_clause] [WHERE <tag_key> <operator> [ '<tag_value>' | <regular_expression>]] [LIMIT_clause] [OFFSET_clause]
```
- `ON <database_name>` is optional.
If the query does not include `ON <database_name>`, you must specify the
database with the `db` query string parameter in the
[InfluxDB API](/influxdb/v2.4/reference/api/influxdb-1x/) request.
- `FROM`, `WHERE`, `LIMIT`, and `OFFSET` clauses are optional.
- The `WHERE` clause in `SHOW SERIES` supports tag comparisons but not field comparisons.
**Supported operators in the `WHERE` clause**:
- `=`: equal to
- `<>`: not equal to
- `!=`: not equal to
- `=~`: matches against
- `!~`: doesn't match against
See [Explore data using InfluxQL](/influxdb/v2.4/query-data/influxql/explore-data/) for documentation on the
[`FROM` clause](/influxdb/v2.4/query-data/influxql/explore-data/select/#from-clause),
[`LIMIT` clause](/influxdb/v2.4/query-data/influxql/explore-data/limit-and-slimit/),
[`OFFSET` clause](/influxdb/v2.4/query-data/influxql/explore-data/offset-and-soffset/),
and [Regular Expressions](/influxdb/v2.4/query-data/influxql/explore-data/regular-expressions/).
### Examples
#### Run SHOW SERIES with the ON clause
```sql
SHOW SERIES ON noaa
```
**Output:**
The query returns all series in the `noaa` database.
The query's output is similar to the [line protocol](/influxdb/v2.4/reference/syntax/line-protocol/) format.
Everything before the first comma is the [measurement](/influxdb/v2.4/reference/glossary/#measurement) name.
Everything after the first comma is either a [tag key](/influxdb/v2.4/reference/glossary/#tag-key) or a [tag value](/influxdb/v2.4/reference/glossary/#tag-value).
The `noaa` database has 5 different measurements and 13 different series.
| key |
| :------------------------------------------ |
| average_temperature,location=coyote_creek |
| average_temperature,location=santa_monica |
| h2o_feet,location=coyote_creek |
| h2o_feet,location=santa_monica |
| h2o_pH,location=coyote_creek |
| h2o_pH,location=santa_monica |
| h2o_quality,location=coyote_creek,randtag=1 |
| h2o_quality,location=coyote_creek,randtag=2 |
| h2o_quality,location=coyote_creek,randtag=3 |
| h2o_quality,location=santa_monica,randtag=1 |
| h2o_quality,location=santa_monica,randtag=2 |
| h2o_quality,location=santa_monica,randtag=3 |
| h2o_temperature,location=coyote_creek |
#### Run SHOW SERIES with several clauses
```sql
SHOW SERIES ON noaa FROM "h2o_quality" WHERE "location" = 'coyote_creek' LIMIT 2
```
**Output:**
The query returns all series in the `noaa` database that are
associated with the `h2o_quality` measurement and the tag `location = coyote_creek`.
The `LIMIT` clause limits the number of series returned to two.
| key |
| :------------------------------------------ |
|h2o_quality,location=coyote_creek,randtag=1 |
|h2o_quality,location=coyote_creek,randtag=2 |
## SHOW MEASUREMENTS
Returns a list of [measurements](/influxdb/v2.4/reference/glossary/#measurement)
for the specified [database](/influxdb/v2.4/reference/glossary/#database).
### Syntax
```sql
SHOW MEASUREMENTS [ON <database_name>] [WITH MEASUREMENT <operator> ['<measurement_name>' | <regular_expression>]] [WHERE <tag_key> <operator> ['<tag_value>' | <regular_expression>]] [LIMIT_clause] [OFFSET_clause]
```
- `ON <database_name>` is optional.
If the query does not include `ON <database_name>`, you must specify the
database with the `db` query string parameter in the
[InfluxDB API](/influxdb/v2.4/reference/api/influxdb-1x/) request.
- The `WITH`, `WHERE`, `LIMIT` and `OFFSET` clauses are optional.
- The `WHERE` in `SHOW MEASURMENTS` supports tag comparisons, but not field comparisons.
**Supported operators in the `WHERE` clause:**
- `=` : equal to
- `<>`: not equal to
- `!=`: not equal to
- `=~`: matches against
- `!~`: doesn't match against
See [Explore data using InfluxQL](/influxdb/v2.4/query-data/influxql/explore-data/) for documentation on the
[`FROM` clause](/influxdb/v2.4/query-data/influxql/explore-data/select/#from-clause),
[`LIMIT` clause](/influxdb/v2.4/query-data/influxql/explore-data/limit-and-slimit/),
[`OFFSET` clause](/influxdb/v2.4/query-data/influxql/explore-data/offset-and-soffset/),
and [Regular Expressions](/influxdb/v2.4/query-data/influxql/explore-data/regular-expressions/).
### Examples
#### Run SHOW MEASUREMENTS with the ON clause
```sql
SHOW MEASUREMENTS ON noaa
```
**Output:**
The query returns the list of measurements in the `noaa` database.
The database has five measurements: `average_temperature`, `h2o_feet`, `h2o_pH`,
`h2o_quality`, and `h2o_temperature`.
| name |
| :------------------ |
| average_temperature |
| h2o_feet |
| h2o_pH |
| h2o_quality |
| h2o_temperature |
#### Run SHOW MEASUREMENTS with several clauses (i)
```sql
SHOW MEASUREMENTS ON noaa WITH MEASUREMENT =~ /h2o.*/ LIMIT 2 OFFSET 1
```
**Output:**
The query returns the measurements in the `noaa` database that start with `h2o`.
The `LIMIT` and `OFFSET` clauses limit the number of measurement names returned to
two and offset the results by one, skipping the `h2o_feet` measurement.
| name |
| :---------- |
| h2o_pH |
| h2o_quality |
#### Run SHOW MEASUREMENTS with several clauses (ii)
```sql
SHOW MEASUREMENTS ON noaa WITH MEASUREMENT =~ /h2o.*/ WHERE "randtag" =~ /\d/
```
The query returns all measurements in the `noaa` that start with `h2o` and have
values for the tag key `randtag` that include an integer.
| name |
| :---------- |
| h2o_quality |
## SHOW TAG KEYS
Returns a list of [tag keys](/influxdb/v2.4/reference/glossary/#tag-key)
associated with the specified [database](/influxdb/v2.4/reference/glossary/#database).
### Syntax
```sql
SHOW TAG KEYS [ON <database_name>] [FROM_clause] WITH KEY [ [<operator> "<tag_key>" | <regular_expression>] | [IN ("<tag_key1>","<tag_key2>")]] [WHERE <tag_key> <operator> ['<tag_value>' | <regular_expression>]] [LIMIT_clause] [OFFSET_clause]
```
- `ON <database_name>` is optional.
If the query does not include `ON <database_name>`, you must specify the
database with `db` query string parameter in the [InfluxDB API](/influxdb/v2.4/reference/api/influxdb-1x/) request.
- The `FROM` clause and the `WHERE` clause are optional.
- The `WHERE` clause in `SHOW TAG KEYS` supports tag comparisons, but not field comparisons.
**Supported operators in the `WHERE` clause:**
- `=` : equal to
- `<>`: not equal to
- `!=`: not equal to
- `=~`: matches against
- `!~`: doesn't match against
See [Explore data using InfluxQL](/influxdb/v2.4/query-data/influxql/explore-data/) for documentation on the
[`FROM` clause](/influxdb/v2.4/query-data/influxql/explore-data/select/#from-clause),
[`LIMIT` clause](/influxdb/v2.4/query-data/influxql/explore-data/limit-and-slimit/),
[`OFFSET` clause](/influxdb/v2.4/query-data/influxql/explore-data/offset-and-soffset/),
and [Regular Expressions](/influxdb/v2.4/query-data/influxql/explore-data/regular-expressions/).
### Examples
#### Run SHOW TAG KEYS with the ON clause
```sql
SHOW TAG KEYS ON noaa
```
**Output:**
The query returns the list of tag keys in the `noaa` database.
The output groups tag keys by measurement name;
it shows that every measurement has the `location` tag key and that the
`h2o_quality` measurement has an additional `randtag` tag key.
| name | tagKey |
| :------------------ | :------- |
| average_temperature | location |
| h2o_feet | location |
| h2o_pH | location |
| h2o_quality | location |
| h2o_quality | randtag |
| h2o_temperature | location |
#### Run SHOW TAG KEYS with several clauses
```sql
SHOW TAG KEYS ON noaa FROM "h2o_quality" LIMIT 1 OFFSET 1
```
**Output:**
The query returns tag keys from the `h2o_quality` measurement in the `noaa` database.
The `LIMIT` and `OFFSET` clauses limit the number of tag keys returned to one
and offsets the results by one.
| name | tagKey |
| :---------- | :------ |
| h2o_quality | randtag |
#### Run SHOW TAG KEYS with a WITH KEY IN clause
```sql
SHOW TAG KEYS ON noaa WITH KEY IN ("location")
```
**Output:**
| measurement | tagKey |
| :------------------ | :------- |
| average_temperature | location |
| h2o_feet | location |
| h2o_pH | location |
| h2o_quality | location |
| h2o_quality | randtag |
| h2o_temperature | location |
## SHOW TAG VALUES
Returns the list of [tag values](/influxdb/v2.4/reference/glossary/#tag-value)
for the specified [tag key(s)](/influxdb/v2.4/reference/glossary/#tag-key) in the database.
### Syntax
```sql
SHOW TAG VALUES [ON <database_name>][FROM_clause] WITH KEY [ [<operator> "<tag_key>" | <regular_expression>] | [IN ("<tag_key1>","<tag_key2>")]] [WHERE <tag_key> <operator> ['<tag_value>' | <regular_expression>]] [LIMIT_clause] [OFFSET_clause]
```
- `ON <database_name>` is optional.
If the query does not include `ON <database_name>`, you must specify the
database with the `db` query string parameter in the [InfluxDB API](/influxdb/v2.4/reference/api/influxdb-1x/) request.
- The `WITH` clause is required.
It supports specifying a single tag key, a regular expression, and multiple tag keys.
- The `FROM`, `WHERE`, `LIMIT`, and `OFFSET` clauses are optional.
- The `WHERE` clause in `SHOW TAG KEYS` supports tag comparisons, but not field comparisons.
**Supported operators in the `WITH` and `WHERE` clauses:**
- `=` : equal to
- `<>`: not equal to
- `!=`: not equal to
- `=~`: matches against
- `!~`: doesn't match against
See [Explore data using InfluxQL](/influxdb/v2.4/query-data/influxql/explore-data/) for documentation on the
[`FROM` clause](/influxdb/v2.4/query-data/influxql/explore-data/select/#from-clause),
[`LIMIT` clause](/influxdb/v2.4/query-data/influxql/explore-data/limit-and-slimit/),
[`OFFSET` clause](/influxdb/v2.4/query-data/influxql/explore-data/offset-and-soffset/),
and [Regular Expressions](/influxdb/v2.4/query-data/influxql/explore-data/regular-expressions/).
### Examples
#### Run SHOW TAG VALUES with the ON clause
```sql
SHOW TAG VALUES ON noaa WITH KEY = "randtag"
```
**Output:**
The query returns all tag values of the `randtag` tag key in the `noaa` database.
`SHOW TAG VALUES` groups query results by measurement name.
{{% influxql/table-meta %}}
name: h2o_quality
{{% /influxql/table-meta %}}
| key | value |
| :------ | ----: |
| randtag | 1 |
| randtag | 2 |
| randtag | 3 |
#### Run a `SHOW TAG VALUES` query with several clauses
```sql
SHOW TAG VALUES ON noaa WITH KEY IN ("location","randtag") WHERE "randtag" =~ /./ LIMIT 3
```
**Output:**
The query returns the tag values of the tag keys `location` and `randtag` for
all measurements in the `noaa` database where `randtag` has tag values.
The `LIMIT` clause limits the number of tag values returned to three.
{{% influxql/table-meta %}}
name: h2o_quality
{{% /influxql/table-meta %}}
| key | value |
| :------- | -----------: |
| location | coyote_creek |
| location | santa_monica |
| randtag | 1 |
## SHOW FIELD KEYS
Returns the [field keys](/influxdb/v2.4/reference/glossary/#field-key) and the
[data type](/influxdb/v2.4/reference/glossary/#data-type) of their
[field values](/influxdb/v2.4/reference/glossary/#field-value).
### Syntax
```sql
SHOW FIELD KEYS [ON <database_name>] [FROM <measurement_name>]
```
- `ON <database_name>` is optional.
If the query does not include `ON <database_name>`, you must specify the
database with `USE <database_name>` when using the [InfluxQL shell](/influxdb/v2.4/tools/influxql-shell/)
or with the `db` query string parameter in the
[InfluxDB 1.x compatibility API](/influxdb/v2.4/reference/api/influxdb-1x/) request.
- The `FROM` clause is optional.
See the Data Exploration page for documentation on the
[` FROM` clause](/influxdb/v2.4/query-data/influxql/explore-data/select/#from-clause).
{{% note %}}
**Note:** A field's data type [can differ](/influxdb/v2.4/reference/faq/#how-does-influxdb-handle-field-type-discrepancies-across-shards) across
[shards](/influxdb/v2.4/reference/glossary/#shard).
If your field has more than one type, `SHOW FIELD KEYS` returns the type that
occurs first in the following list: float, integer, string, boolean.
{{% /note %}}
### Examples
#### Run SHOW FIELD KEYS with the ON clause
```sql
SHOW FIELD KEYS ON noaa
```
**Output:**
The query returns the field keys and field value data types for each
measurement in the `noaa` database.
| name | fieldKey | fieldType |
| :------------------ | :---------------- | :-------- |
| average_temperature | degrees | float |
| h2o_feet | level description | string |
| h2o_feet | water_level | float |
| h2o_pH | pH | float |
| h2o_quality | index | float |
| hh2o_temperature | degrees | float |
#### Run SHOW FIELD KEYS with the FROM clause
```sql
SHOW FIELD KEYS ON noaa FROM h2o_feet
```
**Output:**
The query returns the fields keys and field value data types for the `h2o_feet`
measurement in the `noaa` database.
| name | fieldKey | fieldType |
| :------- | :---------------- | :-------- |
| h2o_feet | level description | string |
| h2o_feet | water_level | float |
### Common Issues with SHOW FIELD KEYS
#### SHOW FIELD KEYS and field type discrepancies
Field value [data types](/influxdb/v2.4/reference/glossary/#data-type)
cannot differ within a [shard](/influxdb/v2.4/reference/glossary/#shard) but they
can differ across shards.
`SHOW FIELD KEYS` returns every data type, across every shard, associated with
the field key.
##### Example
The `all_the_types` field stores four different data types:
```sql
SHOW FIELD KEYS
```
{{% influxql/table-meta %}}
name: mymeas
{{% /influxql/table-meta %}}
| fieldKey | fieldType |
| :------------ | :-------- |
| all_the_types | integer |
| all_the_types | float |
| all_the_types | string |
| all_the_types | boolean |
Note that `SHOW FIELD KEYS` handles field type discrepancies differently from
`SELECT` statements.
For more information, see the
[How does InfluxDB handle field type discrepancies across shards?](/enterprise_influxdb/v1.9/troubleshooting/frequently-asked-questions/#how-does-influxdb-handle-field-type-discrepancies-across-shards).
## SHOW FIELD KEY CARDINALITY
Cardinality is the product of all unique databases, retention policies, measurements, field keys and tag values in your Influx instance. Managing cardinality is important, as high cardinality leads to greater resource usage.
```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 noaa
```
## SHOW TAG KEY CARDINALITY
```sql
-- show estimated tag key cardinality
SHOW TAG KEY CARDINALITY
-- show exact tag key cardinality
SHOW TAG KEY EXACT CARDINALITY
```
<!--
### SHOW TAG VALUES CARDINALITY
```sql
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" -->
<!-- ### Filter meta queries by time
When you filter meta queries by time, you may see results outside of your specified time. Meta query results are filtered at the shard level, so results can be approximately as granular as your shard group duration. If your time filter spans multiple shards, you'll get results from all shards with points in the specified time range. To review your shards and timestamps on points in the shard, run `SHOW SHARDS`. To learn more about shards and their duration, see [recommended shard groups durations](/influxdb/v2.4/reference/internals/shards/#shard-group-duration).
The example below shows how to filter `SHOW TAG KEYS` by approximately one hour using a 1h shard group duration. To filter other meta data, replace `SHOW TAG KEYS` with `SHOW TAG VALUES`, `SHOW SERIES`, `SHOW FIELD KEYS`, and so on.
{{% note %}}
**Note:** `SHOW MEASUREMENTS` cannot be filtered by time.
{{% /note %}}
#### Example filtering `SHOW TAG KEYS` by time
1. Specify a shard duration on a new database or [alter an existing shard duration](/enterprise_influxdb/v1.9/query_language/manage-database/#modify-retention-policies-with-alter-retention-policy). To specify a 1h shard duration when creating a new database, run the following command:
```sh
> CREATE database mydb with duration 7d REPLICATION 1 SHARD DURATION 1h name myRP;
```
> **Note:** The minimum shard duration is 1h.
2. Verify the shard duration has the correct time interval (precision) by running the `SHOW SHARDS` command. The example below shows a shard duration with an hour precision.
```sh
> SHOW SHARDS
name: mydb
id database retention_policy shard_group start_time end_time expiry_time owners
-- -------- ---------------- ----------- ---------- -------- ----------- ------
> precision h
```
3. (Optional) Insert sample tag keys. This step is for demonstration purposes. If you already have tag keys (or other meta data) to search for, skip this step.
```sh
// Insert a sample tag called "test_key" into the "test" measurement, and then check the timestamp:
> INSERT test,test_key=hello value=1
> select * from test
name: test
time test_key value
---- -------- -----
434820 hello 1
// Add new tag keys with timestamps one, two, and three hours earlier:
> INSERT test,test_key_1=hello value=1 434819
> INSERT test,test_key_2=hello value=1 434819
> INSERT test,test_key_3_=hello value=1 434818
> INSERT test,test_key_4=hello value=1 434817
> INSERT test,test_key_5_=hello value=1 434817
```
4. To find tag keys within a shard duration, run one of the following commands:
`SHOW TAG KEYS ON database-name <WHERE time clause>` OR
`SELECT * FROM measurement <WHERE time clause>`
The examples below use test data from step 3.
```sh
//Using data from Step 3, show tag keys between now and an hour ago
> SHOW TAG KEYS ON mydb where time > now() -1h and time < now()
name: test
tagKey
------
test_key
test_key_1
test_key_2
// Find tag keys between one and two hours ago
> SHOW TAG KEYS ON mydb where > time > now() -2h and time < now()-1h
name: test
tagKey
------
test_key_1
test_key_2
test_key_3
// Find tag keys between two and three hours ago
> SHOW TAG KEYS ON mydb where > time > now() -3h and time < now()-2h
name: test
tagKey
------select statement
test_key_3
test_key_4
test_key_5
// For a specified measurement, find tag keys in a given shard by specifying the time boundaries of the shard
SELECT * FROM test WHERE time >= '2019-08-09T00:00:00Z' and time < '2019-08-09T10:00:00Z'
name: test
time test_key_4 test_key_5 value
---- ------------ ------------ -----
434817 hello 1
434817 hello 1
// For a specified database, find tag keys in a given shard by specifying the time boundaries of the shard
> SHOW TAG KEYS ON mydb WHERE time >= '2019-08-09T00:00:00Z' and time < '2019-08-09T10:00:00Z'
name: test
tagKey
------
test_key_4
test_key_5
``` -->

View File

@ -0,0 +1,75 @@
---
title: View InfluxQL functions
description: >
Aggregate, select, transform, and predict data with InfluxQL functions.
menu:
influxdb_2_4:
name: InfluxQL functions
parent: Query with InfluxQL
weight: 203
---
Use InfluxQL functions to aggregate, select, transform, analyze, and predict data.
{{% note %}}
To query with InfluxQL, the bucket you query must be mapped to a database and retention policy (DBRP). For more information, see how to [Query data with InfluxQL](/influxdb/v2.4/query-data/influxql/).
{{%/ note %}}
## InfluxQL functions (by type)
- [Aggregates](/influxdb/v2.4/query-data/influxql/functions/aggregates/)
- [COUNT()](/influxdb/v2.4/query-data/influxql/functions/aggregates/#count)
- [DISTINCT()](/influxdb/v2.4/query-data/influxql/functions/aggregates/#distinct)
- [INTEGRAL()](/influxdb/v2.4/query-data/influxql/functions/aggregates/#integral)
- [MEAN()](/influxdb/v2.4/query-data/influxql/functions/aggregates/#mean)
- [MEDIAN()](/influxdb/v2.4/query-data/influxql/functions/aggregates/#median)
- [MODE()](/influxdb/v2.4/query-data/influxql/functions/aggregates/#mode)
- [SPREAD()](/influxdb/v2.4/query-data/influxql/functions/aggregates/#spread)
- [STDDEV()](/influxdb/v2.4/query-data/influxql/functions/aggregates/#stddev)
- [SUM()](/influxdb/v2.4/query-data/influxql/functions/aggregates/#sum)
- [Selectors](/influxdb/v2.4/query-data/influxql/functions/selectors/)
- [BOTTOM()](/influxdb/v2.4/query-data/influxql/functions/selectors/#bottom)
- [FIRST()](/influxdb/v2.4/query-data/influxql/functions/selectors/#first)
- [LAST()](/influxdb/v2.4/query-data/influxql/functions/selectors/#last)
- [MAX()](/influxdb/v2.4/query-data/influxql/functions/selectors/#max)
- [MIN()](/influxdb/v2.4/query-data/influxql/functions/selectors/#min)
- [PERCENTILE()](/influxdb/v2.4/query-data/influxql/functions/selectors/#percentile)
- [SAMPLE()](/influxdb/v2.4/query-data/influxql/functions/selectors/#sample)
- [TOP()](/influxdb/v2.4/query-data/influxql/functions/selectors/#top)
- [Transformations](/influxdb/v2.4/query-data/influxql/functions/transformations/)
- [ABS()](/influxdb/v2.4/query-data/influxql/functions/transformations/#abs)
- [ACOS()](/influxdb/v2.4/query-data/influxql/functions/transformations/#acos)
- [ASIN()](/influxdb/v2.4/query-data/influxql/functions/transformations/#asin)
- [ATAN()](/influxdb/v2.4/query-data/influxql/functions/transformations/#atan)
- [ATAN2()](/influxdb/v2.4/query-data/influxql/functions/transformations/#atan2)
- [CEIL()](/influxdb/v2.4/query-data/influxql/functions/transformations/#ceil)
- [COS()](/influxdb/v2.4/query-data/influxql/functions/transformations/#cos)
- [CUMULATIVE_SUM()](/influxdb/v2.4/query-data/influxql/functions/transformations/#cumulative_sum)
- [DERIVATIVE()](/influxdb/v2.4/query-data/influxql/functions/transformations/#derivative)
- [DIFFERENCE()](/influxdb/v2.4/query-data/influxql/functions/transformations/#difference)
- [ELAPSED()](/influxdb/v2.4/query-data/influxql/functions/transformations/#elapsed)
- [EXP()](/influxdb/v2.4/query-data/influxql/functions/transformations/#exp)
- [FLOOR()](/influxdb/v2.4/query-data/influxql/functions/transformations/#floor)
- [HISTOGRAM()](/influxdb/v2.4/query-data/influxql/functions/transformations/#histogram)
- [LN()](/influxdb/v2.4/query-data/influxql/functions/transformations/#ln)
- [LOG()](/influxdb/v2.4/query-data/influxql/functions/transformations/#log)
- [LOG2()](/influxdb/v2.4/query-data/influxql/functions/transformations/#log2)
- [LOG10()](/influxdb/v2.4/query-data/influxql/functions/transformations/#log10)
- [MOVING_AVERAGE()](/influxdb/v2.4/query-data/influxql/functions/transformations/#moving_average)
- [NON_NEGATIVE_DERIVATIVE()](/influxdb/v2.4/query-data/influxql/functions/transformations/#non_negative_derivative)
- [NON_NEGATIVE_DIFFERENCE()](/influxdb/v2.4/query-data/influxql/functions/transformations/#non_negative_difference)
- [POW()](/influxdb/v2.4/query-data/influxql/functions/transformations/#pow)
- [ROUND()](/influxdb/v2.4/query-data/influxql/functions/transformations/#round)
- [SIN()](/influxdb/v2.4/query-data/influxql/functions/transformations/#sin)
- [SQRT()](/influxdb/v2.4/query-data/influxql/functions/transformations/#sqrt)
- [TAN()](/influxdb/v2.4/query-data/influxql/functions/transformations/#tan)
- [Technical analysis](/influxdb/v2.4/query-data/influxql/functions/technical-analysis/)
- (Predictive analysis) [HOLT_WINTERS()](/influxdb/v2.4/query-data/influxql/functions/technical-analysis/#holt_winters)
- [CHANDE_MOMENTUM_OSCILLATOR()](/influxdb/v2.4/query-data/influxql/functions/technical-analysis/#chande_momentum_oscillator)
- [EXPONENTIAL_MOVING_AVERAGE()](/influxdb/v2.4/query-data/influxql/functions/technical-analysis/#exponential_moving_average)
- [DOUBLE_EXPONENTIAL_MOVING_AVERAGE()](/influxdb/v2.4/query-data/influxql/functions/technical-analysis/#double_exponential_moving_average)
- [KAUFMANS_EFFICIENCY_RATIO()](/influxdb/v2.4/query-data/influxql/functions/technical-analysis/#kaufmans_adaptive_moving_average)
- [KAUFMANS_ADAPTIVE_MOVING_AVERAGE()](/influxdb/v2.4/query-data/influxql/functions/technical-analysis/#kaufmans_adaptive_moving_average)
- [TRIPLE_EXPONENTIAL_MOVING_AVERAGE()](/influxdb/v2.4/query-data/influxql/functions/technical-analysis/#triple_exponential_moving_average)
- [TRIPLE_EXPONENTIAL_DERIVATIVE()](/influxdb/v2.4/query-data/influxql/functions/technical-analysis/#triple_exponential_derivative)
- [RELATIVE_STRENGTH_INDEX()](/influxdb/v2.4/query-data/influxql/functions/technical-analysis/#relative_strength_index)

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,659 @@
---
title: InfluxQL analysis functions
list_title: Technical analysis functions
description: >
Use technical analysis functions to apply algorithms to your data.
menu:
influxdb_2_4:
name: Technical analysis
parent: InfluxQL functions
weight: 205
---
Use technical analysis functions to apply algorithms to your data--often used to analyze financial and investment data.
Each analysis function below covers **syntax**, including parameters to pass to the function, and **examples** of how to use the function. Examples use [NOAA water sample data](/influxdb/v2.4/reference/sample-data/#noaa-water-sample-data).
- [Predictive analysis](#predictive-analysis):
- [HOLT_WINTERS()](#holt_winters)
- [Technical analysis](#technical-analysis-functions):
- [CHANDE_MOMENTUM_OSCILLATOR()](#chande_momentum_oscillator)
- [EXPONENTIAL_MOVING_AVERAGE()](#exponential_moving_average)
- [DOUBLE_EXPONENTIAL_MOVING_AVERAGE()](#double_exponential_moving_average)
- [KAUFMANS_EFFICIENCY_RATIO()](#kaufmans_efficiency_ratio)
- [KAUFMANS_ADAPTIVE_MOVING_AVERAGE()](#kaufmans_adaptive_moving_average)
- [TRIPLE_EXPONENTIAL_MOVING_AVERAGE()](#triple_exponential_moving_average)
- [TRIPLE_EXPONENTIAL_DERIVATIVE()](#triple_exponential_derivative)
- [RELATIVE_STRENGTH_INDEX()](#relative_strength_index)
## Predictive analysis
Predictive analysis functions are a type of technical analysis algorithms that
predict and forecast future values.
### HOLT_WINTERS()
Returns N number of predicted [field values](/influxdb/v2.4/reference/glossary/#field-value)
using the [Holt-Winters](https://www.otexts.org/fpp/7/5) seasonal method.
Supports int64 and float64 field value [data types](/influxdb/v2.4/query-data/influxql/explore-data/select/#data-types).
Works with data that occurs at consistent time intervals.
Requires an InfluxQL function and the `GROUP BY time()` clause to ensure that
the Holt-Winters function operates on regular data.
Use `HOLT_WINTERS()` to:
- Predict when data values will cross a given threshold
- Compare predicted values with actual values to detect anomalies in your data
#### Syntax
```
SELECT HOLT_WINTERS[_WITH-FIT](<function>(<field_key>),<N>,<S>) FROM_clause [WHERE_clause] GROUP_BY_clause [ORDER_BY_clause] [LIMIT_clause] [OFFSET_clause] [SLIMIT_clause] [SOFFSET_clause]
```
`HOLT_WINTERS(function(field_key),N,S)` returns `N` seasonally adjusted
predicted field values for the specified [field key](/influxdb/v2.4/reference/glossary/#field-key).
The `N` predicted values occur at the same interval as the [`GROUP BY time()` interval](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-time-intervals).
If your `GROUP BY time()` interval is `6m` and `N` is `3` you'll
receive three predicted values that are each six minutes apart.
`S` is the seasonal pattern parameter and delimits the length of a seasonal
pattern according to the `GROUP BY time()` interval.
If your `GROUP BY time()` interval is `2m` and `S` is `3`, then the
seasonal pattern occurs every six minutes, that is, every three data points.
If you do not want to seasonally adjust your predicted values, set `S` to `0`
or `1.`
`HOLT_WINTERS_WITH_FIT(function(field_key),N,S)` returns the fitted values in
addition to `N` seasonally adjusted predicted field values for the specified field key.
#### Examples
{{< expand-wrapper >}}
{{% expand "Predict field values associated with a field key" %}}
##### Sample data
The examples use the following subset of the [NOAA water sample data](/influxdb/v2.4/reference/sample-data/#noaa-water-sample-data):
```sql
SELECT "water_level" FROM "noaa"."autogen"."h2o_feet" WHERE "location"='santa_monica' AND time >= '2019-08-17T00:00:00Z' AND time <= '2019-08-22T00:00:00Z'
```
##### Step 1: Match the trends of the raw data
Write a `GROUP BY time()` query that matches the general trends of the raw `water_level` data.
Here, we use the [`FIRST()`](/influxdb/v2.4/query-data/influxql/functions/selectors/#first) function:
```sql
SELECT FIRST("water_level") FROM "noaa"."autogen"."h2o_feet" WHERE "location"='santa_monica' and time >= '2019-08-17T00:00:00Z' AND time <= '2019-08-22T00:00:00Z' GROUP BY time(6h,6h)
```
In the `GROUP BY time()` clause, the first argument (`6h`) matches
the length of time that occurs between each peak and trough in the `water_level` data.
The second argument (`6h`) is the
[offset interval](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#advanced-group-by-time-syntax).
The offset interval alters the default `GROUP BY time()` boundaries to
match the time range of the raw data.
{{< img-hd src="/img/influxdb/2-4-influxql-holtwinters-1.png" alt="Holt Winters base data" />}}
###### Step 2: Determine the seasonal pattern
Identify the seasonal pattern in the data using the information from the
query in step 1.
The pattern in the `water_level` data repeats about every 12 hours.
There are two data points per season, so `2` is the seasonal pattern argument.
{{< img-hd src="/img/influxdb/2-4-influxql-holtwinters-2.png" alt="Holt Winters seasonal data" />}}
###### Step 3: Apply the HOLT_WINTERS() function
Add the Holt-Winters function to the query.
Here, we use `HOLT_WINTERS_WITH_FIT()` to view both the fitted values and the predicted values:
```sql
SELECT HOLT_WINTERS_WITH_FIT(FIRST("water_level"),10,2) FROM "noaa"."autogen"."h2o_feet" WHERE "location"='santa_monica' AND time >= '2019-08-17 00:00:00' AND time <= '2019-08-22 00:00:00' GROUP BY time(6h,6h)
```
In the `HOLT_WINTERS_WITH_FIT()` function, the first argument (`10`) requests 10 predicted field values.
Each predicted point is `6h` apart, the same interval as the first argument in the `GROUP BY time()` clause.
The second argument in the `HOLT_WINTERS_WITH_FIT()` function (`2`) is the seasonal pattern that we determined in the previous step.
{{< img-hd src="/img/influxdb/2-4-influxql-holtwinters-3.png" alt="Holt Winters predicted data" />}}
{{% /expand %}}
{{< /expand-wrapper >}}
#### Common issues with `HOLT_WINTERS()`
##### Receiving fewer than `N` points
In some cases, you may receive fewer predicted points than requested by the `N` parameter.
That behavior typically occurs when the math becomes unstable and cannot forecast more
points. In this case, `HOLT_WINTERS()` may not be suited for the dataset or the seasonal adjustment parameter is invalid.
## Technical analysis functions
Technical analysis functions apply widely used algorithms to your data.
While they are primarily used in finance and investing, they have
application in other industries.
For technical analysis functions, consider whether to include the `PERIOD`, `HOLD_PERIOD`, and `WARMUP_TYPE` arguments:
#### `PERIOD`
**Required, integer, min=1**
The sample size for the algorithm, which is the number of historical samples with significant
effect on the output of the algorithm.
For example, `2` means the current point and the point before it.
The algorithm uses an exponential decay rate to determine the weight of a historical point,
generally known as the alpha (α). The `PERIOD` controls the decay rate.
{{% note %}}
**Note:** Older points can still have an impact.
{{% /note %}}
#### `HOLD_PERIOD`
**integer, min=-1**
How many samples the algorithm needs before emitting results.
The default of `-1` means the value is based on the algorithm, the `PERIOD`,
and the `WARMUP_TYPE`. Verify this value is enough for the algorithm to emit meaningful results.
_**Default hold periods:**_
For most technical analysis functions, the default `HOLD_PERIOD` is
determined by the function and the [`WARMUP_TYPE`](#warmup_type) shown in the following table:
| Algorithm \ Warmup Type | simple | exponential | none |
| --------------------------------- | ---------------------- | ----------- |:----------: |
| [EXPONENTIAL_MOVING_AVERAGE](#exponential_moving_average) | PERIOD - 1 | PERIOD - 1 | <span style="opacity:.35">n/a</span> |
| [DOUBLE_EXPONENTIAL_MOVING_AVERAGE](#double_exponential_moving_average) | ( PERIOD - 1 ) * 2 | PERIOD - 1 | <span style="opacity:.35">n/a</span> |
| [TRIPLE_EXPONENTIAL_MOVING_AVERAGE](#triple_exponential_moving_average) | ( PERIOD - 1 ) * 3 | PERIOD - 1 | <span style="opacity:.35">n/a</span> |
| [TRIPLE_EXPONENTIAL_DERIVATIVE](#triple_exponential_derivative) | ( PERIOD - 1 ) * 3 + 1 | PERIOD | <span style="opacity:.35">n/a</span> |
| [RELATIVE_STRENGTH_INDEX](#relative_strength_index) | PERIOD | PERIOD | <span style="opacity:.35">n/a</span> |
| [CHANDE_MOMENTUM_OSCILLATOR](#chande_momentum_oscillator) | PERIOD | PERIOD | PERIOD - 1 |
_**Kaufman algorithm default hold periods:**_
| Algorithm | Default Hold Period |
| --------- | ------------------- |
| [KAUFMANS_EFFICIENCY_RATIO()](#kaufmans_efficiency_ratio) | PERIOD |
| [KAUFMANS_ADAPTIVE_MOVING_AVERAGE()](#kaufmans_adaptive_moving_average) | PERIOD |
#### `WARMUP_TYPE`
**default='exponential'**
Controls how the algorithm initializes for the first `PERIOD` samples.
It is essentially the duration for which it has an incomplete sample set.
##### simple
Simple moving average (SMA) of the first `PERIOD` samples.
This is the method used by [ta-lib](https://www.ta-lib.org/).
##### exponential
Exponential moving average (EMA) with scaling alpha (α).
Uses an EMA with `PERIOD=1` for the first point, `PERIOD=2`
for the second point, and so on, until the algorithm has consumed `PERIOD` number of points.
As the algorithm immediately starts using an EMA, when this method is used and
`HOLD_PERIOD` is unspecified or `-1`, the algorithm may start emitting points
after a much smaller sample size than with `simple`.
##### none
The algorithm does not perform any smoothing at all.
Method used by [ta-lib](https://www.ta-lib.org/).
When this method is used and `HOLD_PERIOD` is unspecified, `HOLD_PERIOD`
defaults to `PERIOD - 1`.
{{% note %}}
**Note:** The `none` warmup type is only available with the [`CHANDE_MOMENTUM_OSCILLATOR()`](#chande_momentum_oscillator) function.
{{% /note %}}
## CHANDE_MOMENTUM_OSCILLATOR()
The Chande Momentum Oscillator (CMO) is a technical momentum indicator developed by Tushar Chande.
The CMO indicator is created by calculating the difference between the sum of all
recent higher data points and the sum of all recent lower data points,
then dividing the result by the sum of all data movement over a given time period.
The result is multiplied by 100 to give the -100 to +100 range.
<sup style="line-height:0; font-size:.7rem; font-style:italic; font-weight:normal;"><a href="https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/cmo" target="\_blank">Source</a>
Supports `GROUP BY` clauses that [group by tags](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-tags) but not `GROUP BY` clauses that [group by time](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-time-intervals). To use `CHANDE_MOMENTUM_OSCILLATOR()` with a `GROUP BY time()` clause, see [Advanced syntax](/influxdb/v2.4/query-data/influxql/functions/transformations/#advanced-syntax).
### Basic syntax
```
CHANDE_MOMENTUM_OSCILLATOR([ * | <field_key> | /regular_expression/ ], <period>[, <hold_period>, [warmup_type]])
```
### Arguments
- [period](#period)
- (Optional) [hold_period](#hold_period)
- (Optional) [warmup_type](#warmup_type)
`CHANDE_MOMENTUM_OSCILLATOR(field_key, 2)`
Returns the field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Chande Momentum Oscillator algorithm with a 2-value period
and the default hold period and warmup type.
`CHANDE_MOMENTUM_OSCILLATOR(field_key, 10, 9, 'none')`
Returns the field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Chande Momentum Oscillator algorithm with a 10-value period
a 9-value hold period, and the `none` warmup type.
`CHANDE_MOMENTUM_OSCILLATOR(MEAN(<field_key>), 2) ... GROUP BY time(1d)`
Returns the mean of field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Chande Momentum Oscillator algorithm with a 2-value period
and the default hold period and warmup type.
{{% note %}}
**Note:** When aggregating data with a `GROUP BY` clause, you must include an [aggregate function](/influxdb/v2.4/query-data/influxql/functions/aggregates/) in your call to the `CHANDE_MOMENTUM_OSCILLATOR()` function.
{{% /note %}}
`CHANDE_MOMENTUM_OSCILLATOR(/regular_expression/, 2)`
Returns the field values associated with each field key that matches the [regular expression](/influxdb/v2.4/query-data/influxql/explore-data/regular-expressions/)
processed using the Chande Momentum Oscillator algorithm with a 2-value period
and the default hold period and warmup type.
`CHANDE_MOMENTUM_OSCILLATOR(*, 2)`
Returns the field values associated with each field key in the [measurement](/influxdb/v2.4/reference/glossary/#measurement)
processed using the Chande Momentum Oscillator algorithm with a 2-value period
and the default hold period and warmup type.
`CHANDE_MOMENTUM_OSCILLATOR()` supports int64 and float64 field value [data types](/influxdb/v2.4/query-data/influxql/explore-data/select/#data-types).
## EXPONENTIAL_MOVING_AVERAGE()
An exponential moving average (EMA) (or exponentially weighted moving average) is a type of moving average similar to a [simple moving average](/influxdb/v2.4/query-data/influxql/functions/transformations/#moving_average),
except more weight is given to the latest data.
This type of moving average reacts faster to recent data changes than a simple moving average.
<sup style="line-height:0; font-size:.7rem; font-style:italic; font-weight:normal;"><a href="https://www.investopedia.com/terms/e/ema.asp" target="\_blank">Source</a>
Supports `GROUP BY` clauses that [group by tags](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-tags) but not `GROUP BY` clauses that [group by time](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-time-intervals).
To use `EXPONENTIAL_MOVING_AVERAGE()` with a `GROUP BY time()` clause, see [Advanced syntax](/influxdb/v2.4/query-data/influxql/functions/transformations/#advanced-syntax).
### Basic syntax
```sql
EXPONENTIAL_MOVING_AVERAGE([ * | <field_key> | /regular_expression/ ], <period>[, <hold_period)[, <warmup_type]])
```
`EXPONENTIAL_MOVING_AVERAGE(field_key, 2)`
Returns the field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`EXPONENTIAL_MOVING_AVERAGE(field_key, 10, 9, 'exponential')`
Returns the field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Exponential Moving Average algorithm with a 10-value period
a 9-value hold period, and the `exponential` warmup type.
`EXPONENTIAL_MOVING_AVERAGE(MEAN(<field_key>), 2) ... GROUP BY time(1d)`
Returns the mean of field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
{{% note %}}
**Note:** When aggregating data with a `GROUP BY` clause, you must include an [aggregate function](/influxdb/v2.4/query-data/influxql/functions/aggregates/) in your call to the `EXPONENTIAL_MOVING_AVERAGE()` function.
{{% /note %}}
`EXPONENTIAL_MOVING_AVERAGE(/regular_expression/, 2)`
Returns the field values associated with each field key that matches the [regular expression](/influxdb/v2.4/query-data/influxql/explore-data/regular-expressions/)
processed using the Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`EXPONENTIAL_MOVING_AVERAGE(*, 2)`
Returns the field values associated with each field key in the [measurement](/influxdb/v2.4/reference/glossary/#measurement)
processed using the Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`EXPONENTIAL_MOVING_AVERAGE()` supports int64 and float64 field value [data types](/influxdb/v2.4/query-data/influxql/explore-data/select/#data-types).
### Arguments
- [period](#period)
- (Optional) [hold_period](#hold_period)
- (Optional) [warmup_type](#warmup_type)
## DOUBLE_EXPONENTIAL_MOVING_AVERAGE()
The Double Exponential Moving Average (DEMA) attempts to remove the inherent lag
associated with moving averages by placing more weight on recent values.
The name suggests this is achieved by applying a double exponential smoothing which is not the case.
The value of an [EMA](#exponential_moving_average) is doubled.
To keep the value in line with the actual data and to remove the lag, the value "EMA of EMA"
is subtracted from the previously doubled EMA.
<sup style="line-height:0; font-size:.7rem; font-style:italic; font-weight:normal;"><a href="https://en.wikipedia.org/wiki/Double_exponential_moving_average" target="\_blank">Source</a>
Supports `GROUP BY` clauses that [group by tags](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-tags) but not `GROUP BY` clauses that [group by time](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-time-intervals).
To use `DOUBLE_EXPONENTIAL_MOVING_AVERAGE()` with a `GROUP BY time()` clause, see [Advanced syntax](/influxdb/v2.4/query-data/influxql/functions/transformations/#advanced-syntax).
### Basic syntax
```
DOUBLE_EXPONENTIAL_MOVING_AVERAGE([ * | <field_key> | /regular_expression/ ], <period>[, <hold_period)[, <warmup_type]])
```
`DOUBLE_EXPONENTIAL_MOVING_AVERAGE(field_key, 2)`
Returns the field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Double Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`DOUBLE_EXPONENTIAL_MOVING_AVERAGE(field_key, 10, 9, 'exponential')`
Returns the field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Double Exponential Moving Average algorithm with a 10-value period
a 9-value hold period, and the `exponential` warmup type.
`DOUBLE_EXPONENTIAL_MOVING_AVERAGE(MEAN(<field_key>), 2) ... GROUP BY time(1d)`
Returns the mean of field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Double Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
{{% note %}}
**Note:** When aggregating data with a `GROUP BY` clause, you must include an [aggregate function](/influxdb/v2.4/query-data/influxql/functions/aggregates/) in your call to the `DOUBLE_EXPONENTIAL_MOVING_AVERAGE()` function.
{{% /note %}}
`DOUBLE_EXPONENTIAL_MOVING_AVERAGE(/regular_expression/, 2)`
Returns the field values associated with each field key that matches the [regular expression](/influxdb/v2.4/query-data/influxql/explore-data/regular-expressions/)
processed using the Double Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`DOUBLE_EXPONENTIAL_MOVING_AVERAGE(*, 2)`
Returns the field values associated with each field key in the [measurement](/influxdb/v2.4/reference/glossary/#measurement)
processed using the Double Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`DOUBLE_EXPONENTIAL_MOVING_AVERAGE()` supports int64 and float64 field value [data types](/influxdb/v2.4/query-data/influxql/explore-data/select/#data-types).
### Arguments
- [period](#period)
- (Optional) [hold_period](#hold_period)
- (Optional) [warmup_type](#warmup_type)
## KAUFMANS_EFFICIENCY_RATIO()
Kaufman's Efficiency Ration, or simply "Efficiency Ratio" (ER), is calculated by
dividing the data change over a period by the absolute sum of the data movements
that occurred to achieve that change.
The resulting ratio ranges between 0 and 1 with higher values representing a
more efficient or trending market.
The ER is very similar to the [Chande Momentum Oscillator](#chande_momentum_oscillator) (CMO).
The difference is that the CMO takes market direction into account, but if you take the absolute CMO and divide by 100, you you get the Efficiency Ratio.
<sup style="line-height:0; font-size:.7rem; font-style:italic; font-weight:normal;"><a href="http://etfhq.com/blog/2011/02/07/kaufmans-efficiency-ratio/" target="\_blank">Source</a>
Supports `GROUP BY` clauses that [group by tags](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-tags) but not `GROUP BY` clauses that [group by time](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-time-intervals).
To use `KAUFMANS_EFFICIENCY_RATIO()` with a `GROUP BY time()` clause, see [Advanced syntax](/influxdb/v2.4/query-data/influxql/functions/transformations/#advanced-syntax).
### Basic syntax
```
KAUFMANS_EFFICIENCY_RATIO([ * | <field_key> | /regular_expression/ ], <period>[, <hold_period>])
```
`KAUFMANS_EFFICIENCY_RATIO(field_key, 2)`
Returns the field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Efficiency Index algorithm with a 2-value period
and the default hold period and warmup type.
`KAUFMANS_EFFICIENCY_RATIO(field_key, 10, 10)`
Returns the field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Efficiency Index algorithm with a 10-value period and
a 10-value hold period.
`KAUFMANS_EFFICIENCY_RATIO(MEAN(<field_key>), 2) ... GROUP BY time(1d)`
Returns the mean of field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Efficiency Index algorithm with a 2-value period
and the default hold period.
{{% note %}}
**Note:** When aggregating data with a `GROUP BY` clause, you must include an [aggregate function](/influxdb/v2.4/query-data/influxql/functions/aggregates/) in your call to the `KAUFMANS_EFFICIENCY_RATIO()` function.
{{% /note %}}
`KAUFMANS_EFFICIENCY_RATIO(/regular_expression/, 2)`
Returns the field values associated with each field key that matches the [regular expression](/influxdb/v2.4/query-data/influxql/explore-data/regular-expressions/)
processed using the Efficiency Index algorithm with a 2-value period
and the default hold period and warmup type.
`KAUFMANS_EFFICIENCY_RATIO(*, 2)`
Returns the field values associated with each field key in the [measurement](/influxdb/v2.4/reference/glossary/#measurement)
processed using the Efficiency Index algorithm with a 2-value period
and the default hold period and warmup type.
`KAUFMANS_EFFICIENCY_RATIO()` supports int64 and float64 field value [data types](/influxdb/v2.4/query-data/influxql/explore-data/select/#data-types).
**Arguments:**
- [period](#period)
- (Optional) [hold_period](#hold_period)
## KAUFMANS_ADAPTIVE_MOVING_AVERAGE()
Kaufman's Adaptive Moving Average (KAMA) is a moving average designed to
account for sample noise or volatility.
KAMA will closely follow data points when the data swings are relatively small and noise is low.
KAMA will adjust when the data swings widen and follow data from a greater distance.
This trend-following indicator can be used to identify the overall trend,
time turning points and filter data movements.
<sup style="line-height:0; font-size:.7rem; font-style:italic; font-weight:normal;"><a href="http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:kaufman_s_adaptive_moving_average" target="\_blank">Source</a>
Supports `GROUP BY` clauses that [group by tags](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-tags) but not `GROUP BY` clauses that [group by time](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-time-intervals).
To use `KAUFMANS_ADAPTIVE_MOVING_AVERAGE()` with a `GROUP BY time()` clause, see [Advanced syntax](/influxdb/v2.4/query-data/influxql/functions/transformations/#advanced-syntax).
### Basic syntax
```
KAUFMANS_ADAPTIVE_MOVING_AVERAGE([ * | <field_key> | /regular_expression/ ], <period>[, <hold_period>])
```
`KAUFMANS_ADAPTIVE_MOVING_AVERAGE(field_key, 2)`
Returns the field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Kaufman Adaptive Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`KAUFMANS_ADAPTIVE_MOVING_AVERAGE(field_key, 10, 10)`
Returns the field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Kaufman Adaptive Moving Average algorithm with a 10-value period
and a 10-value hold period.
`KAUFMANS_ADAPTIVE_MOVING_AVERAGE(MEAN(<field_key>), 2) ... GROUP BY time(1d)`
Returns the mean of field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Kaufman Adaptive Moving Average algorithm with a 2-value period
and the default hold period.
{{% note %}}
**Note:** When aggregating data with a `GROUP BY` clause, you must include an [aggregate function](/influxdb/v2.4/query-data/influxql/functions/aggregates/) in your call to the `KAUFMANS_ADAPTIVE_MOVING_AVERAGE()` function.
{{% /note %}}
`KAUFMANS_ADAPTIVE_MOVING_AVERAGE(/regular_expression/, 2)`
Returns the field values associated with each field key that matches the [regular expression](/influxdb/v2.4/query-data/influxql/explore-data/regular-expressions/)
processed using the Kaufman Adaptive Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`KAUFMANS_ADAPTIVE_MOVING_AVERAGE(*, 2)`
Returns the field values associated with each field key in the [measurement](/influxdb/v2.4/reference/glossary/#measurement)
processed using the Kaufman Adaptive Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`KAUFMANS_ADAPTIVE_MOVING_AVERAGE()` supports int64 and float64 field value [data types](/influxdb/v2.4/query-data/influxql/explore-data/select/#data-types).
**Arguments:**
- [period](#period)
- (Optional) [hold_period](#hold_period)
## TRIPLE_EXPONENTIAL_MOVING_AVERAGE()
The triple exponential moving average (TEMA) filters out
volatility from conventional moving averages.
While the name implies that it's a triple exponential smoothing, it's actually a
composite of a [single exponential moving average](#exponential_moving_average),
a [double exponential moving average](#double_exponential_moving_average),
and a triple exponential moving average.
<sup style="line-height:0; font-size:.7rem; font-style:italic; font-weight:normal;"><a href="https://www.investopedia.com/terms/t/triple-exponential-moving-average.asp " target="\_blank">Source</a>
Supports `GROUP BY` clauses that [group by tags](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-tags) but not `GROUP BY` clauses that [group by time](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-time-intervals).
To use `TRIPLE_EXPONENTIAL_MOVING_AVERAGE()` with a `GROUP BY time()` clause, see [Advanced syntax](/influxdb/v2.4/query-data/influxql/functions/transformations/#advanced-syntax).
### Basic syntax
```
TRIPLE_EXPONENTIAL_MOVING_AVERAGE([ * | <field_key> | /regular_expression/ ], <period>[, <hold_period)[, <warmup_type]])
```
`TRIPLE_EXPONENTIAL_MOVING_AVERAGE(field_key, 2)`
Returns the field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Triple Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`TRIPLE_EXPONENTIAL_MOVING_AVERAGE(field_key, 10, 9, 'exponential')`
Returns the field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Triple Exponential Moving Average algorithm with a 10-value period
a 9-value hold period, and the `exponential` warmup type.
`TRIPLE_EXPONENTIAL_MOVING_AVERAGE(MEAN(<field_key>), 2) ... GROUP BY time(1d)`
Returns the mean of field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Triple Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
{{% note %}}
**Note:** When aggregating data with a `GROUP BY` clause, you must include an [aggregate function](/influxdb/v2.4/query-data/influxql/functions/aggregates/) in your call to the `TRIPLE_EXPONENTIAL_MOVING_AVERAGE()` function.
{{% /note %}}
`TRIPLE_EXPONENTIAL_MOVING_AVERAGE(/regular_expression/, 2)`
Returns the field values associated with each field key that matches the [regular expression](/influxdb/v2.4/query-data/influxql/explore-data/regular-expressions/)
processed using the Triple Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`TRIPLE_EXPONENTIAL_MOVING_AVERAGE(*, 2)`
Returns the field values associated with each field key in the [measurement](/influxdb/v2.4/reference/glossary/#measurement)
processed using the Triple Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`TRIPLE_EXPONENTIAL_MOVING_AVERAGE()` supports int64 and float64 field value [data types](/influxdb/v2.4/query-data/influxql/explore-data/select/#data-types).
**Arguments:**
- [period](#period)
- (Optional) [hold_period](#hold_period)
- (Optional) [warmup_type](#warmup_type)
## TRIPLE_EXPONENTIAL_DERIVATIVE()
The triple exponential derivative indicator, commonly referred to as "TRIX," is
an oscillator used to identify oversold and overbought markets, and can also be
used as a momentum indicator.
TRIX calculates a [triple exponential moving average](#triple_exponential_moving_average)
of the [log](/influxdb/v2.4/query-data/influxql/functions/transformations/#log)
of the data input over the period of time.
The previous value is subtracted from the previous value.
This prevents cycles that are shorter than the defined period from being considered by the indicator.
Like many oscillators, TRIX oscillates around a zero line. When used as an oscillator,
a positive value indicates an overbought market while a negative value indicates an oversold market.
When used as a momentum indicator, a positive value suggests momentum is increasing
while a negative value suggests momentum is decreasing.
Many analysts believe that when the TRIX crosses above the zero line it gives a
buy signal, and when it closes below the zero line, it gives a sell signal.
<sup style="line-height:0; font-size:.7rem; font-style:italic; font-weight:normal;"><a href="https://www.investopedia.com/articles/technical/02/092402.asp " target="\_blank">Source</a>
Supports `GROUP BY` clauses that [group by tags](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-tags) but not `GROUP BY` clauses that [group by time](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-time-intervals).
To use `TRIPLE_EXPONENTIAL_DERIVATIVE()` with a `GROUP BY time()` clause, see [Advanced syntax](/influxdb/v2.4/query-data/influxql/functions/transformations/#advanced-syntax).
### Basic syntax
```
TRIPLE_EXPONENTIAL_DERIVATIVE([ * | <field_key> | /regular_expression/ ], <period>[, <hold_period)[, <warmup_type]])
```
`TRIPLE_EXPONENTIAL_DERIVATIVE(field_key, 2)`
Returns the field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Triple Exponential Derivative algorithm with a 2-value period
and the default hold period and warmup type.
`TRIPLE_EXPONENTIAL_DERIVATIVE(field_key, 10, 10, 'exponential')`
Returns the field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Triple Exponential Derivative algorithm with a 10-value period,
a 10-value hold period, and the `exponential` warmup type.
`TRIPLE_EXPONENTIAL_DERIVATIVE(MEAN(<field_key>), 2) ... GROUP BY time(1d)`
Returns the mean of field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Triple Exponential Derivative algorithm with a 2-value period
and the default hold period and warmup type.
{{% note %}}
**Note:** When aggregating data with a `GROUP BY` clause, you must include an [aggregate function](/influxdb/v2.4/query-data/influxql/functions/aggregates/) in your call to the `TRIPLE_EXPONENTIAL_DERIVATIVE()` function.
{{% /note %}}
`TRIPLE_EXPONENTIAL_DERIVATIVE(/regular_expression/, 2)`
Returns the field values associated with each field key that matches the [regular expression](/influxdb/v2.4/query-data/influxql/explore-data/regular-expressions/)
processed using the Triple Exponential Derivative algorithm with a 2-value period
and the default hold period and warmup type.
`TRIPLE_EXPONENTIAL_DERIVATIVE(*, 2)`
Returns the field values associated with each field key in the [measurement](/influxdb/v2.4/reference/glossary/#measurement)
processed using the Triple Exponential Derivative algorithm with a 2-value period
and the default hold period and warmup type.
`TRIPLE_EXPONENTIAL_DERIVATIVE()` supports int64 and float64 field value [data types](/influxdb/v2.4/query-data/influxql/explore-data/select/#data-types).
## RELATIVE_STRENGTH_INDEX()
The relative strength index (RSI) is a momentum indicator that compares the magnitude of recent increases and decreases over a specified time period to measure speed and change of data movements.
<sup style="line-height:0; font-size:.7rem; font-style:italic; font-weight:normal;"><a href="https://www.investopedia.com/terms/r/rsi.asp" target="\_blank">Source</a>
Supports `GROUP BY` clauses that [group by tags](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-tags) but not `GROUP BY` clauses that [group by time](/influxdb/v2.4/query-data/influxql/explore-data/group-by/#group-by-time-intervals).
To use `RELATIVE_STRENGTH_INDEX()` with a `GROUP BY time()` clause, see [Advanced syntax](/influxdb/v2.4/query-data/influxql/functions/transformations/#advanced-syntax).
### Basic syntax
```
RELATIVE_STRENGTH_INDEX([ * | <field_key> | /regular_expression/ ], <period>[, <hold_period)[, <warmup_type]])
```
`RELATIVE_STRENGTH_INDEX(field_key, 2)`
Returns the field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Relative Strength Index algorithm with a 2-value period
and the default hold period and warmup type.
`RELATIVE_STRENGTH_INDEX(field_key, 10, 10, 'exponential')`
Returns the field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Relative Strength Index algorithm with a 10-value period,
a 10-value hold period, and the `exponential` warmup type.
`RELATIVE_STRENGTH_INDEX(MEAN(<field_key>), 2) ... GROUP BY time(1d)`
Returns the mean of field values associated with the [field key](/influxdb/v2.4/reference/glossary/#field-key)
processed using the Relative Strength Index algorithm with a 2-value period
and the default hold period and warmup type.
{{% note %}}
**Note:** When aggregating data with a `GROUP BY` clause, you must include an [aggregate function](/influxdb/v2.4/query-data/influxql/functions/aggregates/) in your call to the `RELATIVE_STRENGTH_INDEX()` function.
{{% /note %}}
`RELATIVE_STRENGTH_INDEX(/regular_expression/, 2)`
Returns the field values associated with each field key that matches the [regular expression](/influxdb/v2.4/query-data/influxql/explore-data/regular-expressions/)
processed using the Relative Strength Index algorithm with a 2-value period
and the default hold period and warmup type.
`RELATIVE_STRENGTH_INDEX(*, 2)`
Returns the field values associated with each field key in the [measurement](/influxdb/v2.4/reference/glossary/#measurement)
processed using the Relative Strength Index algorithm with a 2-value period
and the default hold period and warmup type.
`RELATIVE_STRENGTH_INDEX()` supports int64 and float64 field value [data types](/influxdb/v2.4/query-data/influxql/explore-data/select/#data-types).
**Arguments:**
- [period](#period)
- (Optional) [hold_period](#hold_period)
- (Optional) [warmup_type](#warmup_type)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,149 @@
---
title: Manage your data using InfluxQL
description: >
Use InfluxQL data management commands to write and delete data.
menu:
influxdb_2_4:
name: Manage your data
parent: Query with InfluxQL
identifier: manage-database
weight: 204
---
Use the following data management commands to write and delete data with InfluxQL:
- [Write data with INSERT](#write-data-with-insert)
- [Delete series with DELETE](#delete-series-with-delete)
- [Delete measurements with DROP MEASUREMENT](#delete-measurements-with-drop-measurement)
## Write data with INSERT
The `INSERT` statement writes [line protocol](/influxdb/v2.4/reference/syntax/line-protocol/)
to a database and retention policy.
### Syntax
```sql
INSERT [INTO <database>[.<retention-policy>]] <line-protocol>
```
- The `INTO` clause is optional.
If the command does not include `INTO`, you must specify the
database with `USE <database_name>` when using the [InfluxQL shell](/influxdb/v2.4/tools/influxql-shell/)
or with the `db` query string parameter in the
[InfluxDB 1.x compatibility API](/influxdb/v2.4/reference/api/influxdb-1x/) request.
### Examples
- [Insert data into the a specific database and retention policy](#insert-data-into-the-a-specific-database-and-retention-policy)
- [Insert data into the a the default retention policy of a database](#insert-data-into-the-a-the-default-retention-policy-of-a-database)
- [Insert data into the currently used database](#insert-data-into-the-currently-used-database)
#### Insert data into the a specific database and retention policy
```sql
INSERT INTO mydb.myrp example-m,tag1=value1 field1=1i 1640995200000000000
```
#### Insert data into the a the default retention policy of a database
```sql
INSERT INTO mydb example-m,tag1=value1 field1=1i 1640995200000000000
```
#### Insert data into the currently used database
The following example uses the [InfluxQL shell](/influxdb/v2.4/tools/influxql-shell).
```sql
> USE mydb
> INSERT example-m,tag1=value1 field1=1i 1640995200000000000
```
## Delete series with DELETE
The `DELETE` statement deletes all points from a [series](/influxdb/v2.4/reference/glossary/#series) in a database.
### Syntax
```sql
DELETE FROM <measurement_name> WHERE [<tag_key>='<tag_value>'] | [<time interval>]
```
You must include either the [`FROM` clause](/influxdb/v2.4/query-data/influxql/explore-data/select/#from-clause), the [`WHERE` clause](/influxdb/v2.4/query-data/influxql/explore-data/where/), or both.
{{% note %}}
- `DELETE` supports [regular expressions](/influxdb/v2.4/query-data/influxql/explore-data/regular-expressions/)
in the `FROM` clause when specifying measurement names and in the `WHERE` clause
when specifying tag values.
- `DELETE` does not support [fields](/influxdb/v2.4/reference/glossary/#field) in the `WHERE` clause.
{{% /note %}}
### Examples
- [Delete all measurement data](#delete-all-measurement-data)
- [Delete data in a measurement that has a specific tag value](#delete-data-in-a-measurement-that-has-a-specific-tag-value)
- [Delete data before or after specified time](#delete-data-before-or-after-specified-time)
#### Delete all measurement data
Delete all data associated with the measurement `h2o_feet`:
```sql
DELETE FROM "h2o_feet"
```
#### Delete data in a measurement that has a specific tag value
Delete all data associated with the measurement `h2o_quality` and where the tag `randtag` equals `3`:
```sql
DELETE FROM "h2o_quality" WHERE "randtag" = '3'
```
#### Delete data before or after specified time
Delete all data in the database that occur before January 01, 2020:
```sql
DELETE WHERE time < '2020-01-01'
```
A successful `DELETE` query returns an empty result.
If you need to delete points in the future, you must specify the future time period because `DELETE SERIES` runs for `time < now()` by default.
Delete future points:
```sql
DELETE FROM device_data WHERE "device" = 'sensor1" and time > now() and < '2024-01-14T01:00:00Z'
```
Delete points in the future within a specified time range:
```sql
DELETE FROM device_data WHERE "device" = 'sensor15" and time >= '2024-01-01T12:00:00Z' and <= '2025-06-30T11:59:00Z'
```
## Delete measurements with DROP MEASUREMENT
The `DROP MEASUREMENT` statement deletes all data and series from the specified [measurement](/influxdb/v2.4/reference/glossary/#measurement) and deletes the measurement from the index.
#### Syntax
```sql
DROP MEASUREMENT <measurement_name>
```
#### Example
Delete the measurement `h2o_feet`:
```sql
DROP MEASUREMENT "h2o_feet"
```
A successful `DROP MEASUREMENT` query returns an empty result.
{{% warn %}}
The DROP MEASURMENT command is very resource intensive. We do not recommend this command for bulk data deletion. Use the DELETE FROM command instead, which is less resource intensive.
{{% /warn %}}

View File

@ -0,0 +1,318 @@
---
title: InfluxQL mathematical operators
descriptions: >
Use InfluxQL mathematical operators to perform mathematical operations in queries.
menu:
influxdb_2_4:
name: Mathematical operators
parent: Query with InfluxQL
identifier: influxql-mathematical-operators
weight: 209
---
Use InfluxQL mathematical operators to perform mathematical operations in 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)
- [Common Issues with Mathematical Operators](#common-issues-with-mathematical-operators)
## Addition
Perform addition with a constant.
```sql
SELECT "A" + 5 FROM "add"
```
```sql
SELECT * FROM "add" WHERE "A" + 5 > 10
```
Perform addition on two fields.
```sql
SELECT "A" + "B" FROM "add"
```
```sql
SELECT * FROM "add" WHERE "A" + "B" >= 10
```
## Subtraction
Perform subtraction with a constant.
```sql
SELECT 1 - "A" FROM "sub"
```
```sql
SELECT * FROM "sub" WHERE 1 - "A" <= 3
```
Perform subtraction with two fields.
```sql
SELECT "A" - "B" FROM "sub"
```
```sql
SELECT * FROM "sub" WHERE "A" - "B" <= 1
```
## Multiplication
Perform multiplication with a constant.
```sql
SELECT 10 * "A" FROM "mult"
```
```sql
SELECT * FROM "mult" WHERE "A" * 10 >= 20
```
Perform multiplication with two fields.
```sql
SELECT "A" * "B" * "C" FROM "mult"
```
```sql
SELECT * FROM "mult" WHERE "A" * "B" <= 80
```
Multiplication distributes across other operators.
```sql
SELECT 10 * ("A" + "B" + "C") FROM "mult"
```
```sql
SELECT 10 * ("A" - "B" - "C") FROM "mult"
```
```sql
SELECT 10 * ("A" + "B" - "C") FROM "mult"
```
## Division
Perform division with a constant.
```sql
SELECT 10 / "A" FROM "div"
```
```sql
SELECT * FROM "div" WHERE "A" / 10 <= 2
```
Perform division with two fields.
```sql
SELECT "A" / "B" FROM "div"
```
```sql
SELECT * FROM "div" WHERE "A" / "B" >= 10
```
Division distributes across other operators.
```sql
SELECT 10 / ("A" + "B" + "C") FROM "mult"
```
## Modulo
Perform modulo arithmetic with a constant.
```sql
SELECT "B" % 2 FROM "modulo"
```
```sql
SELECT "B" FROM "modulo" WHERE "B" % 2 = 0
```
Perform modulo arithmetic on two fields.
```sql
SELECT "A" % "B" FROM "modulo"
```
```sql
SELECT "A" FROM "modulo" WHERE "A" % "B" = 0
```
## Bitwise AND
You can use this operator with any integers or Booleans, whether they are fields or constants.
It does not work with float or string datatypes, and you cannot mix integers and Booleans.
```sql
SELECT "A" & 255 FROM "bitfields"
```
```sql
SELECT "A" & "B" FROM "bitfields"
```
```sql
SELECT * FROM "data" WHERE "bitfield" & 15 > 0
```
```sql
SELECT "A" & "B" FROM "booleans"
```
```sql
SELECT ("A" ^ true) & "B" FROM "booleans"
```
## Bitwise OR
You can use this operator with any integers or Booleans, whether they are fields or constants.
It does not work with float or string datatypes, and you cannot mix integers and Booleans.
```sql
SELECT "A" | 5 FROM "bitfields"
```
```sql
SELECT "A" | "B" FROM "bitfields"
```
```sql
SELECT * FROM "data" WHERE "bitfield" | 12 = 12
```
## Bitwise Exclusive-OR
You can use this operator with any integers or Booleans, whether they are fields or constants.
It does not work with float or string datatypes, and you cannot mix integers and Booleans.
```sql
SELECT "A" ^ 255 FROM "bitfields"
```
```sql
SELECT "A" ^ "B" FROM "bitfields"
```
```sql
SELECT * FROM "data" 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 tokens in InfluxQL.
However, you can apply the bitwise operators `&`, `|` and `^` to boolean data.
### 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 to you 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 "data"
```
For 16-bit data:
```sql
SELECT "A" ^ 65535 FROM "data"
```
For 32-bit data:
```sql
SELECT "A" ^ 4294967295 FROM "data"
```
In each case the constant you need can be calculated as `(2 ** width) - 1`.
## Common Issues with 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
InfluxDB does not support combining mathematical operations with a wildcard (`*`) or [regular expression](/influxdb/v2.4/query-data/influxql/explore-data/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
The use of mathematical operators inside of function calls is currently unsupported.
Note that InfluxDB 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.4/query-data/influxql/explore-data/subqueries/) which offer similar functionality to using mathematical operators inside a function call.
{{% /note %}}

View File

@ -51,6 +51,7 @@ weight: 9
- [What are the minimum and maximum integers that InfluxDB can store?](#what-are-the-minimum-and-maximum-integers-that-influxdb-can-store)
- [What are the minimum and maximum timestamps that InfluxDB can store?](#what-are-the-minimum-and-maximum-timestamps-that-influxdb-can-store)
- [Can I change a field's data type?](#can-i-change-a-fields-data-type)
- {{% oss-only %}}[How does InfluxDB handle field type discrepancies across shards?](#how-does-influxdb-handle-field-type-discrepancies-across-shards){{% /oss-only %}}
##### Writing data {href="writing-data"}
- [How do I write integer and unsigned integer field values?](#how-do-i-write-integer-and-unsigned-integer-field-values)
@ -413,6 +414,81 @@ Below are some possible workarounds:
|> to(bucket: "example-bucket-2")
```
#### How does InfluxDB handle field type discrepancies across shards?
Field values can be floats, integers, strings, or Booleans.
Field value types cannot differ within a
[shard](/enterprise_influxdb/v1.10/concepts/glossary/#shard), but they can [differ](/enterprise_influxdb/v1.10/write_protocols/line_protocol_reference) across shards.
The
[`SELECT` statement](/enterprise_influxdb/v1.10/query_language/explore-data/#the-basic-select-statement)
returns all field values **if** all values have the same type.
If field value types differ across shards, InfluxDB first performs any
applicable [cast](/enterprise_influxdb/v1.10/query_language/explore-data/#cast-operations)
operations and then returns all values with the type that occurs first in the
following list: float, integer, string, Boolean.
If your data have field value type discrepancies, use the syntax
`<field_key>::<type>` to query the different data types.
#### Example
The measurement `just_my_type` has a single field called `my_field`.
`my_field` has four field values across four different shards, and each value has
a different data type (float, integer, string, and Boolean).
`SELECT *` returns only the float and integer field values.
Note that InfluxDB casts the integer value to a float in the response.
```sql
SELECT * FROM just_my_type
name: just_my_type
------------------
time my_field
2016-06-03T15:45:00Z 9.87034
2016-06-03T16:45:00Z 7
```
`SELECT <field_key>::<type> [...]` returns all value types.
InfluxDB outputs each value type in its own column with incremented column names.
Where possible, InfluxDB casts field values to another type;
it casts the integer `7` to a float in the first column, and it
casts the float `9.879034` to an integer in the second column.
InfluxDB cannot cast floats or integers to strings or Booleans.
```sql
SELECT "my_field"::float,"my_field"::integer,"my_field"::string,"my_field"::boolean FROM just_my_type
name: just_my_type
------------------
time my_field my_field_1 my_field_2 my_field_3
2016-06-03T15:45:00Z 9.87034 9
2016-06-03T16:45:00Z 7 7
2016-06-03T17:45:00Z a string
2016-06-03T18:45:00Z true
```
`SHOW FIELD KEYS` returns every data type, across every shard, associated with
the field key.
#### Example
The measurement `just_my_type` has a single field called `my_field`.
`my_field` has four field values across four different shards, and each value has
a different data type (float, integer, string, and Boolean).
`SHOW FIELD KEYS` returns all four data types:
```sql
> SHOW FIELD KEYS
name: just_my_type
fieldKey fieldType
-------- ---------
my_field float
my_field string
my_field integer
my_field boolean
```
---
## Writing data

View File

@ -289,7 +289,11 @@ For more information about different data types, see:
In InfluxDB {{< current-version >}}, a database represents the InfluxDB instance as a whole.
Related entries: [continuous query](#continuous-query-cq), <!-- [retention policy](#retention-policy-rp),--> [user](#user)
#### 1.x database
In InfluxDB 1.x, a database represented a logical container for users, retention policies, continuous queries, and time series data. The InfluxDB 2.x equivalent of this concept is an InfluxDB [bucket](/influxdb/v2.4/reference/glossary/#bucket).
Related entries: [continuous query](#continuous-query-cq), [retention policy](#retention-policy-rp), [user](#user)
### date-time

View File

@ -0,0 +1,14 @@
---
title: InfluxQL syntax
list_title: InfluxQL
description: InfluxQL is an SQL-like query language for interacting with data in InfluxDB.
menu:
influxdb_2_4_ref:
parent: Syntax
name: InfluxQL
identifier: influxql-syntax
weight: 101
---
{{< children readmore=true hr=true >}}

View File

@ -0,0 +1,163 @@
---
title: InfluxQL internals reference
description: Read about the implementation of InfluxQL.
menu:
influxdb_2_4_ref:
name: InfluxQL internals
parent: influxql-syntax
weight: 103
---
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 provided 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, a statement
such as this:
```sql
SELECT MEAN(value) FROM cpu GROUP BY time(10m)
```
In this case, `MEAN(value)` is a `MeanIterator` wrapping an iterator from the
underlying shards. However, if we can add an additional iterator 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 trasverses 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 which do not need stronger sorting guarantees.
* Sorted Merge Iterator - This iterator also 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/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. It is resource
intensive so it 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 first
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,761 @@
---
title: Influx Query Language (InfluxQL) 2.x specification
description: Reference (spec) for Influx Query Language (InfluxQL) 2.x.
menu:
influxdb_2_4_ref:
name: InfluxQL 2.x specification
parent: influxql-syntax
aliases:
- /influxdb/v2.4/query_languages/spec/
weight: 105
---
InfluxQL is a SQL-like query language used to interact with InfluxDB and work with your times series data.
Find Influx Query Language (InfluxQL) definitions and details, including:
- [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.4/query-data/influxql/explore-data/)
- [Explore your schema with InfluxQL](/influxdb/v2.4/query-data/influxql/explore-schema/)
- [Database management](/influxdb/v2.4/query-data/influxql/manage-database/)
- [Query engine internals](/influxdb/v2.4/reference/syntax/influxql/internals/)
## Notation
The syntax is specified using Extended Backus-Naur Form ("EBNF").
EBNF is the same notation used in the [Go](http://golang.org) programming language specification,
which can be found [here](https://golang.org/ref/spec).
```
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 characters plus the underscore character _ (U+005F) is considered a letter.
Only decimal digits are supported.
```
letter = ascii_letter | "_" .
ascii_letter = "A" … "Z" | "a" … "z" .
digit = "0" … "9" .
```
### Identifiers
Identifiers are tokens which refer to [database](/influxdb/v2.4/reference/glossary/#database) names, [retention policy](/influxdb/v2.4/reference/glossary/#retention-policy-rp) names, [user](/influxdb/v2.4/reference/glossary/#user) names, [measurement](/influxdb/v2.4/reference/glossary/#measurement) names, [tag keys](/influxdb/v2.4/reference/glossary/#tag-key), and [field keys](/influxdb/v2.4/reference/glossary/#field-key).
The rules:
- double quoted identifiers can contain any unicode character other than a new line
- double quoted identifiers can contain escaped `"` characters (i.e., `\"`)
- double quoted identifiers can contain 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 keywords as an
[identifier](/influxdb/v2.4/reference/glossary/#identifier) you will need to
double quote that identifier in every query.
The keyword `time` is a special case.
`time` can be a
database name,
[measurement](/influxdb/v2.4/reference/glossary/#measurement) name,
[retention policy](/influxdb/v2.4/reference/glossary/#retention-policy-rp) name,
[subscription](/influxdb/v2.4/reference/glossary/#subscription) name, and
[user](/influxdb/v2.4/reference/glossary/#user) name.
In those cases, `time` does not require double quotes in queries.
`time` cannot be a [field key](/influxdb/v2.4/reference/glossary/#field-key) or
[tag key](/influxdb/v2.4/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.4/reference/faq/) for more information.
### Literals
#### Integers
InfluxQL supports decimal integer literals.
Hexadecimal and octal literals are not currently supported.
```
int_lit = ( "1" … "9" ) { digit } .
```
#### Floats
InfluxQL supports floating-point literals.
Exponents are not 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 a duration unit 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
The date and time literal format is not specified in EBNF like the rest of this document.
It is specified using Go's date / time parsing format, which is a reference date 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 %}}
**NOTE:** InfluxQL supports using regular expressions when specifying:
* [field keys](/influxdb/v2.4/reference/glossary/#field-key) and [tag keys](/influxdb/v2.4/reference/glossary/#tag-key) in the [`SELECT` clause](/influxdb/v2.4/query-data/influxql/explore-data/select/)
* [measurements](/influxdb/v2.4/reference/glossary/#measurement) in the [`FROM` clause](/influxdb/v2.4/query-data/influxql/explore-data/select/#from-clause)
* [tag values](/influxdb/v2.4/reference/glossary/#tag-value) and string [field values](/influxdb/v2.4/reference/glossary/#field-value) in the [`WHERE` clause](/influxdb/v2.4/query-data/influxql/explore-data/where/)
* [tag keys](/influxdb/v2.4/reference/glossary/#tag-key) in the [`GROUP BY` clause](/influxdb/v2.4/query-data/influxql/explore-data/group-by/)
Currently, InfluxQL does not support using regular expressions to match non-string field values in the `WHERE` clause, [databases](/influxdb/v2.4/reference/glossary/#database), and [retention polices](/influxdb/v2.4/reference/glossary/#retention-policy-rp).
{{% /note %}}
## Queries
A query is composed of one or more statements separated by a semicolon.
```
query = statement { ";" statement } .
statement = delete_stmt |
drop_measurement_stmt |
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
### DELETE
```
delete_stmt = "DELETE" ( from_clause | where_clause | from_clause where_clause ) .
```
#### Examples
```sql
DELETE FROM "cpu"
DELETE FROM "cpu" WHERE time < '2000-01-01T00:00:00Z'
DELETE WHERE time < '2000-01-01T00:00:00Z'
```
### DROP MEASUREMENT
```
drop_measurement_stmt = "DROP MEASUREMENT" measurement .
```
#### Examples
```sql
-- drop the cpu measurement
DROP MEASUREMENT "cpu"
```
### 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 does not support joins, the cost of a 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.
The elements of `EXPLAIN` query plan include:
- 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 on 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, executing 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'
```
May produce an output 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 is not accounted for.
##### 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 the executing the query. For example, the number of series keys required to execute a query affects how quickly the query is planned and the required memory.
First, InfluxDB determines the effective time range of the query and selects the shards to access (in InfluxDB Enterprise, shards may be on remote nodes).
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:
| `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 |
For more information about storage blocks, see [TSM files](/influxdb/v2.4/reference/internals/storage-engine/#time-structured-merge-tree-tsm).
### SELECT
```
select_stmt = "SELECT" fields from_clause [ where_clause ]
[ group_by_clause ] [ order_by_clause ] [ limit_clause ]
[ offset_clause ] [ slimit_clause ] [ soffset_clause ] [ timezone_clause ] .
```
#### Example
Select from measurements grouped by the day with a timezone
```sql
SELECT mean("value") FROM "cpu" GROUP BY region, time(1d) fill(0) tz('America/Chicago')
```
### SHOW CARDINALITY
Refers to the group of commands used to estimate or count exactly the cardinality of measurements, series, tag keys, tag key values, and field keys.
The SHOW CARDINALITY commands are available in two variations: estimated and exact. Estimated values are calculated using sketches and are a safe default for all cardinality sizes. Exact values are counts directly from TSM (Time-Structured Merge Tree) data, but are expensive to run for high cardinality data. Unless required, use the estimated variety.
Filtering by `time` is only supported when Time Series Index (TSI) is enabled on a database.
See the specific SHOW CARDINALITY commands for details:
- [SHOW FIELD KEY CARDINALITY](#show-field-key-cardinality)
- [SHOW SERIES CARDINALITY](#show-series-cardinality)
- [SHOW TAG KEY CARDINALITY](#show-tag-key-cardinality)
- [SHOW TAG VALUES CARDINALITY](#show-tag-values-cardinality)
### SHOW DATABASES
```
show_databases_stmt = "SHOW DATABASES" .
```
#### Example
```sql
-- show all databases
SHOW DATABASES
```
### SHOW FIELD KEY CARDINALITY
Estimates or counts exactly the cardinality of the field key set for the current database unless a database is specified using the `ON <database>` option.
> **Note:** `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 Time Series Index (TSI) is enabled and `time` is not supported in the `WHERE` clause.
```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
```
- [Series cardinality](/influxdb/v2.4/reference/glossary/#series-cardinality) is the major factor that affects RAM requirements. For more information, see:
- [Don't have too many series](/influxdb/v2.4/reference/faq/#why-does-series-cardinality-matter). As the number of unique series grows, so does the memory usage. High series cardinality can force the host operating system to kill the InfluxDB process with an out of memory (OOM) exception.
{{% 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.
```
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

@ -18,13 +18,15 @@ Additional users cannot be created in the InfluxDB UI.
## Create a user using the influx CLI
To create a new user, use the [`influx user create` command](/influxdb/v2.4/reference/cli/influx/user/create)
and include the following:
To create a new user, you must have an [operator token](/influxdb/v2.4/reference/glossary/#token). For more information, see how to [create an operator token](/influxdb/v2.4/security/tokens/create-token/#create-an-operator-token).
Use the [`influx user create` command](/influxdb/v2.4/reference/cli/influx/user/create) and include the following:
- Username
- Organization name or organization ID to add the user to _(provided in the output of
[`influx org list`](/influxdb/v2.4/reference/cli/influx/org/list/))_
{{< cli/influx-creds-note >}}
```sh
# Syntax
influx user create -n <username> -o <org-name>

View File

@ -2,51 +2,52 @@
title: Query data with InfluxQL
description: >
Use the [InfluxDB 1.x `/query` compatibility endpoint](/influxdb/v2.5/reference/api/influxdb-1x/query)
to query data in InfluxDB Cloud and InfluxDB OSS 2.5 with **InfluxQL**.
to query data in InfluxDB Cloud and InfluxDB OSS 2.4 with **InfluxQL**.
weight: 102
influxdb/v2.5/tags: [influxql, query]
menu:
influxdb_2_5:
name: Query with InfluxQL
parent: Query data
cascade:
related:
related:
- /influxdb/v2.5/reference/api/influxdb-1x/
- /influxdb/v2.5/reference/api/influxdb-1x/query
- /influxdb/v2.5/reference/api/influxdb-1x/dbrp
- /influxdb/v2.5/tools/influxql-shell/
---
Use InfluxQL (an SQL-like query language) to interact with InfluxDB, and query and analyze your times series data.
In InfluxDB 1.x, data is stored in [databases](/{{< latest "influxdb" "v1" >}}/concepts/glossary/#database)
and [retention policies](/{{< latest "influxdb" "v1" >}}/concepts/glossary/#retention-policy-rp).
InfluxDB {{< current-version >}} combines and replaces database and retention
policies with [buckets](/influxdb/v2.5/reference/glossary/#bucket).
Because InfluxQL uses the 1.x data model, a database and retention policy combination
(DBRP) must be mapped to a bucket before it can be queried using InfluxQL.
In InfluxDB OSS {{< current-version >}}, data is stored in [buckets](/influxdb/v2.5/reference/glossary/#bucket).
Because InfluxQL uses the 1.x data model, a bucket must be mapped to a database and retention policy (DBRP) before it can be queried using InfluxQL.
{{% note %}}
#### InfluxQL reference documentation
For complete InfluxQL reference documentation, see
[Influx Query Language in the latest InfluxDB 1.x documentation](/{{< latest "influxdb" "v1" >}}/query_language/).
{{% /note %}}
**To use InfluxQL to query bucket data, complete the following steps:**
**To query data with InfluxQL, complete the following steps:**
1. [Verify buckets have a mapping](#verify-buckets-have-a-mapping).
2. [Create DBRP mappings for unmapped buckets](#create-dbrp-mappings-for-unmapped-buckets).
3. [Query a mapped bucket with InfluxQL](#query-a-mapped-bucket-with-influxql).
{{% note %}}
#### InfluxQL reference documentation
For complete InfluxQL reference documentation, see the
[InfluxQL specification for InfluxDB 2.x](/influxdb/v2.5/reference/syntax/influxql/spec/).
{{% /note %}}
## Verify buckets have a mapping
Use the [`influx` CLI](/influxdb/v2.5/reference/cli/influx/) or the [InfluxDB API](/influxdb/v2.5/reference/api/)
to verify the buckets you want to query are mapped to a database and retention policy.
1. To verify the buckets you want to query are mapped to a database and retention policy, use the [`influx` CLI](/influxdb/v2.5/reference/cli/influx/) or the [InfluxDB API](/influxdb/v2.5/reference/api/).
_For examples, see [List DBRP mappings](/influxdb/v2.5/query-data/influxql/dbrp/#list-dbrp-mappings)._
If you **do not find a DBRP mapping for a bucket**, [create a new DBRP mapping]() to
2. If you **do not find a DBRP mapping for a bucket**, [create a new DBRP mapping](/influxdb/v2.5/query-data/influxql/dbrp/#create-dbrp-mappings) to
map the unmapped bucket.
## Create DBRP mappings for unmapped buckets
Use the [`influx` CLI](/influxdb/v2.5/reference/cli/influx/) or the [InfluxDB API](/influxdb/v2.5/reference/api/)
- Use the [`influx` CLI](/influxdb/v2.5/reference/cli/influx/) or the [InfluxDB API](/influxdb/v2.5/reference/api/)
to manually create DBRP mappings for unmapped buckets.
_For examples, see [Create DBRP mappings](/influxdb/v2.5/query-data/influxql/dbrp/#create-dbrp-mappings)._
@ -54,36 +55,32 @@ _For examples, see [Create DBRP mappings](/influxdb/v2.5/query-data/influxql/dbr
{{< tabs-wrapper >}}
{{% tabs %}}
[InfluxQL Shell](#)
[InfluxQL shell](#)
[InfluxDB API](#)
{{% /tabs %}}
{{% tab-content %}}
<!---------------------------- BEGIN InfluxQL shell --------------------------->
The [`influx` CLI](/influxdb/v2.5/tools/influx-cli/) provides an InfluxQL shell
where you can execute InfluxQL queries in an interactive Read-Eval-Print-Loop (REPL).
The [`influx` CLI](/influxdb/v2.5/reference/cli/influx/) provides an [InfluxQL shell](/influxdb/v2.5/tools/influxql-shell/) where you can execute InfluxQL queries in an interactive Read-Eval-Print-Loop (REPL).
{{% note %}}
If you haven't already, be sure to do the following:
1. If you haven't already, do the following:
- [Download and install the `influx` CLI](/influxdb/v2.5/tools/influx-cli/#install-the-influx-cli)
- [Configure your authentication credentials](/influxdb/v2.5/tools/influx-cli/#provide-required-authentication-credentials)
{{% /note %}}
- [Download and install the `influx` CLI](/influxdb/v2.5/tools/influx-cli/#install-the-influx-cli)
- [Configure your authentication credentials](/influxdb/v2.5/tools/influx-cli/#provide-required-authentication-credentials)
Use the following command to start an InfluxQL shell:
2. Use the following command to start an InfluxQL shell:
```sh
influx v1 shell
```
```sh
influx v1 shell
```
Execute an InfluxQL query inside the InfluxQL shell.
3. Execute an InfluxQL query inside the InfluxQL shell.
```sql
> SELECT used_percent FROM example-db.example-rp.example-measurement WHERE host=host1
```
```sql
SELECT used_percent FROM example-db.example-rp.example-measurement WHERE host=host1
```
For more information about using the InfluxQL shell, see
[Use the InfluxQL shell](/influxdb/v2.5/tools/influxql-shell/).
For more information, see how to [use the InfluxQL shell](/influxdb/v2.5/tools/influxql-shell/). For more information about DBRP mappings, see [Manage DBRP mappings](/influxdb/v2.5/query-data/influxql/dbrp/).
<!----------------------------- END InfluxQL shell ---------------------------->
{{% /tab-content %}}
@ -93,37 +90,36 @@ For more information about using the InfluxQL shell, see
The [InfluxDB 1.x compatibility API](/influxdb/v2.5/reference/api/influxdb-1x/) supports
all InfluxDB 1.x client libraries and integrations in InfluxDB {{< current-version >}}.
To query a mapped bucket with InfluxQL, use the [`/query` 1.x compatibility endpoint](/influxdb/v2.5/reference/api/influxdb-1x/query/).
Include the following in your request:
1. To query a mapped bucket with InfluxQL, use the [`/query` 1.x compatibility endpoint](/influxdb/v2.5/reference/api/influxdb-1x/query/), and include the following in your request:
- **Request method:** `GET`
- **Headers:**
- **Request method:** `GET`
- **Headers:**
- **Authorization:** _See [compatibility API authentication](/influxdb/v2.5/reference/api/influxdb-1x/#authentication)_
- **Query parameters:**
- **Query parameters:**
- **db**: 1.x database to query
- **rp**: 1.x retention policy to query _(if no retention policy is specified, InfluxDB uses the default retention policy for the specified database)_
- **q**: URL-encoded InfluxQL query
{{% api/url-encode-note %}}
{{% api/url-encode-note %}}
```sh
curl --get http://localhost:8086/query?db=example-db \
```sh
curl --get http://localhost:8086/query?db=example-db \
--header "Authorization: Token YourAuthToken" \
--data-urlencode "q=SELECT used_percent FROM example-db.example-rp.example-measurement WHERE host=host1"
```
```
By default, the `/query` compatibility endpoint returns results in **JSON**.
To return results as **CSV**, include the `Accept: application/csv` header.
By default, the `/query` compatibility endpoint returns results in **JSON**.
2. (Optional) To return results as **CSV**, include the `Accept: application/csv` header.
For more information about DBRP mappings, see [Manage DBRP mappings](/influxdb/v2.5/query-data/influxql/dbrp/).
<!------------------------------ END InfluxDB API ----------------------------->
{{% /tab-content %}}
{{< /tabs-wrapper >}}
## InfluxQL support
InfluxDB {{< current-version >}} supports InfluxQL queries.
See supported and unsupported queries below.
To learn more about InfluxQL, see [Influx Query Language (InfluxQL)](/{{< latest "influxdb" "v1" >}}/query_language/).
InfluxDB OSS 2.x supports the following InfluxQL statements and clauses. See supported and unsupported queries below.
{{< flex >}}
{{< flex-content >}}
@ -135,10 +131,13 @@ To learn more about InfluxQL, see [Influx Query Language (InfluxQL)](/{{< latest
- `EXPLAIN ANALYZE`
- `SELECT` _(read-only)_
- `SHOW DATABASES`
- `SHOW SERIES`
- `SHOW MEASUREMENTS`
- `SHOW TAG KEYS`
- `SHOW TAG VALUES`
- `SHOW FIELD KEYS`
- `SHOW SERIES EXACT CARDINALITY`
- `SHOW TAG KEY CARDINALITY`
- `SHOW FIELD KEY CARDINALITY`
\* These commands delete data.
{{% /note %}}
@ -155,6 +154,7 @@ To learn more about InfluxQL, see [Influx Query Language (InfluxQL)](/{{< latest
- `GRANT`
- `KILL`
- `REVOKE`
- `SHOW SERIES CARDINALITY`
{{% /warn %}}
{{< /flex-content >}}
{{< /flex >}}

View File

@ -7,14 +7,14 @@ description: >
menu:
influxdb_2_5:
parent: Query with InfluxQL
weight: 202
weight: 201
influxdb/v2.5/tags: [influxql, dbrp]
---
InfluxQL requires a database and retention policy (DBRP) combination to query data from.
InfluxQL requires a database and retention policy (DBRP) combination in order to query data.
In InfluxDB {{< current-version >}}, databases and retention policies have been
combined and replaced by InfluxDB [buckets](/influxdb/v2.5/reference/glossary/#bucket).
To query an InfluxDB {{< current-version >}} with InfluxQL, the specified DBRP
To query InfluxDB {{< current-version >}} with InfluxQL, the specified DBRP
combination must be mapped to a bucket.
- [Automatic DBRP mapping](#automatic-dbrp-mapping)

View File

@ -0,0 +1,73 @@
---
title: Explore data using InfluxQL
description: >
Explore time series data using InfluxQL, InfluxData's SQL-like query language.
Use the `SELECT` statement to query data from measurements, tags, and fields.
menu:
influxdb_2_5:
name: Explore data
parent: Query with InfluxQL
weight: 202
---
To start exploring data with InfluxQL, do the following:
1. Verify your bucket has a database and retention policy (DBRP) mapping by [listing DBRP mappings for your bucket](/influxdb/v2.5/query-data/influxql/dbrp/#list-dbrp-mappings). If not, [create a new DBRP mapping](/influxdb/v2.5/query-data/influxql/dbrp/#create-dbrp-mappings).
2. [Configure timestamps in the InfluxQL shell](/influxdb/v2.5/query-data/influxql/explore-data/time-and-timezone/).
3. _(Optional)_ If you would like to use the data used in the examples below, [download the NOAA sample data](#download-sample-data).
4. Use the InfluxQL `SELECT` statement with other key clauses to explore your data.
{{< children type="anchored-list" >}}
{{< children readmore=true hr=true >}}
## Download sample data
The example InfluxQL queries in this documentation use publicly available [National Oceanic and Atmospheric Administration (NOAA)](https://www.noaa.gov/) data.
To download a subset of NOAA data used in examples, run the script under [NOAA water sample data](/influxdb/v2.5/reference/sample-data/#noaa-water-sample-data) (for example, copy and paste the script into your Data Explorer - Script Editor), and replace "example-org" in the script with the name of your InfluxDB organization.
Let's get acquainted with this subsample of the data in the `h2o_feet` measurement:
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
|time | level description | location | water_level |
| :------------------- | :------------------ | :----------------------- |----------------------:|
| 2019-08-18T00:00:00Z | between 6 and 9 feet |coyote_creek | 8.1200000000 |
| 2019-08-18T00:00:00Z | below 3 feet | santa_monica | 2.0640000000 |
| 2019-08-18T00:06:00Z | between 6 and 9 feet | coyote_creek | 8.0050000000 |
| 2019-08-18T00:06:00Z | below 3 feet| santa_monica | 2.1160000000 |
| 2019-08-18T00:12:00Z | between 6 and 9 feet| coyote_creek | 7.8870000000 |
| 2019-08-18T00:12:00Z | below 3 feet | santa_monica | 2.0280000000 |
The data in the `h2o_feet` [measurement](/influxdb/v2.5/reference/glossary/#measurement)
occurs at six-minute time intervals.
This measurement has one [tag key](/influxdb/v2.5/reference/glossary/#tag-key)
(`location`) which has two [tag values](/influxdb/v2.5/reference/glossary/#tag-value):
`coyote_creek` and `santa_monica`.
The measurement also has two [fields](/influxdb/v2.5/reference/glossary/#field):
`level description` stores string [field values](/influxdb/v2.5/reference/glossary/#field-value)
and `water_level` stores float field values.
### Configure timestamps in the InfluxQL shell
By default, the [InfluxQL shell](/influxdb/v2.5/tools/influxql-shell/) returns timestamps in
nanosecond UNIX epoch format by default.
To return human-readable RFC3339 timestamps instead of Unix nanosecond timestamps,
use the [precision helper command](/influxdb/v2.5/tools/influxql-shell/#precision) ` to configure
the timestamp format:
```sql
precision rfc3339
```
The [InfluxDB API](/influxdb/v2.5/reference/api/influxdb-1x/) returns timestamps
in [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) format by default.
Specify alternative formats with the [`epoch` query string parameter](/influxdb/v2.5/reference/api/influxdb-1x/).

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,241 @@
---
title: LIMIT and SLIMIT clauses
description: >
Use the `LIMIT` and `SLIMIT` clauses to limit the number of [points](/influxdb/v2.5/reference/glossary/#point) and [series](/influxdb/v2.5/reference/glossary/#series) returned in queries.
menu:
influxdb_2_5:
name: LIMIT and SLIMIT clauses
parent: Explore data
weight: 305
list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] LIMIT <N>
```
---
Use `LIMIT` and `SLIMIT` to limit the number of [points](/influxdb/v2.5/reference/glossary/#point) and [series](/influxdb/v2.5/reference/glossary/#series) returned per query.
- [LIMIT clause](#limit-clause)
- [Syntax](#syntax)
- [Examples](#examples)
- [SLIMIT clause](#slimit-clause)
- [Syntax](#syntax-1)
- [Examples](#examples-2)
- [Use LIMIT and SLIMIT together](#use-limit-and-slimit-together)
## LIMIT clause
`LIMIT <N>` returns the first `N` points from the specified [measurement](/influxdb/v2.5/reference/glossary/#measurement).
### Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] LIMIT <N>
```
`N` specifies the number of points to return from the specified measurement . If `N` is greater than the number of points in a measurement, InfluxDB returns all points from the measurement.
{{% note %}}
**IMPORTANT:** The `LIMIT` clause must appear in the order outlined in the syntax above.
{{% /note %}}
### Examples
{{< expand-wrapper >}}
{{% expand "Limit the number of points returned" %}}
```sql
SELECT "water_level","location" FROM "h2o_feet" LIMIT 3
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level | location |
| :-------------- | :-------------------| ------------------:|
| 2019-08-17T00:00:00Z | 8.1200000000 | coyote_creek|
| 2019-08-17T00:00:00Z | 2.0640000000 |santa_monica |
| 2019-08-17T00:06:00Z | 8.0050000000 |coyote_creek |
The query returns the three oldest points, determined by timestamp, from the `h2o_feet` [measurement](/influxdb/v2.5/reference/glossary/#measurement).
{{% /expand %}}
{{% expand "Limit the number of points returned and include a `GROUP BY` clause" %}}
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:42:00Z' GROUP BY *,time(12m) LIMIT 2
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | :-------------------------- |
| 2019-08-18T00:00:00Z | 8.4615000000 |
| 2019-08-18T00:12:00Z | 8.2725000000 |
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=santa_monica
{{% /influxql/table-meta %}}
| time | mean |
| :------------------- | :-------------------------- |
| 2019-08-18T00:00:00Z | 2.3655000000 |
| 2019-08-18T00:12:00Z | 2.3360000000 |
This query uses the InfluxQL [MEAN() function](/influxdb/v2.5/query-data/influxql/functions/aggregates/#mean) and a `GROUP BY` clause to calculate the average `water_level` for each [tag](/influxdb/v2.5/reference/glossary/#tag) and for each 12-minute interval in the queried time range. `LIMIT 2` requests the two oldest 12-minute averages (determined by timestamp).
Note that without `LIMIT 2`, the query would return four points per series; one for each 12-minute interval in the queried time range.
{{% /expand %}}
{{< /expand-wrapper >}}
## SLIMIT clause
`SLIMIT <N>` returns every [point](/influxdb/v2.5/reference/glossary/#point) from `N` [series](//influxdb/v2.5/reference/glossary/#series) in the specified [measurement](/influxdb/v2.5/reference/glossary/#measurement).
### Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] GROUP BY *[,time(<time_interval>)] [ORDER_BY_clause] SLIMIT <N>
```
`N` specifies the number of series to return from the specified measurement. If `N` is greater than the number of series in a measurement, InfluxDB returns all series from that measurement.
`SLIMIT` queries must include `GROUP BY *`. Note that the `SLIMIT` clause must appear in the order outlined in the syntax above.
### Examples
{{< expand-wrapper >}}
{{% expand "Limit the number of series returned" %}}
```sql
SELECT "water_level" FROM "h2o_feet" GROUP BY * SLIMIT 1
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------ | ---------------------:|
| 2019-08-17T00:00:00Z | 8.1200000000|
| 2019-08-17T00:06:00Z | 8.0050000000|
| 2019-08-17T00:12:00Z | 7.8870000000|
| 2019-08-17T00:18:00Z | 7.7620000000|
| 2019-08-17T00:24:00Z | 7.6350000000|
| 2019-08-17T00:30:00Z | 7.5000000000|
| 2019-08-17T00:36:00Z | 7.3720000000|
The results above include only the first few rows, as the data set is quite large. The query returns all `water_level` [points](/influxdb/v2.5/reference/glossary/#point) from one of the [series](/influxdb/v2.5/reference/glossary/#series) associated with the `h2o_feet` [measurement](/influxdb/v2.5/reference/glossary/#measurement).
{{% /expand %}}
{{% expand "Limit the number of series returned and include a `GROUP BY time()` clause" %}}
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:42:00Z' GROUP BY *,time(12m) SLIMIT 1
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 2019-08-18T00:00:00Z | 8.4615000000|
| 2019-08-18T00:12:00Z | 8.2725000000|
| 2019-08-18T00:24:00Z | 8.0710000000|
| 2019-08-18T00:36:00Z | 7.8330000000|
The query uses the InfluxQL [MEAN() function](/influxdb/v2.5/query-data/influxql/functions/aggregates/#mean)
and a time interval in the [GROUP BY clause](/influxdb/v2.5/query-data/influxql/explore-data/group-by/)
to calculate the average `water_level` for each 12-minute
interval in the queried time range.
`SLIMIT 1` requests a single series associated with the `h2o_feet` measurement.
Note that without `SLIMIT 1`, the query would return results for the two series
associated with the `h2o_feet` measurement: `location=coyote_creek` and
`location=santa_monica`.
{{% /expand %}}
{{< /expand-wrapper >}}
## Use LIMIT and SLIMIT together
`LIMIT <N>` followed by `SLIMIT <2>` returns the first `N1` [points](/influxdb/v2.5/reference/glossary/#point) from `N2` series in the specified measurement.
### Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] GROUP BY *[,time(<time_interval>)] [ORDER_BY_clause] LIMIT <N1> SLIMIT <N2>
```
`N1` specifies the number of points to return per measurement. If `N1` is greater than the number of points in a measurement, InfluxDB returns all points from that measurement.
`N2` specifies the number of series to return from the specified measurement. If `N2` is greater than the number of series in a measurement, InfluxDB returns all series from that measurement.
`SLIMIT` queries must include `GROUP BY *`. Note that the `SLIMIT` clause must appear in the order outlined in the syntax above.
### Examples
{{< expand-wrapper >}}
{{% expand "Limit the number of points and series returned" %}}
```sql
SELECT "water_level" FROM "h2o_feet" GROUP BY * LIMIT 3 SLIMIT 1
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
Tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------ | ---------------------:|
| 2019-08-17T00:00:00Z | 8.1200000000|
| 2019-08-17T00:06:00Z | 8.0050000000|
| 2019-08-17T00:12:00Z | 7.8870000000|
The query returns the three oldest points, determined by timestamp, from one of the series associated with the measurement `h2o_feet`.
{{% /expand %}}
{{% expand "Limit the number of points and series returned and include a `GROUP BY time()` clause" %}}
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:42:00Z' GROUP BY *,time(12m) LIMIT 2 SLIMIT 1
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
Tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 2019-08-18T00:00:00Z | 8.4615000000|
| 2019-08-18T00:12:00Z | 8.2725000000|
The query uses the InfluxQL function MEAN() and a time interval in the GROUP BY clause to calculate the average `water_level` for each 12-minute interval in the queried time range. `LIMIT 2` requests the two oldest 12-minute averages (determined by
timestamp) and `SLIMIT 1` requests a single series associated with the `h2o_feet` measurement.
Note that without `LIMIT 2 SLIMIT 1`, the query would return four points for each of the two series associated with the `h2o_feet` measurement.
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -0,0 +1,206 @@
---
title: OFFSET and SOFFSET clauses
description: >
Use the `OFFSET` and `SOFFSET` clauses to paginate [points](/influxdb/v2.5/reference/glossary/#point) and [series](/influxdb/v2.5/reference/glossary/#series).
menu:
influxdb_2_5:
name: OFFSET and SOFFSET clauses
parent: Explore data
weight: 306
list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] LIMIT_clause OFFSET <N> [SLIMIT_clause]
```
---
Use `OFFSET` and `SOFFSET` to paginate [points](/influxdb/v2.5/reference/glossary/#point) and [series](/influxdb/v2.5/reference/glossary/#series) returned.
- [OFFSET clause](#offset-clause)
- [Syntax](#syntax)
- [Examples](#examples)
- [The SOFFSET clause](#soffset-clause)
- [Syntax](#syntax-1)
- [Examples](#examples-1)
## `OFFSET` clause
`OFFSET <N>` paginates `N` [points](/influxdb/v2.5/reference/glossary/#point) in the query results.
### Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] LIMIT_clause OFFSET <N> [SLIMIT_clause]
```
`N` specifies the number of points to paginate. The `OFFSET` clause requires a [`LIMIT` clause](/influxdb/v2.5/query-data/influxql/explore-data/limit-and-slimit/#limit-clause).
{{% note %}}
**Note:** InfluxDB returns no results if the `WHERE clause` includes a time range and the `OFFSET clause` would cause InfluxDB to return points with timestamps outside of that time range.
{{% /note %}}
### Examples
{{< expand-wrapper >}}
{{% expand "Paginate points" %}}
```sql
SELECT "water_level","location" FROM "h2o_feet" LIMIT 3 OFFSET 3
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level | location |
| :-------------- | -------------------:| :------------------|
| 2019-08-17T00:06:00Z | 2.1160000000 | santa_monica|
| 2019-08-17T00:12:00Z | 7.8870000000 | coyote_creek|
| 2019-08-17T00:12:00Z | 2.0280000000 | santa_monica|
The query returns the fourth, fifth, and sixth points from the `h2o_feet` [measurement](/influxdb/v2.5/reference/glossary/#measurement). If the query did not include `OFFSET 3`, it would return the first, second,
and third points from that measurement.
{{% /expand %}}
{{% expand "Paginate points and include several clauses" %}}
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:42:00Z' GROUP BY *,time(12m) ORDER BY time DESC LIMIT 2 OFFSET 2 SLIMIT 1
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 2019-08-18T00:12:00Z | 8.2725000000 |
| 2019-08-18T00:00:00Z | 8.4615000000 |
In this example:
- The [`SELECT clause`](/influxdb/v2.5/query-data/influxql/explore-data/select/) specifies the InfluxQL [MEAN() function](/influxdb/v2.5/query-data/influxql/functions/aggregates/#mean).
- The [`FROM clause`] (/influxdb/v2.5/query-data/influxql/explore-data/select/#from-clause) specifies a single measurement.
- The [`WHERE` clause](/influxdb/v2.5/query-data/influxql/explore-data/where/) specifies the time range for the query.
- The [`GROUP BY` clause](/influxdb/v2.5/query-data/influxql/explore-data/group-by/) groups results by all tags (`*`) and into 12-minute intervals.
- The [`ORDER BY time DESC` clause](/influxdb/v2.5/query-data/influxql/explore-data/order-by/#order-by-time-desc) returns results in descending timestamp order.
- The [`LIMIT 2` clause](/influxdb/v2.5/query-data/influxql/explore-data/limit-and-slimit/) limits the number of points returned to two.
- The `OFFSET 2` clause excludes the first two averages from the query results.
- The [`SLIMIT 1` clause](/influxdb/v2.5/query-data/influxql/explore-data/limit-and-slimit/) limits the number of series returned to one.
Without `OFFSET 2`, the query would return the first two averages of the query results:
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 2019-08-18T00:36:00Z | 7.8330000000 |
| 2019-08-18T00:24:00Z | 8.0710000000 |
{{< /expand >}}
{{< /expand-wrapper >}}
## `SOFFSET` clause
`SOFFSET <N>` paginates `N` [series](/influxdb/v2.5/reference/glossary/#series) in the query results.
### Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] GROUP BY *[,time(time_interval)] [ORDER_BY_clause] [LIMIT_clause] [OFFSET_clause] SLIMIT_clause SOFFSET <N>
```
`N` specifies the number of [series](/influxdb/v2.5/reference/glossary/#series) to paginate.
The `SOFFSET` clause requires an [`SLIMIT` clause](/influxdb/v2.5/query-data/influxql/explore-data/limit-and-slimit/.
Using the `SOFFSET` clause without an `SLIMIT` clause can cause [inconsistent
query results](https://github.com/influxdata/influxdb/issues/7578).
`SLIMIT` queries must include `GROUP BY *`.
{{% note %}}
**Note:** InfluxDB returns no results if the `SOFFSET` clause paginates through more than the total number of series.
{{% /note %}}
### Examples
{{% expand-wrapper %}}
{{% expand "Paginate series" %}}
#### Paginate series
```sql
SELECT "water_level" FROM "h2o_feet" GROUP BY * SLIMIT 1 SOFFSET 1
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=santa_monica
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------ | ---------------------:|
| 2019-08-17T00:00:00Z | 2.0640000000|
| 2019-08-17T00:06:00Z | 2.1160000000|
| 2019-08-17T00:12:00Z | 2.0280000000|
| 2019-08-17T00:18:00Z | 2.1260000000|
| 2019-08-17T00:24:00Z | 2.0410000000|
| 2019-08-17T00:30:00Z | 2.0510000000|
| 2019-08-17T00:36:00Z | 2.0670000000|
| 2019-08-17T00:42:00Z | 2.0570000000|
The results above are partial, as the data set is quite large. The query returns data for the series associated with the `h2o_feet`
measurement and the `location = santa_monica` tag. Without `SOFFSET 1`, the query returns data for the series associated with the `h2o_feet` measurement and the `location = coyote_creek` tag.
{{% /expand %}}
{{% expand "Paginate points and include several clauses" %}}
#### Paginate series and include all clauses
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:42:00Z' GROUP BY *,time(12m) ORDER BY time DESC LIMIT 2 OFFSET 2 SLIMIT 1 SOFFSET 1
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=santa_monica
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 2019-08-18T00:12:00Z | 2.3360000000|
| 2019-08-18T00:00:00Z | 2.3655000000|
In this example:
- The [`SELECT` clause](/influxdb/v2.5/query-data/influxql/explore-data/select/) specifies an InfluxQL [function](/influxdb/v2.5/query-data/influxql/functions/).
- The [`FROM` clause](/influxdb/v2.5/query-data/influxql/explore-data/select/#from-clause) specifies a single measurement.
- The [`WHERE` clause](/influxdb/v2.5/query-data/influxql/explore-data/where/) specifies the time range for the query.
- The [`GROUP BY` clause](/influxdb/v2.5/query-data/influxql/explore-data/group-by/) groups results by all tags (`*`) and into 12-minute intervals.
- The [`ORDER BY time DESC` clause](/influxdb/v2.5/query-data/influxql/explore-data/order-by/#order-by-time-desc) returns results in descending timestamp order.
- The [`LIMIT 2` clause](/influxdb/v2.5/query-data/influxql/explore-data/limit-and-slimit/) limits the number of points returned to two.
- The [`OFFSET 2` clause](/influxdb/v2.5/query-data/influxql/explore-data/offset-and-soffset/) excludes the first two averages from the query results.
- The [`SLIMIT 1` clause](/influxdb/v2.5/query-data/influxql/explore-data/limit-and-slimit/) limits the number of series returned to one.
- The [`SOFFSET 1`](/influxdb/v2.5/query-data/influxql/explore-data/offset-and-soffset/) clause paginates the series returned.
Without `SOFFSET 1`, the query would return the results for a different series:
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
| time | mean |
| :------------------ | ---------------------:|
| 2019-08-18T00:12:00Z | 8.2725000000 |
| 2019-08-18T00:00:00Z | 8.4615000000 |
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -0,0 +1,119 @@
---
title: ORDER BY clause
list_title: ORDER BY clause
description: >
Use the `ORDER BY` clause to sort data in ascending or descending order.
menu:
influxdb_2_5:
name: ORDER BY clause
parent: Explore data
weight: 304
list_code_example: |
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] ORDER BY time DESC
```
---
Use the `ORDER BY` clause to sort data.
- [Syntax](#syntax)
- [Examples](#examples)
## ORDER BY time DESC
By default, InfluxDB returns results in ascending time order; the first [point](/influxdb/v2.5/reference/glossary/#point)
returned has the oldest [timestamp](/influxdb/v2.5/reference/glossary/#timestamp) and
the last point returned has the most recent timestamp.
`ORDER BY time DESC` reverses that order such that InfluxDB returns the points
with the most recent timestamps first.
### Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] ORDER BY time DESC
```
If the query includes a `GROUP BY` clause, `ORDER by time DESC` must appear **after** the `GROUP BY` clause.
If the query includes a `WHERE` clause and no `GROUP BY` clause, `ORDER by time DESC` must appear **after** the `WHERE` clause.
### Examples
{{< expand-wrapper >}}
{{% expand "Return the newest points first" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" = 'santa_monica' ORDER BY time DESC
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :-------------- | ------------------:|
| 2019-09-17T21:42:00Z | 4.9380000000|
| 2019-09-17T21:36:00Z | 5.0660000000|
| 2019-09-17T21:30:00Z | 5.0100000000|
| 2019-09-17T21:24:00Z | 5.0130000000|
| 2019-09-17T21:18:00Z | 5.0720000000|
The query returns the points with the most recent timestamps from the
`h2o_feet` [measurement](/influxdb/v2.5/reference/glossary/#measurement) first.
Without `ORDER by time DESC`, the query would return the following output:
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :-------------- | ------------------:|
| 2019-08-17T00:00:00Z | 2.0640000000|
| 2019-08-17T00:06:00Z | 2.1160000000|
| 2019-08-17T00:12:00Z | 2.0280000000|
| 2019-08-17T00:18:00Z | 2.1260000000|
{{% /expand %}}
{{% expand "Return the newest points first and include a `GROUP BY time()` clause" %}}
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:42:00Z' GROUP BY time(12m) ORDER BY time DESC
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | mean |
| :-------------- | ------------------:|
| 2019-08-18T00:36:00Z | 4.9712860355|
| 2019-08-18T00:24:00Z | 5.1682500000|
| 2019-08-18T00:12:00Z | 5.3042500000|
| 2019-08-18T00:00:00Z | 5.4135000000|
The query uses the InfluxQL [MEAN() function](/influxdb/v2.5/query-data/influxql/functions/aggregates/#mean)
and a time interval in the [GROUP BY clause](/influxdb/v2.5/query-data/influxql/explore-data/group-by/)
to calculate the average `water_level` for each 12-minute
interval in the queried time range.
[`ORDER BY time DESC`](/influxdb/v2.5/query-data/influxql/explore-data/order-by/#order-by-time-desc) returns the most recent 12-minute time intervals
first.
Without `ORDER BY time DESC`, the query would return the following output:
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | mean |
| :-------------- | ------------------:|
| 2019-08-18T00:00:00Z | 5.4135000000|
| 2019-08-18T00:12:00Z | 5.3042500000|
| 2019-08-18T00:24:00Z | 5.1682500000|
| 2019-08-18T00:36:00Z | 4.9712860355|
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -0,0 +1,216 @@
---
title: Regular expressions
list_title: Regular expressions
description: >
Use `regular expressions` to match patterns in your data.
menu:
influxdb_2_5:
name: Regular expressions
identifier: influxql-regular-expressions
parent: Explore data
weight: 313
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>/
```
---
InfluxQL supports using regular expressions when specifying:
- [field keys](/influxdb/v2.5/reference/glossary/#field-key) and [tag keys](/influxdb/v2.5/reference/glossary/#tag-key) in the [`SELECT` clause](/influxdb/v2.5/query-data/influxql/explore-data/select/).
- [measurements](/influxdb/v2.5/reference/glossary/#measurement) in the [`FROM` clause](/influxdb/v2.5/query-data/influxql/explore-data/select/#from-clause).
- [tag values](/influxdb/v2.5/reference/glossary/#tag-value) and string [field values](/influxdb/v2.5/reference/glossary/#field-value) in the [`WHERE` clause](/influxdb/v2.5/query-data/influxql/explore-data/where/).
- [tag keys](/influxdb/v2.5/reference/glossary/#tag-key) in the [`GROUP BY` clause](/influxdb/v2.5/query-data/influxql/explore-data/group-by/)
Regular expressions in InfluxQL only support string comparisons and can only evaluate [fields](/influxdb/v2.5/reference/glossary/#field) with string values.
{{% note %}}
**Note:** Regular expression comparisons are more computationally intensive than exact
string comparisons. Queries with regular expressions are not as performant
as those without.
{{% /note %}}
- [Syntax](#syntax)
- [Examples](#examples)
## Syntax
```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 surrounded by `/` characters and use
[Golang's regular expression syntax](http://golang.org/pkg/regexp/syntax/).
## Supported operators
`=~`: matches against
`!~`: doesn't match against
### Examples
{{< expand-wrapper >}}
{{% expand "Use a regular expression to specify field keys and tag keys in the SELECT clause" %}}
```sql
SELECT /l/ FROM "h2o_feet" LIMIT 1
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level|
| :------------ | :----------------| :--------------| --------------:|
| 2019-08-17T00:00:00Z | below 3 feet | santa_monica | 2.0640000000|
The query selects all field keys and tag keys that include an `l`.
Note that the regular expression in the `SELECT` clause must match at least one
field key in order to return results for a tag key that matches the regular
expression.
Currently, there is no syntax to distinguish between regular expressions for
field keys and regular expressions for tag keys in the `SELECT` clause.
The syntax `/<regular_expression>/::[field | tag]` is not supported.
{{% /expand %}}
{{% expand "Use a regular expression to specify measurements in the FROM clause" %}}
```sql
SELECT MEAN("degrees") FROM /temperature/
```
Output:
{{% influxql/table-meta %}}
Name: average_temperature
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 1970-01-01T00:00:00Z | 79.9847293223 |
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 1970-01-01T00:00:00Z | 64.9980273540 |
This query uses the InfluxQL [MEAN() function](/influxdb/v2.5/query-data/influxql/functions/aggregates/#mean) to calculate the average `degrees` for every [measurement](/influxdb/v2.5/reference/glossary/#measurement) in the [NOAA sample data] that contains the word `temperature`.
{{% /expand %}}
{{% expand "Use a regular expression to specify tag values in the WHERE clause" %}}
```sql
SELECT MEAN(water_level) FROM "h2o_feet" WHERE "location" =~ /[m]/ AND "water_level" > 3
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 1970-01-01T00:00:00Z | 4.4710766395|
This query uses the InfluxQL [MEAN() function](/influxdb/v2.5/query-data/influxql/functions/aggregates/#mean) to calculate the average `water_level` where the [tag value](/influxdb/v2.5/reference/glossary/#measurement) of `location` includes an `m` and `water_level` is greater than three.
{{% /expand %}}
{{% expand "Use a regular expression to specify a tag with no value in the WHERE clause" %}}
```sql
SELECT * FROM "h2o_feet" WHERE "location" !~ /./
>
```
The query selects all data from the `h2o_feet` measurement where the `location`
[tag](/influxdb/v2.5/reference/glossary/#tag) has no value.
Every data [point](/influxdb/v2.5/reference/glossary/#point) in the [NOAA water sample data](/influxdb/v2.5/reference/sample-data/#noaa-water-sample-data) has a tag value for `location`.
It's possible to perform this same query without a regular expression.
See the [Frequently Asked Questions](/influxdb/v2.5/reference/faq/#how-do-i-query-data-by-a-tag-with-a-null-value)
document for more information.
{{% /expand %}}
{{% expand "Use a regular expression to specify a tag with a value in the WHERE clause" %}}
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE "location" =~ /./
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 1970-01-01T00:00:00Z | 4.4418434585|
This query uses the InfluxQL [MEAN() function](/influxdb/v2.5/query-data/influxql/functions/aggregates/#mean) to calculate the average `water_level` across all data with a tag value for `location`.
{{% /expand %}}
{{% expand "Use a regular expression to specify a field value in the WHERE clause" %}}
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE "location" = 'santa_monica' AND "level description" =~ /between/
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ | ---------------------:|
| 1970-01-01T00:00:00Z | 4.4713666916
This query uses the InfluxQL [MEAN() function](/influxdb/v2.5/query-data/influxql/functions/aggregates/#mean)
to calculate the average `water_level` for all data where the field value of `level description` includes the word `between`.
{{% /expand %}}
{{% expand "Use a regular expression to specify tag keys in the GROUP BY clause" %}}
```sql
SELECT FIRST("index") FROM "h2o_quality" GROUP BY /l/
```
Output:
{{% influxql/table-meta %}}
name: h2o_quality
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ |-------------------:|
| 2019-08-17T00:00:00Z | 41.0000000000 |
{{% influxql/table-meta %}}
name: h2o_quality
tags: location=santa_monica
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ |-------------------:|
| 2019-08-17T00:00:00Z | 99.0000000000 |
This query uses the InfluxQL [FIRST() function](/influxdb/v2.5/query-data/influxql/functions/selectors/#first)
to select the first value of `index` for every tag that includes the letter `l`
in its tag key.
{{% /expand %}}
{{< /expand-wrapper >}}

View File

@ -0,0 +1,681 @@
---
title: SELECT statement
list_title: SELECT statement
description: >
Use the `SELECT` statement to query data from a particular [measurement](/influxdb/v2.5/reference/glossary/#measurement) or measurements.
menu:
influxdb_2_5:
name: SELECT statement
parent: Explore data
weight: 301
list_code_example: |
```sql
SELECT <field_key>[,<field_key>,<tag_key>] FROM <measurement_name>[,<measurement_name>]
```
---
Use the `SELECT` statement to query data from a particular [measurement](/influxdb/v2.5/reference/glossary/#measurement) or measurements.
- [Syntax](#syntax)
- [Examples](#examples)
- [Common issues](#common-issues-with-the-select-statement)
- [Regular expressions](#regular-expressions)
- [Data types and cast operations](#data-types-and-cast-operations)
- [Merge behavior](#merge-behavior)
- [Multiple statements](#multiple-statements)
## Syntax
```sql
SELECT <field_key>[,<field_key>,<tag_key>] FROM <measurement_name>[,<measurement_name>]
```
{{% note %}}
**Note:** The `SELECT` statement **requires** a `SELECT` clause and a `FROM` clause.
{{% /note %}}
### `SELECT` clause
The `SELECT` clause supports several formats for specifying data:
- `SELECT *` - Returns all [fields](/influxdb/v2.5/reference/glossary/#field) and [tags](/influxdb/v2.5/reference/glossary/#tag).
- `SELECT "<field_key>"` - Returns a specific field.
- `SELECT "<field_key>","<field_key>"` - Returns more than one field.
- `SELECT "<field_key>","<tag_key>"` - Returns a specific field and tag. The `SELECT` clause must specify at least one field when it includes a tag.
- `SELECT "<field_key>"::field,"<tag_key>"::tag` - Returns a specific field and tag.
The `::[field | tag]` syntax specifies the [identifier's](/influxdb/v2.5/reference/syntax/influxql/spec/#identifiers) type.
Use this syntax to differentiate between field keys and tag keys with the same name.
Other supported features include:
- [Functions](/influxdb/v2.5/query-data/influxql/functions/)
- [Basic cast operations](#data-types-and-cast-operations)
- [Regular expressions](/influxdb/v2.5/query-data/influxql/explore-data/regular-expressions/)
{{% note %}}
**Note:** The SELECT statement cannot include an aggregate function **and** a non-aggregate function, field key, or tag key. For more information, see [error about mixing aggregate and non-aggregate queries](/enterprise_influxdb/v1.9/troubleshooting/errors/#error-parsing-query-mixing-aggregate-and-non-aggregate-queries-is-not-supported).
{{% /note %}}
### `FROM` clause
The `SELECT` clause specifies the measurement to query.
This clause supports several formats for specifying a [measurement(s)](/influxdb/v2.5/reference/glossary/#measurement):
- `FROM <measurement_name>` - Returns data from a measurement.
- `FROM <measurement_name>,<measurement_name>` - Returns data from more than one measurement.
- `FROM <database_name>.<retention_policy_name>.<measurement_name>` - Returns data from a fully qualified measurement.
- `FROM <database_name>..<measurement_name>` - Returns data from a measurement.
#### Quoting
[Identifiers](/influxdb/v2.5/reference/syntax/influxql/spec/#identifiers) **must** be double quoted if they contain characters other than `[A-z,0-9,_]`,
begin with a digit, or are an [InfluxQL keyword](https://github.com/influxdata/influxql/blob/master/README.md#keywords).
While not always necessary, we recommend that you double quote identifiers.
{{% note %}}
**Note:** InfluxQL quoting guidelines differ from [line protocol quoting guidelines](/influxdb/v2.5/reference/syntax/line-protocol/#quotes).
Please review the [rules for single and double-quoting](/influxdb/v2.5/reference/syntax/line-protocol/#quotes) in queries.
{{% /note %}}
### Examples
{{< expand-wrapper >}}
{{% expand "Select all fields and tags from a measurement" %}}
```sql
SELECT * FROM "h2o_feet"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level |
| :-------------- |:----------------------| :-------------------| ------------------:|
| 2019-08-17T00:00:00Z | below 3 feet |santa_monica | 2.0640000000|
| 2019-08-17T00:00:00Z | between 6 and 9 feet | coyote_creek | 8.1200000000|
| 2019-08-17T00:06:00Z | below 3 feet| santa_monica | 2.1160000000|
| 2019- 08-17T00:06:00Z | between 6 and 9 feet |coyote_creek |8.0050000000|
| 2019-08-17T00:12:00Z | below 3 feet | santa_monica | 2.0280000000|
| 2019-08-17T00:12:00Z | between 6 and 9 feet | coyote_creek | 7.8870000000|
| 2019-08-17T00:18:00Z | below 3 feet |santa_monica | 2.1260000000|
The data above is a partial listing of the query output, as the result set is quite large. The query selects all [fields](/influxdb/v2.5/reference/glossary/#field) and
[tags](/influxdb/v2.5/reference/glossary/#tag) from the `h2o_feet`
[measurement](/influxdb/v2.5/reference/glossary/#measurement).
{{% /expand %}}
{{% expand "Select specific tags and fields from a measurement" %}}
```sql
SELECT "level description","location","water_level" FROM "h2o_feet"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level |
| :-------------- |:----------------------| :-------------------| ------------------:|
| 2019-08-17T00:00:00Z | below 3 feet |santa_monica | 2.0640000000|
| 2019-08-17T00:00:00Z | between 6 and 9 feet | coyote_creek | 8.1200000000|
The query selects the `level description` field, the `location` tag, and the
`water_level` field.
{{% note %}}
**Note:** The `SELECT` clause must specify at least one field when it includes
a tag.
{{% /note %}}
{{% /expand %}}
{{% expand "Select specific tags and fields from a measurement and provide their identifier type" %}}
```sql
SELECT "level description"::field,"location"::tag,"water_level"::field FROM "h2o_feet"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level |
| :-------------- |:----------------------| :-------------------| ------------------:|
| 2019-08-17T00:24:00Z | between 6 and 9 feet | coyote_creek | 7.6350000000|
| 2019-08-17T00:30:00Z | below 3 feet | santa_monica | 2.0510000000|
| 2019-08-17T00:30:00Z | between 6 and 9 feet | coyote_creek | 7.5000000000|
| 2019-08-17T00:36:00Z | below 3 feet | santa_monica | 2.0670000000 |
| 2019-08-17T00:36:00Z | between 6 and 9 feet | coyote_creek | 7.3720000000 |
| 2019-08-17T00:42:00Z | below 3 feet | santa_monica | 2.0570000000 |
The query selects the `level description` field, the `location` tag, and the
`water_level` field from the `h2o_feet` measurement.
The `::[field | tag]` syntax specifies if the
[identifier](/influxdb/v2.5/reference/syntax/influxql/spec/#identifiers) is a field or tag.
Use `::[field | tag]` to differentiate between [an identical field key and tag key ](/v2.4/reference/faq/#how-do-i-query-data-with-an-identical-tag-key-and-field-key).
That syntax is not required for most use cases.
{{% /expand %}}
{{% expand "Select all fields from a measurement" %}}
```sql
SELECT *::field FROM "h2o_feet"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description| water_level |
| :-------------- | :-------------------| ------------------:|
| 2019-08-17T00:00:00Z | below 3 feet | 2.0640000000 |
| 2019-08-17T00:00:00Z | between 6 and 9 feet | 8.1200000000|
| 2019-08-17T00:06:00Z | below 3 feet | 2.1160000000|
| 2019-08-17T00:06:00Z | between 6 and 9 feet | 8.0050000000|
| 2019-08-17T00:12:00Z | below 3 feet | 2.0280000000|
| 2019-08-17T00:12:00Z | between 6 and 9 feet | 7.8870000000|
The query selects all fields from the `h2o_feet` measurement.
The `SELECT` clause supports combining the `*` syntax with the `::` syntax.
{{% /expand %}}
{{% expand "Select a specific field from a measurement and perform basic arithmetic" %}}
```sql
SELECT ("water_level" * 2) + 4 FROM "h2o_feet"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :-------------- | ------------------:|
| 2019-08-17T00:00:00Z | 20.2400000000 |
| 2019-08-17T00:00:00Z | 8.1280000000 |
| 2019-08-17T00:06:00Z | 20.0100000000 |
| 2019-08-17T00:06:00Z | 8.2320000000 |
| 2019-08-17T00:12:00Z | 19.7740000000 |
| 2019-08-17T00:12:00Z | 8.0560000000 |
The query multiplies `water_level`'s field values by two and adds four to those
values.
{{% note %}}
**Note:** InfluxDB follows the standard order of operations.
See [InfluxQL mathematical operators](/influxdb/v2.5/query-data/influxql/math-operators/)
for more on supported operators.
{{% /note %}}
{{% /expand %}}
{{% expand "Select all data from more than one measurement" %}}
```sql
SELECT * FROM "h2o_feet","h2o_pH"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | pH | water_level |
| :-------------- |:-------------| :----------------| :-------------| --------------:|
| 2019-08-17T00:00:00Z | below 3 feet | santa_monica | <nil> | 2.0640000000|
| 2019-08-17T00:00:00Z | between 6 and 9 feet | coyote_creek | <nil> | 8.1200000000|
| 2019-08-17T00:06:00Z | below 3 feet | santa_monica | <nil> | 2.1160000000|
| 2019-08-17T00:06:00Z | between 6 and 9 feet | coyote_creek | <nil> | 8.0050000000|
| 2019-08-17T00:12:00Z | below 3 feet | santa_monica | <nil> | 2.0280000000 |
| 2019-08-17T00:12:00Z | between 6 and 9 feet | coyote_creek | <nil> | 7.8870000000|
| 2019-08-17T00:18:00Z | below 3 feet | santa_monica | <nil> | 2.1260000000|
| 2019-08-17T00:18:00Z | between 6 and 9 feet | coyote_creek | <nil> | 7.7620000000|
{{% influxql/table-meta %}}
Name: h2o_pH
{{% /influxql/table-meta %}}
| time | level description | location | pH | water_level |
| :-------------- |:-------------| :----------------| :-------------| --------------:|
| 2019-08-17T00:00:00Z | <nil> | coyote_creek | 7.00| <nil> |
| 2019-08-17T00:06:00Z | <nil> |coyote_creek | 8.00 | <nil> |
| 2019-08-17T00:06:00Z | <nil> |santa_monica | 6.00 | <nil> |
| 2019-08-17T00:12:00Z | <nil> |coyote_creek |8.00 | <nil> |
The query selects all fields and tags from two measurements: `h2o_feet` and
`h2o_pH`.
Separate multiple measurements with a comma (`,`).
{{% /expand %}}
{{% expand "Select all data from a measurement in a particular database" %}}
```sql
SELECT * FROM noaa.."h2o_feet"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level |
| :-------------- |:----------------------| :-------------------| ------------------:|
| 2019-08-17T00:00:00Z | below 3 feet |santa_monica | 2.0640000000|
| 2019-08-17T00:00:00Z | between 6 and 9 feet | coyote_creek | 8.1200000000|
| 2019-08-17T00:06:00Z | below 3 feet| santa_monica | 2.1160000000|
| 2019- 08-17T00:06:00Z | between 6 and 9 feet |coyote_creek |8.0050000000|
| 2019-08-17T00:12:00Z | below 3 feet | santa_monica | 2.0280000000|
| 2019-08-17T00:12:00Z | between 6 and 9 feet | coyote_creek | 7.8870000000|
The query selects data from the `h2o_feet` measurement in the `noaa` database.
The `..` indicates the `DEFAULT` retention policy for the specified database.
{{% /expand %}}
{{< /expand-wrapper >}}
## Common issues with the SELECT statement
### Selecting tag keys in the SELECT statement
A query requires at least one [field key](/influxdb/v2.5/reference/glossary/#field-key)
in the `SELECT` clause to return data.
If the `SELECT` clause only includes a single [tag key](/influxdb/v2.5/reference/glossary/#tag-key) or several tag keys, the
query returns an empty response.
#### Example
The following query returns no data because it specifies a single tag key (`location`) in
the `SELECT` clause:
```sql
SELECT "location" FROM "h2o_feet"
> No results
```
To return any data associated with the `location` tag key, the query's `SELECT`
clause must include at least one field key (`water_level`):
```sql
SELECT "water_level","location" FROM "h2o_feet"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level | location |
| :-------------- | :-------------------| ------------------:|
| 2019-08-17T00:00:00Z | 8.1200000000 | coyote_creek |
| 2019-08-17T00:00:00Z | 2.0640000000 | santa_monica |
| 2019-08-17T 00:06:00Z | 8.0050000000 | coyote_creek |
| 2019-08-17T00:06:00Z | 2.1160000000 | santa_monica |
| 2019-08-17T00:12:00Z | 7.8870000000 | coyote_creek |
| 2019-08-17T00:12:00Z | 2.0280000000 | santa_monica |
| 2019-08-17T00:18:00Z | 7.7620000000 | coyote_creek |
| 2019-08-17T00:18:00Z | 2.1260000000 | santa_monica |
## Regular expressions
InfluxQL supports using regular expressions when specifying:
- [field keys](/influxdb/v2.5/reference/glossary/#field-key) and [tag keys](/influxdb/v2.5/reference/glossary/#tag-key) in the [`SELECT` clause](/influxdb/v2.5/query-data/influxql/explore-data/select/)
- [measurements](/influxdb/v2.5/reference/glossary/#measurement) in the [`FROM` clause](/influxdb/v2.5/query-data/influxql/explore-data/select/#from-clause)
- [tag values](/influxdb/v2.5/reference/glossary/#tag-value) and string [field values](/influxdb/v2.5/reference/glossary/#field-value) in the [`WHERE` clause](/influxdb/v2.5/query-data/influxql/explore-data/where/).
- [tag keys](/influxdb/v2.5/reference/glossary/#tag-key) in the [`GROUP BY` clause](/influxdb/v2.5/query-data/influxql/explore-data/group-by/)
Currently, InfluxQL does not support using regular expressions to match
non-string field values in the
`WHERE` clause,
[databases](/influxdb/v2.5/reference/glossary/#database), and
[retention policies](/influxdb/v2.5/reference/glossary/#retention-policy-rp).
{{% note %}}
**Note:** Regular expression comparisons are more computationally intensive than exact
string comparisons. Queries with regular expressions are not as performant
as those without.
{{% /note %}}
## Syntax
```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 surrounded by `/` characters and use
[Golang's regular expression syntax](http://golang.org/pkg/regexp/syntax/).
## Supported operators
`=~`: matches against
`!~`: doesn't match against
## Examples
{{< expand-wrapper >}}
{{% expand "Use a regular expression to specify field keys and tag keys in the SELECT statement" %}}
#### Use a regular expression to specify field keys and tag keys in the SELECT statement
```sql
SELECT /l/ FROM "h2o_feet" LIMIT 1
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level |
| :-------------- |:----------------------| :-------------------| ------------------:|
| 2019-08-17T00:00:00Z | below 3 feet | santa_monica | 2.0640000000 |
The query selects all [field keys](/influxdb/v2.5/reference/glossary/#field-key)
and [tag keys](/influxdb/v2.5/reference/glossary/#tag-key) that include an `l`.
Note that the regular expression in the `SELECT` clause must match at least one
field key in order to return results for a tag key that matches the regular
expression.
Currently, there is no syntax to distinguish between regular expressions for
field keys and regular expressions for tag keys in the `SELECT` clause.
The syntax `/<regular_expression>/::[field | tag]` is not supported.
{{% /expand %}}
{{% expand "Use a regular expression to specify measurements in the FROM clause" %}}
```sql
SELECT MEAN("degrees") FROM /temperature/
```
Output:
{{% influxql/table-meta %}}
Name: average_temperature
{{% /influxql/table-meta %}}
| time | mean|
| :-------------- |----------------------:|
| 1970-01-01T00:00:00Z | 79.9847293223
{{% influxql/table-meta %}}
Name: h2o_temperature
{{% /influxql/table-meta %}}
| time | mean|
| :-------------- |----------------------:|
| 1970-01-01T00:00:00Z | 64.9980273540 |
This query uses the InfluxQL [MEAN() function](/influxdb/v2.5/query-data/influxql/functions/aggregates/#mean) to calculate the average `degrees` for every [measurement](/influxdb/v2.5/reference/glossary/#measurement) in the `noaa` database that contains the word `temperature`.
{{% /expand %}}
{{< /expand-wrapper >}}
## Data types and cast operations
The [`SELECT` clause](#select-clause) supports specifying a [field's](/influxdb/v2.5/reference/glossary/#field) type and basic cast operations with the `::` syntax.
- [Data types](#data-types)
- [Cast operations](#cast-operations)
### Data types
[Field values](/influxdb/v2.5/reference/glossary/#field-value) can be floats, integers, strings, or booleans.
The `::` syntax allows users to specify the field's type in a query.
{{% note %}}
**Note:** Generally, it is not necessary to specify the field value type in the [`SELECT` clause](/influxdb/v2.5/query-data/influxql/explore-data/select/). In most cases, InfluxDB rejects any writes that attempt to write a [field value](/influxdb/v2.5/reference/glossary/#field-value) to a field that previously accepted field values of a different type.
{{% /note %}}
It is possible for field value types to differ across [shard groups](/influxdb/v2.5/reference/glossary/#shard-group).
In these cases, it may be necessary to specify the field value type in the
`SELECT` clause.
Please see the
[Frequently Asked Questions](/influxdb/v2.5/reference/faq/#how-does-influxdb-handle-field-type-discrepancies-across-shards)
document for more information on how InfluxDB handles field value type discrepancies.
### Syntax
```sql
SELECT_clause <field_key>::<type> FROM_clause
```
`type` can be `float`, `integer`, `string`, or `boolean`.
In most cases, InfluxDB returns no data if the `field_key` does not store data of the specified
`type`. See [Cast Operations](#cast-operations) for more information.
### Example
```sql
SELECT "water_level"::float FROM "h2o_feet" LIMIT 4
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
|time | water_level |
| :------------------ |-------------------:|
| 2019-08-17T00:00:00Z | 8.1200000000 |
| 2019-08-17T00:00:00Z | 2.0640000000 |
| 2019-08-17T00:06:00Z | 8.0050000000 |
| 2019-08-17T00:06:00Z | 2.1160000000 |
The query returns values of the `water_level` field key that are floats.
## Cast operations
The `::` syntax allows users to perform basic cast operations in queries.
Currently, InfluxDB supports casting [field values](/influxdb/v2.5/reference/glossary/#field-value) from integers to
floats or from floats to integers.
### Syntax
```sql
SELECT_clause <field_key>::<type> FROM_clause
```
`type` can be `float` or `integer`.
InfluxDB returns no data if the query attempts to cast an integer or float to a string or boolean.
### Examples
{{< expand-wrapper >}}
{{% expand "Cast float field values to integers" %}}
```sql
SELECT "water_level"::integer FROM "h2o_feet" LIMIT 4
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
|time | water_level |
| :------------------ |-------------------:|
| 2019-08-17T00:00:00Z | 8.0000000000 |
| 2019-08-17T00:00:00Z | 2.0000000000 |
| 2019-08-17T00:06:00Z | 8.0000000000 |
| 2019-08-17T00:06:00Z | 2.0000000000 |
The query returns the integer form of `water_level`'s float [field values](/influxdb/v2.5/reference/glossary/#field-value).
{{% /expand %}}
{{% expand "Cast float field values to strings (this functionality is not supported)" %}}
```sql
SELECT "water_level"::string FROM "h2o_feet" LIMIT 4
> No results
```
The query returns no data as casting a float field value to a string is not yet supported.
{{% /expand %}}
{{< /expand-wrapper >}}
## Merge behavior
InfluxQL merges [series](/influxdb/v2.5/reference/glossary/#series) automatically.
### Example
{{< expand-wrapper >}}
{{% expand "Merge behavior" %}}
The `h2o_feet` [measurement](/influxdb/v2.5/reference/glossary/#measurement) in the `noaa` is part of two [series](/influxdb/v2.5/reference/glossary/#series).
The first series is made up of the `h2o_feet` measurement and the `location = coyote_creek` [tag](/influxdb/v2.5/reference/glossary/#tag). The second series is made of up the `h2o_feet` measurement and the `location = santa_monica` tag.
The following query automatically merges those two series when it calculates the average `water_level` using the [MEAN() function](/influxdb/v2.5/query-data/influxql/functions/aggregates/#mean):
```sql
SELECT MEAN("water_level") FROM "h2o_feet"
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
|time | mean |
| :------------------ |-------------------:|
| 1970-01-01T00:00:00Z | 4.4419314021 |
If you want the average `water_level` for the first series only, specify the relevant tag in the [`WHERE` clause](/influxdb/v2.5/query-data/influxql/explore-data/where/):
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE "location" = 'coyote_creek'
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
|time | mean |
| :------------------ |-------------------:|
| 1970-01-01T00:00:00Z | 5.3591424203 |
If you want the average `water_level` for each individual series, include a [`GROUP BY` clause](/influxdb/v2.5/query-data/influxql/explore-data/group-by/):
```sql
SELECT MEAN("water_level") FROM "h2o_feet" GROUP BY "location"
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ |-------------------:|
| 1970-01-01T00:00:00Z | 5.3591424203 |
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=santa_monica
{{% /influxql/table-meta %}}
| time | mean |
| :------------------ |-------------------:|
| 1970-01-01T00:00:00Z | 3.5307120942 |
{{% /expand %}}
{{< /expand-wrapper >}}
## Multiple statements
Separate multiple `SELECT` statements in a query with a semicolon (`;`).
### Examples
{{< tabs-wrapper >}}
{{% tabs %}}
[InfluxQL shell](#)
[InfluxDB API](#)
{{% /tabs %}}
{{% tab-content %}}
In the [InfluxQL shell](/influxdb/v2.5/tools/influxql-shell/):
```sql
SELECT MEAN("water_level") FROM "h2o_feet"; SELECT "water_level" FROM "h2o_feet" LIMIT 2
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
|time | mean |
| :------------------ |-------------------:|
| 1970-01-01T00:00:00Z | 4.4419314021 |
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
|time | water_level |
| :------------------ |-------------------:|
| 2019-08-17T00:00:00Z | 8.12 |
| 2015-08-18T00:00:00Z | 2.064 |
{{% /tab-content %}}
{{% tab-content %}}
With the [InfluxDB API](/influxdb/v2.5/reference/api/influxdb-1x/):
```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
]
]
}
]
}
]
}
```
{{% /tab-content %}}
{{< /tabs-wrapper >}}

View File

@ -0,0 +1,294 @@
---
title: Subqueries
description: >
Use a `subquery` to apply a query as a condition in the enclosing query.
menu:
influxdb_2_5:
name: Subqueries
parent: Explore data
weight: 310
list_code_example: |
```sql
SELECT_clause FROM ( SELECT_statement ) [...]
```
---
A subquery is a query that is nested in the `FROM` clause of another query. Use a subquery to apply a query as a condition in the enclosing query. Subqueries offer functionality similar to nested functions and the SQL [`HAVING` clause](https://en.wikipedia.org/wiki/Having_%28SQL%29).
{{% note %}}
**Note:** InfluxQL does not support a `HAVING` clause.
{{% /note %}}
- [Syntax](#syntax)
- [Examples](#examples)
- [Common Issues](#common-issues-with-subqueries)
### Syntax
```sql
SELECT_clause FROM ( SELECT_statement ) [...]
```
InfluxDB **performs the subquery first** and the main query second.
The main query surrounds the subquery and requires at least the [`SELECT` clause](/influxdb//v2.4/query-data/influxql/explore-data/select/) and the [`FROM` clause](/influxdb/v2.5/query-data/influxql/explore-data/select/#from-clause).
The main query supports all clauses listed in InfluxQL 2.x documentation.
The subquery appears in the main query's `FROM` clause, and it requires surrounding parentheses.
The subquery also supports all clauses listed in InfluxQL 2.x documentation.
InfluxQL supports multiple nested subqueries per main query.
Sample syntax for multiple subqueries:
```sql
SELECT_clause FROM ( SELECT_clause FROM ( SELECT_statement ) [...] ) [...]
```
{{% note %}}
**Note:** #### Improve performance of time-bound subqueries
To improve the performance of InfluxQL queries with time-bound subqueries,
apply the `WHERE time` clause to the outer query instead of the inner query.
For example, the following queries return the same results, but **the query with
time bounds on the outer query is more performant than the query with time
bounds on the inner query**:
##### Time bounds on the outer query (recommended)
```sql
SELECT inner_value AS value FROM (SELECT raw_value as inner_value)
WHERE time >= '2022-07-19T21:00:00Z'
AND time <= '2022-07-20T22:00:00Z'
```
##### Time bounds on the inner query
```sql
SELECT inner_value AS value FROM (
SELECT raw_value as inner_value
WHERE time >= '2022-07-19T21:00:00Z'
AND time <= '2022-07-20T22:00:00Z'
)
```
{{% /note %}}
### Examples
{{< expand-wrapper >}}
{{% expand "Calculate the SUM() of several MAX() values" %}}
```sql
SELECT SUM("max") FROM (SELECT MAX("water_level") FROM "h2o_feet" GROUP BY "location")
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | sum |
| :--------------| ------------------:|
|1970-01-01T00:00:00Z | 17.169 |
The query returns the sum of the maximum `water_level` values across every tag value of `location`.
InfluxDB first performs the subquery; it calculates the maximum value of `water_level` for each tag value of `location`:
```sql
SELECT MAX("water_level") FROM "h2o_feet" GROUP BY "location"
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | max |
| :--------------------------- | ------------------: |
| 2015-08-29T07:24:00Z | 9.9640000000 |
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=santa_monica
{{% /influxql/table-meta %}}
| time | max |
| :--------------------------- | ------------------: |
| 2015-08-29T03:54:00Z | 7.2050000000 |
Next, InfluxDB performs the main query and calculates the sum of those maximum values: `9.9640000000` + `7.2050000000` = `17.169`.
Notice that the main query specifies `max`, not `water_level`, as the field key in the `SUM()` function.
{{% /expand %}}
{{% expand "Calculate the MEAN() difference between two fields" %}}
```sql
SELECT MEAN("difference") FROM (SELECT "cats" - "dogs" AS "difference" FROM "pet_daycare")
```
Output:
{{% influxql/table-meta %}}
Name: pet_daycare
{{% /influxql/table-meta %}}
| time | max |
| :--------------------------- | ------------------: |
| 1970-01-01T00:00:00Z | 1.75 |
The query returns the average of the differences between the number of `cats` and `dogs` in the `pet_daycare` measurement.
InfluxDB first performs the subquery.
The subquery calculates the difference between the values in the `cats` field and the values in the `dogs` field,
and it names the output column `difference`:
```sql
SELECT "cats" - "dogs" AS "difference" FROM "pet_daycare"
```
Output:
{{% influxql/table-meta %}}
Name: pet_daycare
{{% /influxql/table-meta %}}
| time | difference |
| :--------------------------- | ------------------: |
| 2017-01-20T00:55:56Z | -1 |
2017-01-21T00:55:56Z | -49 |
2017-01-22T00:55:56Z | 66 |
2017-01-23T00:55:56Z | -9 |
Next, InfluxDB performs the main query and calculates the average of those differences.
Notice that the main query specifies `difference` as the field key in the [`MEAN()`](/influxdb/v2.5/query-data/influxql/functions/aggregates/#mean) function.
{{% /expand %}}
{{% expand "Calculate several MEAN() values and place a condition on those mean values" %}}
```sql
SELECT "all_the_means" FROM (SELECT MEAN("water_level") AS "all_the_means" FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:30:00Z' GROUP BY time(12m) ) WHERE "all_the_means" > 5
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | all_the_means |
| :--------------------------- | ------------------: |
| 2019-08-18T00:00:00Z | 5.4135000000 |
| 2019-08-18T00:12:00Z | 5.3042500000 |
| 2019-08-18T00:24:00Z | 5.1682500000 |
The query returns all mean values of the `water_level` field that are greater than five.
InfluxDB first performs the subquery.
The subquery calculates `MEAN()` values of `water_level` from `2019-08-18T00:00:00Z` through `2019-08-18T00:30:00Z` and groups the results into 12-minute intervals. It also names the output column `all_the_means`:
```sql
SELECT MEAN("water_level") AS "all_the_means" FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:30:00Z' GROUP BY time(12m)
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | all_the_means |
| :--------------------------- | ------------------: |
| 2019-08-18T00:00:00Z | 5.4135000000 |
| 2019-08-18T00:12:00Z | 5.3042500000 |
| 2019-08-18T00:24:00Z | 5.1682500000 |
Next, InfluxDB performs the main query and returns only those mean values that are greater than five.
Notice that the main query specifies `all_the_means` as the field key in the `SELECT` clause.
{{% /expand %}}
{{% expand "Calculate the SUM() of several DERIVATIVE() values" %}}
```sql
SELECT SUM("water_level_derivative") AS "sum_derivative" FROM (SELECT DERIVATIVE(MEAN("water_level")) AS "water_level_derivative" FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:30:00Z' GROUP BY time(12m),"location") GROUP BY "location"
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | sum_derivative |
| :--------------------------- | ------------------: |
| 1970-01-01T00:00:00Z | -0.5315000000 |
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=santa_monica
{{% /influxql/table-meta %}}
| time | sum_derivative |
| :--------------------------- | ------------------: |
| 1970-01-01T00:00:00Z | -0.2375000000 |
The query returns the sum of the derivative of average `water_level` values for each tag value of `location`.
InfluxDB first performs the subquery.
The subquery calculates the derivative of average `water_level` values taken at 12-minute intervals.
It performs that calculation for each tag value of `location` and names the output column `water_level_derivative`:
```sql
SELECT DERIVATIVE(MEAN("water_level")) AS "water_level_derivative" FROM "h2o_feet" WHERE time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:30:00Z' GROUP BY time(12m),"location"
```
Output:
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=coyote_creek
{{% /influxql/table-meta %}}
| time | water_level_derivative |
| :--------------------------- | ------------------: |
| 2019-08-18T00:00:00Z | -0.1410000000 |
| 2019-08-18T00:12:00Z | -0.1890000000 |
| 2019-08-18T00:24:00Z | -0.2015000000 |
{{% influxql/table-meta %}}
name: h2o_feet
tags: location=santa_monica
{{% /influxql/table-meta %}}
| time | water_level_derivative |
| :--------------------------- | ------------------: |
| 2019-08-18T00:00:00Z | -0.1375000000 |
| 2019-08-18T00:12:00Z | -0.0295000000 |
| 2019-08-18T00:24:00Z | -0.0705000000 |
Next, InfluxDB performs the main query and calculates the sum of the `water_level_derivative` values for each tag value of `location`.
Notice that the main query specifies `water_level_derivative`, not `water_level` or `derivative`, as the field key in the [`SUM()`](/influxdb/v2.5/query-data/influxql/functions/aggregates/#sum) function.
{{% /expand %}}
{{< /expand-wrapper >}}
### Common issues with subqueries
#### Multiple statements in a subquery
InfluxQL supports multiple nested subqueries per main query:
```sql
SELECT_clause FROM ( SELECT_clause FROM ( SELECT_statement ) [...] ) [...]
------------------ ----------------
Subquery 1 Subquery 2
```
InfluxQL does not support multiple [`SELECT` statements](/influxdb/v2.5/query-data/influxql/explore-data/select/) per subquery:
```sql
SELECT_clause FROM (SELECT_statement; SELECT_statement) [...]
```
The system returns a parsing error if a subquery includes multiple `SELECT` statements.

View File

@ -0,0 +1,441 @@
---
title: Time and timezone queries
list_title: Time and timezone queries
description: >
Explore InfluxQL features used specifically for working with time. Use the `tz` (timezone) clause to return the UTC offset for the specified timezone.
menu:
influxdb_2_5:
name: Time and timezone
parent: Explore data
weight: 308
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:
- [Configuring returned timestamps](#configuring-returned-timestamps)
- [Time syntax](#time-syntax)
- [Absolute time](#absolute-time)
- [Relative time](#relative-time)
- [The Time Zone clause](#the-time-zone-clause)
- [Common issues with time syntax](#common-issues-with-time-syntax)
## Configuring returned timestamps
The [InfluxQL shell](/influxdb/v2.5/tools/influxql-shell/) returns timestamps in
nanosecond UNIX epoch format by default.
Specify alternative formats with the
[`precision <format>` command](/influxdb/v2.5/tools/influxql-shell/#precision).
If you are using the [InfluxQL shell](/influxdb/v2.5/tools/influxql-shell/), use the precision helper command `precision rfc3339` to view results in human readable format.
The [InfluxDB API](/influxdb/v2.5/reference/api/influxdb-1x/) returns timestamps
in [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) format by default.
Specify alternative formats with the
[`epoch` query string parameter](/influxdb/v2.5/reference/api/influxdb-1x/).
## Time syntax
For most `SELECT` statements, the default time range is between [`1677-09-21 00:12:43.145224194` and `2262-04-11T23:47:16.854775806Z` UTC](/influxdb/v2.5/reference/faq/#what-are-the-minimum-and-maximum-timestamps-that-influxdb-can-store).
For `SELECT` statements with a [`GROUP BY time()` clause](/influxdb/v2.5/query-data/influxql/explore-data/group-by/),
the default time range is between `1677-09-21 00:12:43.145224194` UTC and [`now()`](/influxdb/v2.5/reference/glossary/#now).
The following sections detail how to specify alternative time ranges in the `SELECT`
statement's [`WHERE` clause](/influxdb/v2.5/query-data/influxql/explore-data/where/).
Other supported features include:
[Absolute time](#absolute-time)
[Relative time](#relative-time)
## Absolute time
Specify absolute time with date-time strings and epoch time.
### Syntax
```sql
SELECT_clause FROM_clause WHERE time <operator> ['<rfc3339_date_time_string>' | '<rfc3339_like_date_time_string>' | <epoch_time>] [AND ['<rfc3339_date_time_string>' | '<rfc3339_like_date_time_string>' | <epoch_time>] [...]]
```
#### Supported 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 |
Currently, InfluxDB does not support using `OR` with absolute time in the `WHERE`
clause. See the [Frequently Asked Questions](/influxdb/v2.5/reference/faq/#why-is-my-query-with-a-where-or-time-clause-returning-empty-results)
document and the [GitHub Issue](https://github.com/influxdata/influxdb/issues/7530)
for more information.
#### `rfc3339_date_time_string`
```sql
'YYYY-MM-DDTHH:MM:SS.nnnnnnnnnZ'
```
`.nnnnnnnnn` is optional and is set to `.000000000` if not included.
The [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) date-time string requires single quotes.
#### `rfc3339_like_date_time_string`
```sql
'YYYY-MM-DD HH:MM:SS.nnnnnnnnn'
```
`HH:MM:SS.nnnnnnnnn.nnnnnnnnn` is optional and is set to `00:00:00.000000000` if not included.
The RFC3339-like date-time string requires single quotes.
#### `epoch_time`
Epoch time is the amount of time that has elapsed since 00:00:00
Coordinated Universal Time (UTC), Thursday, 1 January 1970.
By default, InfluxDB assumes that all epoch timestamps are in **nanoseconds**. Include a [duration literal](/influxdb/v2.5/reference/glossary/#duration) at the end of the epoch timestamp to indicate a precision other than nanoseconds.
#### Basic arithmetic
All timestamp formats support basic arithmetic.
Add (`+`) or subtract (`-`) a time from a timestamp with a [duration literal](/influxdb/v2.5/reference/glossary/#duration).
Note that InfluxQL requires a whitespace between the `+` or `-` and the
duration literal.
### Examples
{{< expand-wrapper >}}
{{% expand "Specify a time range with RFC3339 date-time strings" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" = 'santa_monica' AND time >= '2019-08-18T00:00:00.000000000Z' AND time <= '2019-08-18T00:12:00Z'
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------ | ------------------:|
| 2019-08-18T00:00:00Z | 2.3520000000|
| 2019-08-18T00:06:00Z | 2.3790000000|
| 2019-08-18T00:12:00Z | 2.3430000000|
The query returns data with timestamps between August 18, 2019 at 00:00:00.000000000 and
August 18, 2019 at 00:12:00.
Note that the single quotes around the RFC3339 date-time strings are required.
{{% /expand %}}
{{% expand "Specify a time range with RFC3339-like date-time strings" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" = 'santa_monica' AND time >= '2019-08-18' AND time <= '2019-08-18 00:12:00'
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------ | ------------------:|
| 2019-08-18T00:00:00Z | 2.3520000000|
| 2019-08-18T00:06:00Z | 2.3790000000|
| 2019-08-18T00:12:00Z | 2.3430000000|
The query returns data with timestamps between August 18, 2019 at 00:00:00 and August 18, 2019
at 00:12:00.
The first date-time string does not include a time; InfluxDB assumes the time
is 00:00:00.
Note that the single quotes around the RFC3339-like date-time strings are
required.
{{% /expand %}}
{{% expand "Specify a time range with epock timestamps" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" = 'santa_monica' AND time >= 1564635600000000000 AND time <= 1566190800000000000
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------ | ------------------:|
| 2019-08-17T00:00:00Z | 2.0640000000|
| 2019-08-17T00:06:00Z | 2.1160000000|
| 2019-08-17T00:12:00Z | 2.0280000000|
| 2019-08-17T00:18:00Z | 2.1260000000|
| 2019-08-17T00:24:00Z | 2.0410000000|
| 2019-08-17T00:30:00Z | 2.0510000000|
| 2019-08-17T00:36:00Z | 2.0670000000|
| 2019-08-17T00:42:00Z | 2.0570000000|
| 2019-08-17T00:48:00Z | 1.9910000000|
| 2019-08-17T00:54:00Z | 2.0540000000|
| 2019-08-17T01:00:00Z | 2.0180000000|
| 2019-08-17T01:06:00Z | 2.0960000000|
| 2019-08-17T01:12:00Z | 2.1000000000|
| 2019-08-17T01:18:00Z | 2.1060000000|
| 2019-08-17T01:24:00Z | 2.1261441460|
The query returns data with timestamps that occur between August 1, 2019
at 00:00:00 and August 19, 2019 at 00:12:00. By default InfluxDB assumes epoch timestamps are in nanoseconds.
{{% /expand %}}
{{% expand "Specify a time range with second-precision epoch timestamps" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" = 'santa_monica' AND time >= 1566190800s AND time <= 1566191520s
```
Output:
| time | water_level |
| :------------------ | ------------------:|
| 2019-08-19T05:00:00Z | 3.2320000000|
| 2019-08-19T05:06:00Z | 3.2320000000|
| 2019-08-19T05:12:00Z | 3.2910000000|
The query returns data with timestamps that occur between August 19, 2019
at 00:00:00 and August 19, 2019 at 00:12:00.
The `s` duration literal at the end of the epoch timestamps indicate that the epoch timestamps are in seconds.
{{% /expand %}}
{{% expand "Perform basic arithmetic on an RFC3339-like date-time string" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE time > '2019-09-17T21:24:00Z' + 6m
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------ | ------------------:|
| 2019-09-17T21:36:00Z | 5.0660000000|
| 2019-09-17T21:42:00Z | 4.9380000000|
The query returns data with timestamps that occur at least six minutes after
September 17, 2019 at 21:24:00.
Note that the whitespace between the `+` and `6m` is required.
{{% /expand %}}
{{% expand "Perform basic arithmetic on an epock timestamp" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE time > 24043524m - 6m
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------ | ------------------:|
| 2019-08-17T00:00:00Z | 8.1200000000|
| 2019-08-17T00:00:00Z | 2.0640000000|
| 2019-08-17T00:06:00Z | 8.0050000000|
| 2019-08-17T00:06:00Z | 2.1160000000|
| 2019-08-17T00:12:00Z | 7.8870000000|
| 2019-08-17T00:12:00Z | 2.0280000000|
| 2019-08-17T00:18:00Z | 7.7620000000|
| 2019-08-17T00:18:00Z | 2.1260000000|
The query returns data with timestamps that occur at least six minutes before
September 18, 2019 at 21:24:00. Note that the whitespace between the `-` and `6m` is required. Note that the results above are partial as the dataset is large.
{{% /expand %}}
{{< /expand-wrapper >}}
## Relative time
Use [`now()`](/influxdb/v2.5/reference/glossary/#now) to query data with [timestamps](/influxdb/v2.5/reference/glossary/#timestamp) relative to the server's current timestamp.
### Syntax
```sql
SELECT_clause FROM_clause WHERE time <operator> now() [[ - | + ] <duration_literal>] [(AND|OR) now() [...]]
```
`now()` is the Unix time of the server at the time the query is executed on that server.
The whitespace between `-` or `+` and the [duration literal](/influxdb/v2.5/reference/glossary/#duration) is required.
#### Supported 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 |
#### `duration_literal`
- microseconds: `u` or `µ`
- milliseconds: `ms`
- seconds`s`
- minutes`m`
- hours:`h`
- days:`d`
- weeks:`w`
### Examples
{{< expand-wrapper >}}
{{% expand "Specify a time range with relative time" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE time > now() - 1h
```
The query returns data with timestamps that occur within the past hour.
The whitespace between `-` and `1h` is required.
{{% /expand %}}
{{% expand "Specify a time range with absolute time and relative time" %}}
#### Specify a time range with absolute time and relative time
```sql
SELECT "level description" FROM "h2o_feet" WHERE time > '2019-09-17T21:18:00Z' AND time < now() + 1000d
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description |
| :------------------ |--------------------:|
|2019-09-17T21:24:00Z | between 3 and 6 feet |
|2019-09-17T21:30:00Z | between 3 and 6 feet |
|2019-09-17T21:36:00Z | between 3 and 6 feet |
|2019-09-17T21:42:00Z | between 3 and 6 feet |
The query returns data with timestamps that occur between September 17, 2019 at 21:18:00 and 1000 days from `now()`. The whitespace between `+` and `1000d` is required.
{{% /expand %}}
{{< /expand-wrapper >}}
## The Time Zone clause
Use the `tz()` clause to return the UTC offset for the specified timezone.
### Syntax
```sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] [ORDER_BY_clause] [LIMIT_clause] [OFFSET_clause] [SLIMIT_clause] [SOFFSET_clause] tz('<time_zone>')
```
By default, InfluxDB stores and returns timestamps in UTC.
The `tz()` clause includes the UTC offset or, if applicable, the UTC Daylight Savings Time (DST) offset to the query's returned timestamps. The returned timestamps must be in `RFC3339` format for the UTC offset or UTC DST to appear.
The `time_zone` parameter follows the TZ syntax in the [Internet Assigned Numbers Authority time zone database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List) and it requires single quotes.
### Examples
{{< expand-wrapper >}}
{{% expand "Return the UTC offset for Chicago's time zone" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" = 'santa_monica' AND time >= '2019-08-18T00:00:00Z' AND time <= '2019-08-18T00:18:00Z' tz('America/Chicago')
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :-------------- | -------------------:|
| 2019-08-17T19:00:00-05:00 | 2.3520000000|
| 2019-08-17T19:06:00-05:00 | 2.3790000000|
| 2019-08-17T19:12:00-05:00 | 2.3430000000|
| 2019-08-17T19:18:00-05:00 | 2.3290000000|
The query results include the UTC offset (`-05:00`) for the `America/Chicago` time zone in the timestamps.
{{% /expand %}}
{{< /expand-wrapper >}}
## Common issues with time syntax
### Using `OR` to select time multiple time intervals
InfluxDB does not support using the `OR` operator in the `WHERE` clause to specify multiple time intervals.
For more information, see [Frequently asked questions](/influxdb/v2.5/reference/faq/#why-is-my-query-with-a-where-or-time-clause-returning-empty-results).
### Querying data that occur after `now()` with a `GROUP BY time()` clause
Most `SELECT` statements have a default time range between [`1677-09-21 00:12:43.145224194` and `2262-04-11T23:47:16.854775806Z` UTC](/influxdb/v2.5/reference/faq/#what-are-the-minimum-and-maximum-timestamps-that-influxdb-can-store).
For `SELECT` statements with a [`GROUP BY time()` clause](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-time-intervals),
the default time range is between `1677-09-21 00:12:43.145224194` UTC and [`now()`](/influxdb/v2.5/reference/glossary/#now).
To query data with timestamps that occur after `now()`, `SELECT` statements with
a `GROUP BY time()` clause must provide an alternative upper bound in the
`WHERE` clause.
<!-- #### Example
Use the [CLI](/enterprise_influxdb/v1.9/tools/influx-cli/use-influx/) to write a point to the `noaa` database that occurs after `now()`:
```sql
> INSERT h2o_feet,location=santa_monica water_level=3.1 1587074400000000000
```
Run a `GROUP BY time()` query that covers data with timestamps between
`2019-09-18T21:30:00Z` and `now()`:
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE "location"='santa_monica' AND time >= '2019-09-18T21:30:00Z' GROUP BY time(12m) fill(none)
name: h2o_feet
time mean
---- ----
2019-09-18T21:24:00Z 5.01
2019-09-18T21:36:00Z 5.002
```
Run a `GROUP BY time()` query that covers data with timestamps between
`2019-09-18T21:30:00Z` and 180 weeks from `now()`:
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE "location"='santa_monica' AND time >= '2019-09-18T21:30:00Z' AND time <= now() + 180w GROUP BY time(12m) fill(none)
name: h2o_feet
time mean
---- ----
2019-09-18T21:24:00Z 5.01
2019-09-18T21:36:00Z 5.002
2020-04-16T22:00:00Z 3.1
```
Note that the `WHERE` clause must provide an alternative **upper** bound to
override the default `now()` upper bound. The following query merely resets
the lower bound to `now()` such that the queried time range is between
`now()` and `now()`:
```sql
SELECT MEAN("water_level") FROM "h2o_feet" WHERE "location"='santa_monica' AND time >= now() GROUP BY time(12m) fill(none)
>
``` -->

View File

@ -0,0 +1,314 @@
---
title: The WHERE clause
list_title: WHERE clause
description: >
Use the `WHERE` clause to filter data based on [fields](/influxdb/v2.5/reference/glossary/#field), [tags](/influxdb/v2.5/reference/glossary/#tag), and/or [timestamps](/influxdb/v2.5/reference/glossary/#timestamp).
menu:
influxdb_2_5:
name: WHERE clause
parent: Explore data
weight: 302
list_code_example: |
```sql
SELECT_clause FROM_clause WHERE <conditional_expression> [(AND|OR) <conditional_expression> [...]]
```
---
Use the `WHERE` clause to filter data based on
[fields](/influxdb/v2.5/reference/glossary/#field),
[tags](/influxdb/v2.5/reference/glossary/#tag), and/or
[timestamps](/influxdb/v2.5/reference/glossary/#timestamp).
- [Syntax](#syntax)
- [Examples](#examples)
- [Common issues](#common-issues-with-the-where-clause)
### Syntax
```sql
SELECT_clause FROM_clause WHERE <conditional_expression> [(AND|OR) <conditional_expression> [...]]
```
The `WHERE` clause supports `conditional_expressions` on fields, tags, and timestamps.
{{% note %}}
**Note:** InfluxDB does not support using OR in the WHERE clause to specify multiple time ranges. For example, InfluxDB returns an empty response for the following query:
```sql
SELECT * FROM "mydb" WHERE time = '2020-07-31T20:07:00Z' OR time = '2020-07-31T23:07:17Z'`
```
{{% /note %}}
#### Fields
```
field_key <operator> ['string' | boolean | float | integer]
```
The `WHERE` clause supports comparisons against string, boolean, float, and integer [field values](/influxdb/v2.5/reference/glossary/#field-value).
Single quote string field values in the `WHERE` clause.
Queries with unquoted string field values or double quoted string field values will not return any data and, in most cases,
[will not return an error](#common-issues-with-the-where-clause).
#### Supported 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 |
InfluxQL also supports [Regular Expressions](/influxdb/v2.5/query-data/influxql/explore-data/regular-expressions/).
#### Tags
```sql
tag_key <operator> ['tag_value']
```
Single quote [tag values](/influxdb/v2.5/reference/glossary/#tag-value) in
the `WHERE` clause.
Queries with unquoted tag values or double quoted tag values will not return
any data and, in most cases,
[will not return an error](#common-issues-with-the-where-clause).
#### Supported operators
| Operator | Meaning |
|:--------:|:------- |
| `=` | equal to |
| `<>` | not equal to |
| `!=` | not equal to |
#### Timestamps
For most `SELECT` statements, the default time range is between [`1677-09-21 00:12:43.145224194` and `2262-04-11T23:47:16.854775806Z` UTC](/influxdb/v2.5/reference/faq/#what-are-the-minimum-and-maximum-integers-that-influxdb-can-store).
For `SELECT` statements with a [`GROUP BY time()` clause](/influxdb/v2.5/query-data/influxql/explore-data/group-by/), the default time
range is between `1677-09-21 00:12:43.145224194` UTC and [`now()`](/influxdb/v2.5/reference/glossary/#now).
See [Time Syntax](/influxdb/v2.5/query-data/influxql/explore-data/time-and-timezone/#time-syntax) for information on how to specify alternative time ranges in the `WHERE` clause.
### Examples
{{< expand-wrapper >}}
{{% expand "Select data with specific field key-values" %}}
```sql
SELECT * FROM "h2o_feet" WHERE "water_level" > 9
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level |
| :-------------- | :-------------------| :------------------| -------: |
| 2019-08-25T04:00:00Z | at or greater than 9 feet | coyote_creek | 9.0320000000|
| 2019-08-25T04:06:00Z | at or greater than 9 feet | coyote_creek | 9.0780000000|
| 2019-08-25T04:12:00Z | at or greater than 9 feet | coyote_creek | 9.1110000000|
| 2019-08-25T04:18:00Z | at or greater than 9 feet | coyote_creek | 9.1500000000|
| 2019-08-25T04:24:00Z | at or greater than 9 feet | coyote_creek | 9.1800000000|
The query returns data from the `h2o_feet` measurement with field values of `water_level` that are greater than nine.
This is a partial data set.
{{% /expand %}}
{{% expand "Select data with a specific string field key-value" %}}
```sql
SELECT * FROM "h2o_feet" WHERE "level description" = 'below 3 feet'
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level |
| :-------------- | :-------------------| :------------------| :------------------ |
| 2019-08-17T00:00:00Z | below 3 feet | santa_monica | 2.0640000000|
| 2019-08-17T00:06:00Z | below 3 feet | santa_monica | 2.1160000000|
| 2019-08-17T00:12:00Z | below 3 feet | santa_monica | 2.0280000000|
| 2019-08-17T00:18:00Z | below 3 feet | santa_monica | 2.1260000000|
| 2019-08-17T00:24:00Z | below 3 feet | santa_monica | 2.0410000000|
| 2019-08-17T00:30:00Z | below 3 feet | santa_monica | 2.0510000000|
The query returns data from the `h2o_feet` measurement with field values of `level description` that equal the `below 3 feet` string. InfluxQL requires single quotes around string field values in the `WHERE` clause.
{{% /expand %}}
{{% expand "Select data with a specific field key-value and perform basic arithmetic" %}}
```sql
SELECT * FROM "h2o_feet" WHERE "water_level" + 2 > 11.9
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level description | location | water_level |
| :-------------- | :-------------------| :------------------|---------------: |
| 2019-08-28T07:06:00Z | at or greater than 9 feet | coyote_creek | 9.9020000000|
| 2019-08-28T07:12:00Z | at or greater than 9 feet | coyote_creek | 9.9380000000|
| 2019-08-28T07:18:00Z | at or greater than 9 feet | coyote_creek | 9.9570000000|
| 2019-08-28T07:24:00Z | at or greater than 9 feet | coyote_creek | 9.9640000000|
| 2019-08-28T07:30:00Z | at or greater than 9 feet | coyote_creek | 9.9540000000|
| 2019-08-28T07:36:00Z | at or greater than 9 feet | coyote_creek | 9.9410000000|
| 2019-08-28T07:42:00Z | at or greater than 9 feet | coyote_creek | 9.9250000000|
| 2019-08-28T07:48:00Z | at or greater than 9 feet | coyote_creek | 9.9020000000|
| 2019-09-01T23:30:00Z | at or greater than 9 feet | coyote_creek | 9.9020000000|
The query returns data from the `h2o_feet` measurement with field values of
`water_level` plus two that are greater than 11.9. Note that InfluxDB follows the standard order of operations.
See [Mathematical operators](/influxdb/v2.5/query-data/influxql/math-operators/)
for more on supported operators.
{{% /expand %}}
{{% expand "Select data with a specific tag key-value" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" = 'santa_monica'
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :-------------- | -------------------:|
| 2019-08-17T00:00:00Z | 2.0640000000|
| 2019-08-17T00:06:00Z | 2.1160000000|
| 2019-08-17T00:12:00Z | 2.0280000000|
| 2019-08-17T00:18:00Z | 2.1260000000|
| 2019-08-17T00:24:00Z | 2.0410000000|
<!-- name: h2o_feet
--------------
time water_level
2019-08-18T00:00:00Z 2.064
2019-08-18T00:06:00Z 2.116
[...]
2019-09-18T21:36:00Z 5.066
2019-09-18T21:42:00Z 4.938 -->
The query returns data from the `h2o_feet` measurement where the
[tag key](/influxdb/v2.5/reference/glossary/#tag-key) `location` is set to `santa_monica`.
InfluxQL requires single quotes around tag values in the `WHERE` clause.
{{% /expand %}}
{{% expand "Select data with specific field key-values and tag key-valuest" %}}
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" <> 'santa_monica' AND (water_level < -0.59 OR water_level > 9.95)
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------- | -----------: |
| 2019-08-28T07:18:00Z | 9.9570000000|
| 2019-08-28T07:24:00Z | 9.9640000000|
| 2019-08-28T07:30:00Z | 9.9540000000|
| 2019-08-28T14:30:00Z | -0.6100000000|
| 2019-08-28T14:36:00Z | -0.5910000000|
| 2019-08-29T15:18:00Z | -0.5940000000|
The query returns data from the `h2o_feet` measurement where the tag key
`location` is not set to `santa_monica` and where the field values of
`water_level` are either less than -0.59 or greater than 9.95.
The `WHERE` clause supports the operators `AND` and `OR`, and supports
separating logic with parentheses.
{{% /expand %}}
{{< /expand-wrapper >}}
```sql
SELECT * FROM "h2o_feet" WHERE time > now() - 7d
```
The query returns data from the `h2o_feet` measurement with [timestamps](/influxdb/v2.5/reference/glossary/#timestamp)
within the past seven days. See [Time Syntax](/influxdb/v2.5/query-data/influxql/explore-data/time-and-timezone/#time-syntax) for more in-depth information on supported time syntax in the `WHERE` clause.
### Common issues with the `WHERE` clause
#### A `WHERE` clause query unexpectedly returns no data
In most cases, this issue is the result of missing single quotes around
tag values or string field values.
Queries with unquoted or double quoted tag values or string field values will
not return any data and, in most cases, will not return an error.
The first two queries in the code block below attempt to specify the tag value
`santa_monica` without any quotes and with double quotes.
Those queries return no results.
The third query single quotes `santa_monica` (this is the supported syntax)
and returns the expected results.
```sql
SELECT "water_level" FROM "h2o_feet" WHERE "location" = santa_monica
No results
SELECT "water_level" FROM "h2o_feet" WHERE "location" = "santa_monica"
No results
SELECT "water_level" FROM "h2o_feet" WHERE "location" = 'santa_monica'
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | water_level |
| :------------------- | -----------: |
| 2019-08-17T00:00:00Z | 2.0640000000 |
| 2019-08-17T00:06:00Z | 2.1160000000 |
| 2019-08-17T00:12:00Z | 2.0280000000 |
| 2019-08-17T00:18:00Z | 2.1260000000 |
| 2019-08-17T00:24:00Z | 2.0410000000 |
| 2019-08-17T00:30:00Z | 2.0510000000 |
The first two queries in the code block below attempt to specify the string
field value `at or greater than 9 feet` without any quotes and with double
quotes.
The first query returns an error because the string field value includes
white spaces.
The second query returns no results.
The third query single quotes `at or greater than 9 feet` (this is the
supported syntax) and returns the expected results.
```sql
SELECT "level description" FROM "h2o_feet" WHERE "level description" = at or greater than 9 feet
ERR: 400 Bad Request: failed to parse query: found than, expected ; at line 1, char 86
SELECT "level description" FROM "h2o_feet" WHERE "level description" = "at or greater than 9 feet"
No results
SELECT "level description" FROM "h2o_feet" WHERE "level description" = 'at or greater than 9 feet'
```
Output:
{{% influxql/table-meta %}}
Name: h2o_feet
{{% /influxql/table-meta %}}
| time | level_description |
| :---------------------------| ------: |
| 2019-08-25T04:00:00Z | at or greater than 9 feet |
| 2019-08-25T04:06:00Z | at or greater than 9 feet |
| 019-08-25T04:12:00Z | at or greater than 9 feet |
| 2019-08-25T04:18:00Z | at or greater than 9 feet |
| 2019-08-25T04:24:00Z | at or greater than 9 feet |

View File

@ -0,0 +1,592 @@
---
title: Explore your schema using InfluxQL
description: >
Learn to use InfluxQL to explore the schema of your time series data.
menu:
influxdb_2_5:
name: Explore your schema
parent: Query with InfluxQL
identifier: explore-schema-influxql
weight: 202
---
Use InfluxQL to explore the schema of your time series data.
Use the following InfluxQL commands to explore your schema:
- [SHOW SERIES](#show-series)
- [SHOW MEASUREMENTS](#show-measurements)
- [SHOW TAG KEYS](#show-tag-keys)
- [SHOW TAG VALUES](#show-tag-values)
- [SHOW FIELD KEYS](#show-field-keys)
- [SHOW FIELD KEY CARDINALITY](#show-field-key-cardinality)
- [SHOW TAG KEY CARDINALITY](#show-tag-key-cardinality)
{{% note %}}
Command examples use the [NOAA water sample data](/influxdb/v2.5/reference/sample-data/#noaa-water-sample-data).
{{% /note %}}
## SHOW SERIES
Return a list of [series](/influxdb/v2.5/reference/glossary/#series) for
the specified [database](/influxdb/v2.5/reference/glossary/#database).
### Syntax
```sql
SHOW SERIES [ON <database_name>] [FROM_clause] [WHERE <tag_key> <operator> [ '<tag_value>' | <regular_expression>]] [LIMIT_clause] [OFFSET_clause]
```
- `ON <database_name>` is optional.
If the query does not include `ON <database_name>`, you must specify the
database with the `db` query string parameter in the
[InfluxDB API](/influxdb/v2.5/reference/api/influxdb-1x/) request.
- `FROM`, `WHERE`, `LIMIT`, and `OFFSET` clauses are optional.
- The `WHERE` clause in `SHOW SERIES` supports tag comparisons but not field comparisons.
**Supported operators in the `WHERE` clause**:
- `=`: equal to
- `<>`: not equal to
- `!=`: not equal to
- `=~`: matches against
- `!~`: doesn't match against
See [Explore data using InfluxQL](/influxdb/v2.5/query-data/influxql/explore-data/) for documentation on the
[`FROM` clause](/influxdb/v2.5/query-data/influxql/explore-data/select/#from-clause),
[`LIMIT` clause](/influxdb/v2.5/query-data/influxql/explore-data/limit-and-slimit/),
[`OFFSET` clause](/influxdb/v2.5/query-data/influxql/explore-data/offset-and-soffset/),
and [Regular Expressions](/influxdb/v2.5/query-data/influxql/explore-data/regular-expressions/).
### Examples
#### Run SHOW SERIES with the ON clause
```sql
SHOW SERIES ON noaa
```
**Output:**
The query returns all series in the `noaa` database.
The query's output is similar to the [line protocol](/influxdb/v2.5/reference/syntax/line-protocol/) format.
Everything before the first comma is the [measurement](/influxdb/v2.5/reference/glossary/#measurement) name.
Everything after the first comma is either a [tag key](/influxdb/v2.5/reference/glossary/#tag-key) or a [tag value](/influxdb/v2.5/reference/glossary/#tag-value).
The `noaa` database has 5 different measurements and 13 different series.
| key |
| :------------------------------------------ |
| average_temperature,location=coyote_creek |
| average_temperature,location=santa_monica |
| h2o_feet,location=coyote_creek |
| h2o_feet,location=santa_monica |
| h2o_pH,location=coyote_creek |
| h2o_pH,location=santa_monica |
| h2o_quality,location=coyote_creek,randtag=1 |
| h2o_quality,location=coyote_creek,randtag=2 |
| h2o_quality,location=coyote_creek,randtag=3 |
| h2o_quality,location=santa_monica,randtag=1 |
| h2o_quality,location=santa_monica,randtag=2 |
| h2o_quality,location=santa_monica,randtag=3 |
| h2o_temperature,location=coyote_creek |
#### Run SHOW SERIES with several clauses
```sql
SHOW SERIES ON noaa FROM "h2o_quality" WHERE "location" = 'coyote_creek' LIMIT 2
```
**Output:**
The query returns all series in the `noaa` database that are
associated with the `h2o_quality` measurement and the tag `location = coyote_creek`.
The `LIMIT` clause limits the number of series returned to two.
| key |
| :------------------------------------------ |
|h2o_quality,location=coyote_creek,randtag=1 |
|h2o_quality,location=coyote_creek,randtag=2 |
## SHOW MEASUREMENTS
Returns a list of [measurements](/influxdb/v2.5/reference/glossary/#measurement)
for the specified [database](/influxdb/v2.5/reference/glossary/#database).
### Syntax
```sql
SHOW MEASUREMENTS [ON <database_name>] [WITH MEASUREMENT <operator> ['<measurement_name>' | <regular_expression>]] [WHERE <tag_key> <operator> ['<tag_value>' | <regular_expression>]] [LIMIT_clause] [OFFSET_clause]
```
- `ON <database_name>` is optional.
If the query does not include `ON <database_name>`, you must specify the
database with the `db` query string parameter in the
[InfluxDB API](/influxdb/v2.5/reference/api/influxdb-1x/) request.
- The `WITH`, `WHERE`, `LIMIT` and `OFFSET` clauses are optional.
- The `WHERE` in `SHOW MEASURMENTS` supports tag comparisons, but not field comparisons.
**Supported operators in the `WHERE` clause:**
- `=` : equal to
- `<>`: not equal to
- `!=`: not equal to
- `=~`: matches against
- `!~`: doesn't match against
See [Explore data using InfluxQL](/influxdb/v2.5/query-data/influxql/explore-data/) for documentation on the
[`FROM` clause](/influxdb/v2.5/query-data/influxql/explore-data/select/#from-clause),
[`LIMIT` clause](/influxdb/v2.5/query-data/influxql/explore-data/limit-and-slimit/),
[`OFFSET` clause](/influxdb/v2.5/query-data/influxql/explore-data/offset-and-soffset/),
and [Regular Expressions](/influxdb/v2.5/query-data/influxql/explore-data/regular-expressions/).
### Examples
#### Run SHOW MEASUREMENTS with the ON clause
```sql
SHOW MEASUREMENTS ON noaa
```
**Output:**
The query returns the list of measurements in the `noaa` database.
The database has five measurements: `average_temperature`, `h2o_feet`, `h2o_pH`,
`h2o_quality`, and `h2o_temperature`.
| name |
| :------------------ |
| average_temperature |
| h2o_feet |
| h2o_pH |
| h2o_quality |
| h2o_temperature |
#### Run SHOW MEASUREMENTS with several clauses (i)
```sql
SHOW MEASUREMENTS ON noaa WITH MEASUREMENT =~ /h2o.*/ LIMIT 2 OFFSET 1
```
**Output:**
The query returns the measurements in the `noaa` database that start with `h2o`.
The `LIMIT` and `OFFSET` clauses limit the number of measurement names returned to
two and offset the results by one, skipping the `h2o_feet` measurement.
| name |
| :---------- |
| h2o_pH |
| h2o_quality |
#### Run SHOW MEASUREMENTS with several clauses (ii)
```sql
SHOW MEASUREMENTS ON noaa WITH MEASUREMENT =~ /h2o.*/ WHERE "randtag" =~ /\d/
```
The query returns all measurements in the `noaa` that start with `h2o` and have
values for the tag key `randtag` that include an integer.
| name |
| :---------- |
| h2o_quality |
## SHOW TAG KEYS
Returns a list of [tag keys](/influxdb/v2.5/reference/glossary/#tag-key)
associated with the specified [database](/influxdb/v2.5/reference/glossary/#database).
### Syntax
```sql
SHOW TAG KEYS [ON <database_name>] [FROM_clause] WITH KEY [ [<operator> "<tag_key>" | <regular_expression>] | [IN ("<tag_key1>","<tag_key2>")]] [WHERE <tag_key> <operator> ['<tag_value>' | <regular_expression>]] [LIMIT_clause] [OFFSET_clause]
```
- `ON <database_name>` is optional.
If the query does not include `ON <database_name>`, you must specify the
database with `db` query string parameter in the [InfluxDB API](/influxdb/v2.5/reference/api/influxdb-1x/) request.
- The `FROM` clause and the `WHERE` clause are optional.
- The `WHERE` clause in `SHOW TAG KEYS` supports tag comparisons, but not field comparisons.
**Supported operators in the `WHERE` clause:**
- `=` : equal to
- `<>`: not equal to
- `!=`: not equal to
- `=~`: matches against
- `!~`: doesn't match against
See [Explore data using InfluxQL](/influxdb/v2.5/query-data/influxql/explore-data/) for documentation on the
[`FROM` clause](/influxdb/v2.5/query-data/influxql/explore-data/select/#from-clause),
[`LIMIT` clause](/influxdb/v2.5/query-data/influxql/explore-data/limit-and-slimit/),
[`OFFSET` clause](/influxdb/v2.5/query-data/influxql/explore-data/offset-and-soffset/),
and [Regular Expressions](/influxdb/v2.5/query-data/influxql/explore-data/regular-expressions/).
### Examples
#### Run SHOW TAG KEYS with the ON clause
```sql
SHOW TAG KEYS ON noaa
```
**Output:**
The query returns the list of tag keys in the `noaa` database.
The output groups tag keys by measurement name;
it shows that every measurement has the `location` tag key and that the
`h2o_quality` measurement has an additional `randtag` tag key.
| name | tagKey |
| :------------------ | :------- |
| average_temperature | location |
| h2o_feet | location |
| h2o_pH | location |
| h2o_quality | location |
| h2o_quality | randtag |
| h2o_temperature | location |
#### Run SHOW TAG KEYS with several clauses
```sql
SHOW TAG KEYS ON noaa FROM "h2o_quality" LIMIT 1 OFFSET 1
```
**Output:**
The query returns tag keys from the `h2o_quality` measurement in the `noaa` database.
The `LIMIT` and `OFFSET` clauses limit the number of tag keys returned to one
and offsets the results by one.
| name | tagKey |
| :---------- | :------ |
| h2o_quality | randtag |
#### Run SHOW TAG KEYS with a WITH KEY IN clause
```sql
SHOW TAG KEYS ON noaa WITH KEY IN ("location")
```
**Output:**
| measurement | tagKey |
| :------------------ | :------- |
| average_temperature | location |
| h2o_feet | location |
| h2o_pH | location |
| h2o_quality | location |
| h2o_quality | randtag |
| h2o_temperature | location |
## SHOW TAG VALUES
Returns the list of [tag values](/influxdb/v2.5/reference/glossary/#tag-value)
for the specified [tag key(s)](/influxdb/v2.5/reference/glossary/#tag-key) in the database.
### Syntax
```sql
SHOW TAG VALUES [ON <database_name>][FROM_clause] WITH KEY [ [<operator> "<tag_key>" | <regular_expression>] | [IN ("<tag_key1>","<tag_key2>")]] [WHERE <tag_key> <operator> ['<tag_value>' | <regular_expression>]] [LIMIT_clause] [OFFSET_clause]
```
- `ON <database_name>` is optional.
If the query does not include `ON <database_name>`, you must specify the
database with the `db` query string parameter in the [InfluxDB API](/influxdb/v2.5/reference/api/influxdb-1x/) request.
- The `WITH` clause is required.
It supports specifying a single tag key, a regular expression, and multiple tag keys.
- The `FROM`, `WHERE`, `LIMIT`, and `OFFSET` clauses are optional.
- The `WHERE` clause in `SHOW TAG KEYS` supports tag comparisons, but not field comparisons.
**Supported operators in the `WITH` and `WHERE` clauses:**
- `=` : equal to
- `<>`: not equal to
- `!=`: not equal to
- `=~`: matches against
- `!~`: doesn't match against
See [Explore data using InfluxQL](/influxdb/v2.5/query-data/influxql/explore-data/) for documentation on the
[`FROM` clause](/influxdb/v2.5/query-data/influxql/explore-data/select/#from-clause),
[`LIMIT` clause](/influxdb/v2.5/query-data/influxql/explore-data/limit-and-slimit/),
[`OFFSET` clause](/influxdb/v2.5/query-data/influxql/explore-data/offset-and-soffset/),
and [Regular Expressions](/influxdb/v2.5/query-data/influxql/explore-data/regular-expressions/).
### Examples
#### Run SHOW TAG VALUES with the ON clause
```sql
SHOW TAG VALUES ON noaa WITH KEY = "randtag"
```
**Output:**
The query returns all tag values of the `randtag` tag key in the `noaa` database.
`SHOW TAG VALUES` groups query results by measurement name.
{{% influxql/table-meta %}}
name: h2o_quality
{{% /influxql/table-meta %}}
| key | value |
| :------ | ----: |
| randtag | 1 |
| randtag | 2 |
| randtag | 3 |
#### Run a `SHOW TAG VALUES` query with several clauses
```sql
SHOW TAG VALUES ON noaa WITH KEY IN ("location","randtag") WHERE "randtag" =~ /./ LIMIT 3
```
**Output:**
The query returns the tag values of the tag keys `location` and `randtag` for
all measurements in the `noaa` database where `randtag` has tag values.
The `LIMIT` clause limits the number of tag values returned to three.
{{% influxql/table-meta %}}
name: h2o_quality
{{% /influxql/table-meta %}}
| key | value |
| :------- | -----------: |
| location | coyote_creek |
| location | santa_monica |
| randtag | 1 |
## SHOW FIELD KEYS
Returns the [field keys](/influxdb/v2.5/reference/glossary/#field-key) and the
[data type](/influxdb/v2.5/reference/glossary/#data-type) of their
[field values](/influxdb/v2.5/reference/glossary/#field-value).
### Syntax
```sql
SHOW FIELD KEYS [ON <database_name>] [FROM <measurement_name>]
```
- `ON <database_name>` is optional.
If the query does not include `ON <database_name>`, you must specify the
database with `USE <database_name>` when using the [InfluxQL shell](/influxdb/v2.5/tools/influxql-shell/)
or with the `db` query string parameter in the
[InfluxDB 1.x compatibility API](/influxdb/v2.5/reference/api/influxdb-1x/) request.
- The `FROM` clause is optional.
See the Data Exploration page for documentation on the
[` FROM` clause](/influxdb/v2.5/query-data/influxql/explore-data/select/#from-clause).
{{% note %}}
**Note:** A field's data type [can differ](/influxdb/v2.5/reference/faq/#how-does-influxdb-handle-field-type-discrepancies-across-shards) across
[shards](/influxdb/v2.5/reference/glossary/#shard).
If your field has more than one type, `SHOW FIELD KEYS` returns the type that
occurs first in the following list: float, integer, string, boolean.
{{% /note %}}
### Examples
#### Run SHOW FIELD KEYS with the ON clause
```sql
SHOW FIELD KEYS ON noaa
```
**Output:**
The query returns the field keys and field value data types for each
measurement in the `noaa` database.
| name | fieldKey | fieldType |
| :------------------ | :---------------- | :-------- |
| average_temperature | degrees | float |
| h2o_feet | level description | string |
| h2o_feet | water_level | float |
| h2o_pH | pH | float |
| h2o_quality | index | float |
| hh2o_temperature | degrees | float |
#### Run SHOW FIELD KEYS with the FROM clause
```sql
SHOW FIELD KEYS ON noaa FROM h2o_feet
```
**Output:**
The query returns the fields keys and field value data types for the `h2o_feet`
measurement in the `noaa` database.
| name | fieldKey | fieldType |
| :------- | :---------------- | :-------- |
| h2o_feet | level description | string |
| h2o_feet | water_level | float |
### Common Issues with SHOW FIELD KEYS
#### SHOW FIELD KEYS and field type discrepancies
Field value [data types](/influxdb/v2.5/reference/glossary/#data-type)
cannot differ within a [shard](/influxdb/v2.5/reference/glossary/#shard) but they
can differ across shards.
`SHOW FIELD KEYS` returns every data type, across every shard, associated with
the field key.
##### Example
The `all_the_types` field stores four different data types:
```sql
SHOW FIELD KEYS
```
{{% influxql/table-meta %}}
name: mymeas
{{% /influxql/table-meta %}}
| fieldKey | fieldType |
| :------------ | :-------- |
| all_the_types | integer |
| all_the_types | float |
| all_the_types | string |
| all_the_types | boolean |
Note that `SHOW FIELD KEYS` handles field type discrepancies differently from
`SELECT` statements.
For more information, see the
[How does InfluxDB handle field type discrepancies across shards?](/enterprise_influxdb/v1.9/troubleshooting/frequently-asked-questions/#how-does-influxdb-handle-field-type-discrepancies-across-shards).
## SHOW FIELD KEY CARDINALITY
Cardinality is the product of all unique databases, retention policies, measurements, field keys and tag values in your Influx instance. Managing cardinality is important, as high cardinality leads to greater resource usage.
```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 noaa
```
## SHOW TAG KEY CARDINALITY
```sql
-- show estimated tag key cardinality
SHOW TAG KEY CARDINALITY
-- show exact tag key cardinality
SHOW TAG KEY EXACT CARDINALITY
```
<!--
### SHOW TAG VALUES CARDINALITY
```sql
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" -->
<!-- ### Filter meta queries by time
When you filter meta queries by time, you may see results outside of your specified time. Meta query results are filtered at the shard level, so results can be approximately as granular as your shard group duration. If your time filter spans multiple shards, you'll get results from all shards with points in the specified time range. To review your shards and timestamps on points in the shard, run `SHOW SHARDS`. To learn more about shards and their duration, see [recommended shard groups durations](/influxdb/v2.5/reference/internals/shards/#shard-group-duration).
The example below shows how to filter `SHOW TAG KEYS` by approximately one hour using a 1h shard group duration. To filter other meta data, replace `SHOW TAG KEYS` with `SHOW TAG VALUES`, `SHOW SERIES`, `SHOW FIELD KEYS`, and so on.
{{% note %}}
**Note:** `SHOW MEASUREMENTS` cannot be filtered by time.
{{% /note %}}
#### Example filtering `SHOW TAG KEYS` by time
1. Specify a shard duration on a new database or [alter an existing shard duration](/enterprise_influxdb/v1.9/query_language/manage-database/#modify-retention-policies-with-alter-retention-policy). To specify a 1h shard duration when creating a new database, run the following command:
```sh
> CREATE database mydb with duration 7d REPLICATION 1 SHARD DURATION 1h name myRP;
```
> **Note:** The minimum shard duration is 1h.
2. Verify the shard duration has the correct time interval (precision) by running the `SHOW SHARDS` command. The example below shows a shard duration with an hour precision.
```sh
> SHOW SHARDS
name: mydb
id database retention_policy shard_group start_time end_time expiry_time owners
-- -------- ---------------- ----------- ---------- -------- ----------- ------
> precision h
```
3. (Optional) Insert sample tag keys. This step is for demonstration purposes. If you already have tag keys (or other meta data) to search for, skip this step.
```sh
// Insert a sample tag called "test_key" into the "test" measurement, and then check the timestamp:
> INSERT test,test_key=hello value=1
> select * from test
name: test
time test_key value
---- -------- -----
434820 hello 1
// Add new tag keys with timestamps one, two, and three hours earlier:
> INSERT test,test_key_1=hello value=1 434819
> INSERT test,test_key_2=hello value=1 434819
> INSERT test,test_key_3_=hello value=1 434818
> INSERT test,test_key_4=hello value=1 434817
> INSERT test,test_key_5_=hello value=1 434817
```
4. To find tag keys within a shard duration, run one of the following commands:
`SHOW TAG KEYS ON database-name <WHERE time clause>` OR
`SELECT * FROM measurement <WHERE time clause>`
The examples below use test data from step 3.
```sh
//Using data from Step 3, show tag keys between now and an hour ago
> SHOW TAG KEYS ON mydb where time > now() -1h and time < now()
name: test
tagKey
------
test_key
test_key_1
test_key_2
// Find tag keys between one and two hours ago
> SHOW TAG KEYS ON mydb where > time > now() -2h and time < now()-1h
name: test
tagKey
------
test_key_1
test_key_2
test_key_3
// Find tag keys between two and three hours ago
> SHOW TAG KEYS ON mydb where > time > now() -3h and time < now()-2h
name: test
tagKey
------select statement
test_key_3
test_key_4
test_key_5
// For a specified measurement, find tag keys in a given shard by specifying the time boundaries of the shard
SELECT * FROM test WHERE time >= '2019-08-09T00:00:00Z' and time < '2019-08-09T10:00:00Z'
name: test
time test_key_4 test_key_5 value
---- ------------ ------------ -----
434817 hello 1
434817 hello 1
// For a specified database, find tag keys in a given shard by specifying the time boundaries of the shard
> SHOW TAG KEYS ON mydb WHERE time >= '2019-08-09T00:00:00Z' and time < '2019-08-09T10:00:00Z'
name: test
tagKey
------
test_key_4
test_key_5
``` -->

View File

@ -0,0 +1,75 @@
---
title: View InfluxQL functions
description: >
Aggregate, select, transform, and predict data with InfluxQL functions.
menu:
influxdb_2_5:
name: InfluxQL functions
parent: Query with InfluxQL
weight: 203
---
Use InfluxQL functions to aggregate, select, transform, analyze, and predict data.
{{% note %}}
To query with InfluxQL, the bucket you query must be mapped to a database and retention policy (DBRP). For more information, see how to [Query data with InfluxQL](/influxdb/v2.5/query-data/influxql/).
{{%/ note %}}
## InfluxQL functions (by type)
- [Aggregates](/influxdb/v2.5/query-data/influxql/functions/aggregates/)
- [COUNT()](/influxdb/v2.5/query-data/influxql/functions/aggregates/#count)
- [DISTINCT()](/influxdb/v2.5/query-data/influxql/functions/aggregates/#distinct)
- [INTEGRAL()](/influxdb/v2.5/query-data/influxql/functions/aggregates/#integral)
- [MEAN()](/influxdb/v2.5/query-data/influxql/functions/aggregates/#mean)
- [MEDIAN()](/influxdb/v2.5/query-data/influxql/functions/aggregates/#median)
- [MODE()](/influxdb/v2.5/query-data/influxql/functions/aggregates/#mode)
- [SPREAD()](/influxdb/v2.5/query-data/influxql/functions/aggregates/#spread)
- [STDDEV()](/influxdb/v2.5/query-data/influxql/functions/aggregates/#stddev)
- [SUM()](/influxdb/v2.5/query-data/influxql/functions/aggregates/#sum)
- [Selectors](/influxdb/v2.5/query-data/influxql/functions/selectors/)
- [BOTTOM()](/influxdb/v2.5/query-data/influxql/functions/selectors/#bottom)
- [FIRST()](/influxdb/v2.5/query-data/influxql/functions/selectors/#first)
- [LAST()](/influxdb/v2.5/query-data/influxql/functions/selectors/#last)
- [MAX()](/influxdb/v2.5/query-data/influxql/functions/selectors/#max)
- [MIN()](/influxdb/v2.5/query-data/influxql/functions/selectors/#min)
- [PERCENTILE()](/influxdb/v2.5/query-data/influxql/functions/selectors/#percentile)
- [SAMPLE()](/influxdb/v2.5/query-data/influxql/functions/selectors/#sample)
- [TOP()](/influxdb/v2.5/query-data/influxql/functions/selectors/#top)
- [Transformations](/influxdb/v2.5/query-data/influxql/functions/transformations/)
- [ABS()](/influxdb/v2.5/query-data/influxql/functions/transformations/#abs)
- [ACOS()](/influxdb/v2.5/query-data/influxql/functions/transformations/#acos)
- [ASIN()](/influxdb/v2.5/query-data/influxql/functions/transformations/#asin)
- [ATAN()](/influxdb/v2.5/query-data/influxql/functions/transformations/#atan)
- [ATAN2()](/influxdb/v2.5/query-data/influxql/functions/transformations/#atan2)
- [CEIL()](/influxdb/v2.5/query-data/influxql/functions/transformations/#ceil)
- [COS()](/influxdb/v2.5/query-data/influxql/functions/transformations/#cos)
- [CUMULATIVE_SUM()](/influxdb/v2.5/query-data/influxql/functions/transformations/#cumulative_sum)
- [DERIVATIVE()](/influxdb/v2.5/query-data/influxql/functions/transformations/#derivative)
- [DIFFERENCE()](/influxdb/v2.5/query-data/influxql/functions/transformations/#difference)
- [ELAPSED()](/influxdb/v2.5/query-data/influxql/functions/transformations/#elapsed)
- [EXP()](/influxdb/v2.5/query-data/influxql/functions/transformations/#exp)
- [FLOOR()](/influxdb/v2.5/query-data/influxql/functions/transformations/#floor)
- [HISTOGRAM()](/influxdb/v2.5/query-data/influxql/functions/transformations/#histogram)
- [LN()](/influxdb/v2.5/query-data/influxql/functions/transformations/#ln)
- [LOG()](/influxdb/v2.5/query-data/influxql/functions/transformations/#log)
- [LOG2()](/influxdb/v2.5/query-data/influxql/functions/transformations/#log2)
- [LOG10()](/influxdb/v2.5/query-data/influxql/functions/transformations/#log10)
- [MOVING_AVERAGE()](/influxdb/v2.5/query-data/influxql/functions/transformations/#moving_average)
- [NON_NEGATIVE_DERIVATIVE()](/influxdb/v2.5/query-data/influxql/functions/transformations/#non_negative_derivative)
- [NON_NEGATIVE_DIFFERENCE()](/influxdb/v2.5/query-data/influxql/functions/transformations/#non_negative_difference)
- [POW()](/influxdb/v2.5/query-data/influxql/functions/transformations/#pow)
- [ROUND()](/influxdb/v2.5/query-data/influxql/functions/transformations/#round)
- [SIN()](/influxdb/v2.5/query-data/influxql/functions/transformations/#sin)
- [SQRT()](/influxdb/v2.5/query-data/influxql/functions/transformations/#sqrt)
- [TAN()](/influxdb/v2.5/query-data/influxql/functions/transformations/#tan)
- [Technical analysis](/influxdb/v2.5/query-data/influxql/functions/technical-analysis/)
- (Predictive analysis) [HOLT_WINTERS()](/influxdb/v2.5/query-data/influxql/functions/technical-analysis/#holt_winters)
- [CHANDE_MOMENTUM_OSCILLATOR()](/influxdb/v2.5/query-data/influxql/functions/technical-analysis/#chande_momentum_oscillator)
- [EXPONENTIAL_MOVING_AVERAGE()](/influxdb/v2.5/query-data/influxql/functions/technical-analysis/#exponential_moving_average)
- [DOUBLE_EXPONENTIAL_MOVING_AVERAGE()](/influxdb/v2.5/query-data/influxql/functions/technical-analysis/#double_exponential_moving_average)
- [KAUFMANS_EFFICIENCY_RATIO()](/influxdb/v2.5/query-data/influxql/functions/technical-analysis/#kaufmans_adaptive_moving_average)
- [KAUFMANS_ADAPTIVE_MOVING_AVERAGE()](/influxdb/v2.5/query-data/influxql/functions/technical-analysis/#kaufmans_adaptive_moving_average)
- [TRIPLE_EXPONENTIAL_MOVING_AVERAGE()](/influxdb/v2.5/query-data/influxql/functions/technical-analysis/#triple_exponential_moving_average)
- [TRIPLE_EXPONENTIAL_DERIVATIVE()](/influxdb/v2.5/query-data/influxql/functions/technical-analysis/#triple_exponential_derivative)
- [RELATIVE_STRENGTH_INDEX()](/influxdb/v2.5/query-data/influxql/functions/technical-analysis/#relative_strength_index)

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,659 @@
---
title: InfluxQL analysis functions
list_title: Technical analysis functions
description: >
Use technical analysis functions to apply algorithms to your data.
menu:
influxdb_2_5:
name: Technical analysis
parent: InfluxQL functions
weight: 205
---
Use technical analysis functions to apply algorithms to your data--often used to analyze financial and investment data.
Each analysis function below covers **syntax**, including parameters to pass to the function, and **examples** of how to use the function. Examples use [NOAA water sample data](/influxdb/v2.5/reference/sample-data/#noaa-water-sample-data).
- [Predictive analysis](#predictive-analysis):
- [HOLT_WINTERS()](#holt_winters)
- [Technical analysis](#technical-analysis-functions):
- [CHANDE_MOMENTUM_OSCILLATOR()](#chande_momentum_oscillator)
- [EXPONENTIAL_MOVING_AVERAGE()](#exponential_moving_average)
- [DOUBLE_EXPONENTIAL_MOVING_AVERAGE()](#double_exponential_moving_average)
- [KAUFMANS_EFFICIENCY_RATIO()](#kaufmans_efficiency_ratio)
- [KAUFMANS_ADAPTIVE_MOVING_AVERAGE()](#kaufmans_adaptive_moving_average)
- [TRIPLE_EXPONENTIAL_MOVING_AVERAGE()](#triple_exponential_moving_average)
- [TRIPLE_EXPONENTIAL_DERIVATIVE()](#triple_exponential_derivative)
- [RELATIVE_STRENGTH_INDEX()](#relative_strength_index)
## Predictive analysis
Predictive analysis functions are a type of technical analysis algorithms that
predict and forecast future values.
### HOLT_WINTERS()
Returns N number of predicted [field values](/influxdb/v2.5/reference/glossary/#field-value)
using the [Holt-Winters](https://www.otexts.org/fpp/7/5) seasonal method.
Supports int64 and float64 field value [data types](/influxdb/v2.5/query-data/influxql/explore-data/select/#data-types).
Works with data that occurs at consistent time intervals.
Requires an InfluxQL function and the `GROUP BY time()` clause to ensure that
the Holt-Winters function operates on regular data.
Use `HOLT_WINTERS()` to:
- Predict when data values will cross a given threshold
- Compare predicted values with actual values to detect anomalies in your data
#### Syntax
```
SELECT HOLT_WINTERS[_WITH-FIT](<function>(<field_key>),<N>,<S>) FROM_clause [WHERE_clause] GROUP_BY_clause [ORDER_BY_clause] [LIMIT_clause] [OFFSET_clause] [SLIMIT_clause] [SOFFSET_clause]
```
`HOLT_WINTERS(function(field_key),N,S)` returns `N` seasonally adjusted
predicted field values for the specified [field key](/influxdb/v2.5/reference/glossary/#field-key).
The `N` predicted values occur at the same interval as the [`GROUP BY time()` interval](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-time-intervals).
If your `GROUP BY time()` interval is `6m` and `N` is `3` you'll
receive three predicted values that are each six minutes apart.
`S` is the seasonal pattern parameter and delimits the length of a seasonal
pattern according to the `GROUP BY time()` interval.
If your `GROUP BY time()` interval is `2m` and `S` is `3`, then the
seasonal pattern occurs every six minutes, that is, every three data points.
If you do not want to seasonally adjust your predicted values, set `S` to `0`
or `1.`
`HOLT_WINTERS_WITH_FIT(function(field_key),N,S)` returns the fitted values in
addition to `N` seasonally adjusted predicted field values for the specified field key.
#### Examples
{{< expand-wrapper >}}
{{% expand "Predict field values associated with a field key" %}}
##### Sample data
The examples use the following subset of the [NOAA water sample data](/influxdb/v2.5/reference/sample-data/#noaa-water-sample-data):
```sql
SELECT "water_level" FROM "noaa"."autogen"."h2o_feet" WHERE "location"='santa_monica' AND time >= '2019-08-17T00:00:00Z' AND time <= '2019-08-22T00:00:00Z'
```
##### Step 1: Match the trends of the raw data
Write a `GROUP BY time()` query that matches the general trends of the raw `water_level` data.
Here, we use the [`FIRST()`](/influxdb/v2.5/query-data/influxql/functions/selectors/#first) function:
```sql
SELECT FIRST("water_level") FROM "noaa"."autogen"."h2o_feet" WHERE "location"='santa_monica' and time >= '2019-08-17T00:00:00Z' AND time <= '2019-08-22T00:00:00Z' GROUP BY time(6h,6h)
```
In the `GROUP BY time()` clause, the first argument (`6h`) matches
the length of time that occurs between each peak and trough in the `water_level` data.
The second argument (`6h`) is the
[offset interval](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#advanced-group-by-time-syntax).
The offset interval alters the default `GROUP BY time()` boundaries to
match the time range of the raw data.
{{< img-hd src="/img/influxdb/2-4-influxql-holtwinters-1.png" alt="Holt Winters base data" />}}
###### Step 2: Determine the seasonal pattern
Identify the seasonal pattern in the data using the information from the
query in step 1.
The pattern in the `water_level` data repeats about every 12 hours.
There are two data points per season, so `2` is the seasonal pattern argument.
{{< img-hd src="/img/influxdb/2-4-influxql-holtwinters-2.png" alt="Holt Winters seasonal data" />}}
###### Step 3: Apply the HOLT_WINTERS() function
Add the Holt-Winters function to the query.
Here, we use `HOLT_WINTERS_WITH_FIT()` to view both the fitted values and the predicted values:
```sql
SELECT HOLT_WINTERS_WITH_FIT(FIRST("water_level"),10,2) FROM "noaa"."autogen"."h2o_feet" WHERE "location"='santa_monica' AND time >= '2019-08-17 00:00:00' AND time <= '2019-08-22 00:00:00' GROUP BY time(6h,6h)
```
In the `HOLT_WINTERS_WITH_FIT()` function, the first argument (`10`) requests 10 predicted field values.
Each predicted point is `6h` apart, the same interval as the first argument in the `GROUP BY time()` clause.
The second argument in the `HOLT_WINTERS_WITH_FIT()` function (`2`) is the seasonal pattern that we determined in the previous step.
{{< img-hd src="/img/influxdb/2-4-influxql-holtwinters-3.png" alt="Holt Winters predicted data" />}}
{{% /expand %}}
{{< /expand-wrapper >}}
#### Common issues with `HOLT_WINTERS()`
##### Receiving fewer than `N` points
In some cases, you may receive fewer predicted points than requested by the `N` parameter.
That behavior typically occurs when the math becomes unstable and cannot forecast more
points. In this case, `HOLT_WINTERS()` may not be suited for the dataset or the seasonal adjustment parameter is invalid.
## Technical analysis functions
Technical analysis functions apply widely used algorithms to your data.
While they are primarily used in finance and investing, they have
application in other industries.
For technical analysis functions, consider whether to include the `PERIOD`, `HOLD_PERIOD`, and `WARMUP_TYPE` arguments:
#### `PERIOD`
**Required, integer, min=1**
The sample size for the algorithm, which is the number of historical samples with significant
effect on the output of the algorithm.
For example, `2` means the current point and the point before it.
The algorithm uses an exponential decay rate to determine the weight of a historical point,
generally known as the alpha (α). The `PERIOD` controls the decay rate.
{{% note %}}
**Note:** Older points can still have an impact.
{{% /note %}}
#### `HOLD_PERIOD`
**integer, min=-1**
How many samples the algorithm needs before emitting results.
The default of `-1` means the value is based on the algorithm, the `PERIOD`,
and the `WARMUP_TYPE`. Verify this value is enough for the algorithm to emit meaningful results.
_**Default hold periods:**_
For most technical analysis functions, the default `HOLD_PERIOD` is
determined by the function and the [`WARMUP_TYPE`](#warmup_type) shown in the following table:
| Algorithm \ Warmup Type | simple | exponential | none |
| --------------------------------- | ---------------------- | ----------- |:----------: |
| [EXPONENTIAL_MOVING_AVERAGE](#exponential_moving_average) | PERIOD - 1 | PERIOD - 1 | <span style="opacity:.35">n/a</span> |
| [DOUBLE_EXPONENTIAL_MOVING_AVERAGE](#double_exponential_moving_average) | ( PERIOD - 1 ) * 2 | PERIOD - 1 | <span style="opacity:.35">n/a</span> |
| [TRIPLE_EXPONENTIAL_MOVING_AVERAGE](#triple_exponential_moving_average) | ( PERIOD - 1 ) * 3 | PERIOD - 1 | <span style="opacity:.35">n/a</span> |
| [TRIPLE_EXPONENTIAL_DERIVATIVE](#triple_exponential_derivative) | ( PERIOD - 1 ) * 3 + 1 | PERIOD | <span style="opacity:.35">n/a</span> |
| [RELATIVE_STRENGTH_INDEX](#relative_strength_index) | PERIOD | PERIOD | <span style="opacity:.35">n/a</span> |
| [CHANDE_MOMENTUM_OSCILLATOR](#chande_momentum_oscillator) | PERIOD | PERIOD | PERIOD - 1 |
_**Kaufman algorithm default hold periods:**_
| Algorithm | Default Hold Period |
| --------- | ------------------- |
| [KAUFMANS_EFFICIENCY_RATIO()](#kaufmans_efficiency_ratio) | PERIOD |
| [KAUFMANS_ADAPTIVE_MOVING_AVERAGE()](#kaufmans_adaptive_moving_average) | PERIOD |
#### `WARMUP_TYPE`
**default='exponential'**
Controls how the algorithm initializes for the first `PERIOD` samples.
It is essentially the duration for which it has an incomplete sample set.
##### simple
Simple moving average (SMA) of the first `PERIOD` samples.
This is the method used by [ta-lib](https://www.ta-lib.org/).
##### exponential
Exponential moving average (EMA) with scaling alpha (α).
Uses an EMA with `PERIOD=1` for the first point, `PERIOD=2`
for the second point, and so on, until the algorithm has consumed `PERIOD` number of points.
As the algorithm immediately starts using an EMA, when this method is used and
`HOLD_PERIOD` is unspecified or `-1`, the algorithm may start emitting points
after a much smaller sample size than with `simple`.
##### none
The algorithm does not perform any smoothing at all.
Method used by [ta-lib](https://www.ta-lib.org/).
When this method is used and `HOLD_PERIOD` is unspecified, `HOLD_PERIOD`
defaults to `PERIOD - 1`.
{{% note %}}
**Note:** The `none` warmup type is only available with the [`CHANDE_MOMENTUM_OSCILLATOR()`](#chande_momentum_oscillator) function.
{{% /note %}}
## CHANDE_MOMENTUM_OSCILLATOR()
The Chande Momentum Oscillator (CMO) is a technical momentum indicator developed by Tushar Chande.
The CMO indicator is created by calculating the difference between the sum of all
recent higher data points and the sum of all recent lower data points,
then dividing the result by the sum of all data movement over a given time period.
The result is multiplied by 100 to give the -100 to +100 range.
<sup style="line-height:0; font-size:.7rem; font-style:italic; font-weight:normal;"><a href="https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/cmo" target="\_blank">Source</a>
Supports `GROUP BY` clauses that [group by tags](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-tags) but not `GROUP BY` clauses that [group by time](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-time-intervals). To use `CHANDE_MOMENTUM_OSCILLATOR()` with a `GROUP BY time()` clause, see [Advanced syntax](/influxdb/v2.5/query-data/influxql/functions/transformations/#advanced-syntax).
### Basic syntax
```
CHANDE_MOMENTUM_OSCILLATOR([ * | <field_key> | /regular_expression/ ], <period>[, <hold_period>, [warmup_type]])
```
### Arguments
- [period](#period)
- (Optional) [hold_period](#hold_period)
- (Optional) [warmup_type](#warmup_type)
`CHANDE_MOMENTUM_OSCILLATOR(field_key, 2)`
Returns the field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Chande Momentum Oscillator algorithm with a 2-value period
and the default hold period and warmup type.
`CHANDE_MOMENTUM_OSCILLATOR(field_key, 10, 9, 'none')`
Returns the field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Chande Momentum Oscillator algorithm with a 10-value period
a 9-value hold period, and the `none` warmup type.
`CHANDE_MOMENTUM_OSCILLATOR(MEAN(<field_key>), 2) ... GROUP BY time(1d)`
Returns the mean of field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Chande Momentum Oscillator algorithm with a 2-value period
and the default hold period and warmup type.
{{% note %}}
**Note:** When aggregating data with a `GROUP BY` clause, you must include an [aggregate function](/influxdb/v2.5/query-data/influxql/functions/aggregates/) in your call to the `CHANDE_MOMENTUM_OSCILLATOR()` function.
{{% /note %}}
`CHANDE_MOMENTUM_OSCILLATOR(/regular_expression/, 2)`
Returns the field values associated with each field key that matches the [regular expression](/influxdb/v2.5/query-data/influxql/explore-data/regular-expressions/)
processed using the Chande Momentum Oscillator algorithm with a 2-value period
and the default hold period and warmup type.
`CHANDE_MOMENTUM_OSCILLATOR(*, 2)`
Returns the field values associated with each field key in the [measurement](/influxdb/v2.5/reference/glossary/#measurement)
processed using the Chande Momentum Oscillator algorithm with a 2-value period
and the default hold period and warmup type.
`CHANDE_MOMENTUM_OSCILLATOR()` supports int64 and float64 field value [data types](/influxdb/v2.5/query-data/influxql/explore-data/select/#data-types).
## EXPONENTIAL_MOVING_AVERAGE()
An exponential moving average (EMA) (or exponentially weighted moving average) is a type of moving average similar to a [simple moving average](/influxdb/v2.5/query-data/influxql/functions/transformations/#moving_average),
except more weight is given to the latest data.
This type of moving average reacts faster to recent data changes than a simple moving average.
<sup style="line-height:0; font-size:.7rem; font-style:italic; font-weight:normal;"><a href="https://www.investopedia.com/terms/e/ema.asp" target="\_blank">Source</a>
Supports `GROUP BY` clauses that [group by tags](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-tags) but not `GROUP BY` clauses that [group by time](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-time-intervals).
To use `EXPONENTIAL_MOVING_AVERAGE()` with a `GROUP BY time()` clause, see [Advanced syntax](/influxdb/v2.5/query-data/influxql/functions/transformations/#advanced-syntax).
### Basic syntax
```sql
EXPONENTIAL_MOVING_AVERAGE([ * | <field_key> | /regular_expression/ ], <period>[, <hold_period)[, <warmup_type]])
```
`EXPONENTIAL_MOVING_AVERAGE(field_key, 2)`
Returns the field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`EXPONENTIAL_MOVING_AVERAGE(field_key, 10, 9, 'exponential')`
Returns the field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Exponential Moving Average algorithm with a 10-value period
a 9-value hold period, and the `exponential` warmup type.
`EXPONENTIAL_MOVING_AVERAGE(MEAN(<field_key>), 2) ... GROUP BY time(1d)`
Returns the mean of field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
{{% note %}}
**Note:** When aggregating data with a `GROUP BY` clause, you must include an [aggregate function](/influxdb/v2.5/query-data/influxql/functions/aggregates/) in your call to the `EXPONENTIAL_MOVING_AVERAGE()` function.
{{% /note %}}
`EXPONENTIAL_MOVING_AVERAGE(/regular_expression/, 2)`
Returns the field values associated with each field key that matches the [regular expression](/influxdb/v2.5/query-data/influxql/explore-data/regular-expressions/)
processed using the Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`EXPONENTIAL_MOVING_AVERAGE(*, 2)`
Returns the field values associated with each field key in the [measurement](/influxdb/v2.5/reference/glossary/#measurement)
processed using the Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`EXPONENTIAL_MOVING_AVERAGE()` supports int64 and float64 field value [data types](/influxdb/v2.5/query-data/influxql/explore-data/select/#data-types).
### Arguments
- [period](#period)
- (Optional) [hold_period](#hold_period)
- (Optional) [warmup_type](#warmup_type)
## DOUBLE_EXPONENTIAL_MOVING_AVERAGE()
The Double Exponential Moving Average (DEMA) attempts to remove the inherent lag
associated with moving averages by placing more weight on recent values.
The name suggests this is achieved by applying a double exponential smoothing which is not the case.
The value of an [EMA](#exponential_moving_average) is doubled.
To keep the value in line with the actual data and to remove the lag, the value "EMA of EMA"
is subtracted from the previously doubled EMA.
<sup style="line-height:0; font-size:.7rem; font-style:italic; font-weight:normal;"><a href="https://en.wikipedia.org/wiki/Double_exponential_moving_average" target="\_blank">Source</a>
Supports `GROUP BY` clauses that [group by tags](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-tags) but not `GROUP BY` clauses that [group by time](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-time-intervals).
To use `DOUBLE_EXPONENTIAL_MOVING_AVERAGE()` with a `GROUP BY time()` clause, see [Advanced syntax](/influxdb/v2.5/query-data/influxql/functions/transformations/#advanced-syntax).
### Basic syntax
```
DOUBLE_EXPONENTIAL_MOVING_AVERAGE([ * | <field_key> | /regular_expression/ ], <period>[, <hold_period)[, <warmup_type]])
```
`DOUBLE_EXPONENTIAL_MOVING_AVERAGE(field_key, 2)`
Returns the field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Double Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`DOUBLE_EXPONENTIAL_MOVING_AVERAGE(field_key, 10, 9, 'exponential')`
Returns the field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Double Exponential Moving Average algorithm with a 10-value period
a 9-value hold period, and the `exponential` warmup type.
`DOUBLE_EXPONENTIAL_MOVING_AVERAGE(MEAN(<field_key>), 2) ... GROUP BY time(1d)`
Returns the mean of field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Double Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
{{% note %}}
**Note:** When aggregating data with a `GROUP BY` clause, you must include an [aggregate function](/influxdb/v2.5/query-data/influxql/functions/aggregates/) in your call to the `DOUBLE_EXPONENTIAL_MOVING_AVERAGE()` function.
{{% /note %}}
`DOUBLE_EXPONENTIAL_MOVING_AVERAGE(/regular_expression/, 2)`
Returns the field values associated with each field key that matches the [regular expression](/influxdb/v2.5/query-data/influxql/explore-data/regular-expressions/)
processed using the Double Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`DOUBLE_EXPONENTIAL_MOVING_AVERAGE(*, 2)`
Returns the field values associated with each field key in the [measurement](/influxdb/v2.5/reference/glossary/#measurement)
processed using the Double Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`DOUBLE_EXPONENTIAL_MOVING_AVERAGE()` supports int64 and float64 field value [data types](/influxdb/v2.5/query-data/influxql/explore-data/select/#data-types).
### Arguments
- [period](#period)
- (Optional) [hold_period](#hold_period)
- (Optional) [warmup_type](#warmup_type)
## KAUFMANS_EFFICIENCY_RATIO()
Kaufman's Efficiency Ration, or simply "Efficiency Ratio" (ER), is calculated by
dividing the data change over a period by the absolute sum of the data movements
that occurred to achieve that change.
The resulting ratio ranges between 0 and 1 with higher values representing a
more efficient or trending market.
The ER is very similar to the [Chande Momentum Oscillator](#chande_momentum_oscillator) (CMO).
The difference is that the CMO takes market direction into account, but if you take the absolute CMO and divide by 100, you you get the Efficiency Ratio.
<sup style="line-height:0; font-size:.7rem; font-style:italic; font-weight:normal;"><a href="http://etfhq.com/blog/2011/02/07/kaufmans-efficiency-ratio/" target="\_blank">Source</a>
Supports `GROUP BY` clauses that [group by tags](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-tags) but not `GROUP BY` clauses that [group by time](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-time-intervals).
To use `KAUFMANS_EFFICIENCY_RATIO()` with a `GROUP BY time()` clause, see [Advanced syntax](/influxdb/v2.5/query-data/influxql/functions/transformations/#advanced-syntax).
### Basic syntax
```
KAUFMANS_EFFICIENCY_RATIO([ * | <field_key> | /regular_expression/ ], <period>[, <hold_period>])
```
`KAUFMANS_EFFICIENCY_RATIO(field_key, 2)`
Returns the field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Efficiency Index algorithm with a 2-value period
and the default hold period and warmup type.
`KAUFMANS_EFFICIENCY_RATIO(field_key, 10, 10)`
Returns the field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Efficiency Index algorithm with a 10-value period and
a 10-value hold period.
`KAUFMANS_EFFICIENCY_RATIO(MEAN(<field_key>), 2) ... GROUP BY time(1d)`
Returns the mean of field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Efficiency Index algorithm with a 2-value period
and the default hold period.
{{% note %}}
**Note:** When aggregating data with a `GROUP BY` clause, you must include an [aggregate function](/influxdb/v2.5/query-data/influxql/functions/aggregates/) in your call to the `KAUFMANS_EFFICIENCY_RATIO()` function.
{{% /note %}}
`KAUFMANS_EFFICIENCY_RATIO(/regular_expression/, 2)`
Returns the field values associated with each field key that matches the [regular expression](/influxdb/v2.5/query-data/influxql/explore-data/regular-expressions/)
processed using the Efficiency Index algorithm with a 2-value period
and the default hold period and warmup type.
`KAUFMANS_EFFICIENCY_RATIO(*, 2)`
Returns the field values associated with each field key in the [measurement](/influxdb/v2.5/reference/glossary/#measurement)
processed using the Efficiency Index algorithm with a 2-value period
and the default hold period and warmup type.
`KAUFMANS_EFFICIENCY_RATIO()` supports int64 and float64 field value [data types](/influxdb/v2.5/query-data/influxql/explore-data/select/#data-types).
**Arguments:**
- [period](#period)
- (Optional) [hold_period](#hold_period)
## KAUFMANS_ADAPTIVE_MOVING_AVERAGE()
Kaufman's Adaptive Moving Average (KAMA) is a moving average designed to
account for sample noise or volatility.
KAMA will closely follow data points when the data swings are relatively small and noise is low.
KAMA will adjust when the data swings widen and follow data from a greater distance.
This trend-following indicator can be used to identify the overall trend,
time turning points and filter data movements.
<sup style="line-height:0; font-size:.7rem; font-style:italic; font-weight:normal;"><a href="http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:kaufman_s_adaptive_moving_average" target="\_blank">Source</a>
Supports `GROUP BY` clauses that [group by tags](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-tags) but not `GROUP BY` clauses that [group by time](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-time-intervals).
To use `KAUFMANS_ADAPTIVE_MOVING_AVERAGE()` with a `GROUP BY time()` clause, see [Advanced syntax](/influxdb/v2.5/query-data/influxql/functions/transformations/#advanced-syntax).
### Basic syntax
```
KAUFMANS_ADAPTIVE_MOVING_AVERAGE([ * | <field_key> | /regular_expression/ ], <period>[, <hold_period>])
```
`KAUFMANS_ADAPTIVE_MOVING_AVERAGE(field_key, 2)`
Returns the field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Kaufman Adaptive Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`KAUFMANS_ADAPTIVE_MOVING_AVERAGE(field_key, 10, 10)`
Returns the field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Kaufman Adaptive Moving Average algorithm with a 10-value period
and a 10-value hold period.
`KAUFMANS_ADAPTIVE_MOVING_AVERAGE(MEAN(<field_key>), 2) ... GROUP BY time(1d)`
Returns the mean of field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Kaufman Adaptive Moving Average algorithm with a 2-value period
and the default hold period.
{{% note %}}
**Note:** When aggregating data with a `GROUP BY` clause, you must include an [aggregate function](/influxdb/v2.5/query-data/influxql/functions/aggregates/) in your call to the `KAUFMANS_ADAPTIVE_MOVING_AVERAGE()` function.
{{% /note %}}
`KAUFMANS_ADAPTIVE_MOVING_AVERAGE(/regular_expression/, 2)`
Returns the field values associated with each field key that matches the [regular expression](/influxdb/v2.5/query-data/influxql/explore-data/regular-expressions/)
processed using the Kaufman Adaptive Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`KAUFMANS_ADAPTIVE_MOVING_AVERAGE(*, 2)`
Returns the field values associated with each field key in the [measurement](/influxdb/v2.5/reference/glossary/#measurement)
processed using the Kaufman Adaptive Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`KAUFMANS_ADAPTIVE_MOVING_AVERAGE()` supports int64 and float64 field value [data types](/influxdb/v2.5/query-data/influxql/explore-data/select/#data-types).
**Arguments:**
- [period](#period)
- (Optional) [hold_period](#hold_period)
## TRIPLE_EXPONENTIAL_MOVING_AVERAGE()
The triple exponential moving average (TEMA) filters out
volatility from conventional moving averages.
While the name implies that it's a triple exponential smoothing, it's actually a
composite of a [single exponential moving average](#exponential_moving_average),
a [double exponential moving average](#double_exponential_moving_average),
and a triple exponential moving average.
<sup style="line-height:0; font-size:.7rem; font-style:italic; font-weight:normal;"><a href="https://www.investopedia.com/terms/t/triple-exponential-moving-average.asp " target="\_blank">Source</a>
Supports `GROUP BY` clauses that [group by tags](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-tags) but not `GROUP BY` clauses that [group by time](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-time-intervals).
To use `TRIPLE_EXPONENTIAL_MOVING_AVERAGE()` with a `GROUP BY time()` clause, see [Advanced syntax](/influxdb/v2.5/query-data/influxql/functions/transformations/#advanced-syntax).
### Basic syntax
```
TRIPLE_EXPONENTIAL_MOVING_AVERAGE([ * | <field_key> | /regular_expression/ ], <period>[, <hold_period)[, <warmup_type]])
```
`TRIPLE_EXPONENTIAL_MOVING_AVERAGE(field_key, 2)`
Returns the field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Triple Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`TRIPLE_EXPONENTIAL_MOVING_AVERAGE(field_key, 10, 9, 'exponential')`
Returns the field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Triple Exponential Moving Average algorithm with a 10-value period
a 9-value hold period, and the `exponential` warmup type.
`TRIPLE_EXPONENTIAL_MOVING_AVERAGE(MEAN(<field_key>), 2) ... GROUP BY time(1d)`
Returns the mean of field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Triple Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
{{% note %}}
**Note:** When aggregating data with a `GROUP BY` clause, you must include an [aggregate function](/influxdb/v2.5/query-data/influxql/functions/aggregates/) in your call to the `TRIPLE_EXPONENTIAL_MOVING_AVERAGE()` function.
{{% /note %}}
`TRIPLE_EXPONENTIAL_MOVING_AVERAGE(/regular_expression/, 2)`
Returns the field values associated with each field key that matches the [regular expression](/influxdb/v2.5/query-data/influxql/explore-data/regular-expressions/)
processed using the Triple Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`TRIPLE_EXPONENTIAL_MOVING_AVERAGE(*, 2)`
Returns the field values associated with each field key in the [measurement](/influxdb/v2.5/reference/glossary/#measurement)
processed using the Triple Exponential Moving Average algorithm with a 2-value period
and the default hold period and warmup type.
`TRIPLE_EXPONENTIAL_MOVING_AVERAGE()` supports int64 and float64 field value [data types](/influxdb/v2.5/query-data/influxql/explore-data/select/#data-types).
**Arguments:**
- [period](#period)
- (Optional) [hold_period](#hold_period)
- (Optional) [warmup_type](#warmup_type)
## TRIPLE_EXPONENTIAL_DERIVATIVE()
The triple exponential derivative indicator, commonly referred to as "TRIX," is
an oscillator used to identify oversold and overbought markets, and can also be
used as a momentum indicator.
TRIX calculates a [triple exponential moving average](#triple_exponential_moving_average)
of the [log](/influxdb/v2.5/query-data/influxql/functions/transformations/#log)
of the data input over the period of time.
The previous value is subtracted from the previous value.
This prevents cycles that are shorter than the defined period from being considered by the indicator.
Like many oscillators, TRIX oscillates around a zero line. When used as an oscillator,
a positive value indicates an overbought market while a negative value indicates an oversold market.
When used as a momentum indicator, a positive value suggests momentum is increasing
while a negative value suggests momentum is decreasing.
Many analysts believe that when the TRIX crosses above the zero line it gives a
buy signal, and when it closes below the zero line, it gives a sell signal.
<sup style="line-height:0; font-size:.7rem; font-style:italic; font-weight:normal;"><a href="https://www.investopedia.com/articles/technical/02/092402.asp " target="\_blank">Source</a>
Supports `GROUP BY` clauses that [group by tags](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-tags) but not `GROUP BY` clauses that [group by time](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-time-intervals).
To use `TRIPLE_EXPONENTIAL_DERIVATIVE()` with a `GROUP BY time()` clause, see [Advanced syntax](/influxdb/v2.5/query-data/influxql/functions/transformations/#advanced-syntax).
### Basic syntax
```
TRIPLE_EXPONENTIAL_DERIVATIVE([ * | <field_key> | /regular_expression/ ], <period>[, <hold_period)[, <warmup_type]])
```
`TRIPLE_EXPONENTIAL_DERIVATIVE(field_key, 2)`
Returns the field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Triple Exponential Derivative algorithm with a 2-value period
and the default hold period and warmup type.
`TRIPLE_EXPONENTIAL_DERIVATIVE(field_key, 10, 10, 'exponential')`
Returns the field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Triple Exponential Derivative algorithm with a 10-value period,
a 10-value hold period, and the `exponential` warmup type.
`TRIPLE_EXPONENTIAL_DERIVATIVE(MEAN(<field_key>), 2) ... GROUP BY time(1d)`
Returns the mean of field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Triple Exponential Derivative algorithm with a 2-value period
and the default hold period and warmup type.
{{% note %}}
**Note:** When aggregating data with a `GROUP BY` clause, you must include an [aggregate function](/influxdb/v2.5/query-data/influxql/functions/aggregates/) in your call to the `TRIPLE_EXPONENTIAL_DERIVATIVE()` function.
{{% /note %}}
`TRIPLE_EXPONENTIAL_DERIVATIVE(/regular_expression/, 2)`
Returns the field values associated with each field key that matches the [regular expression](/influxdb/v2.5/query-data/influxql/explore-data/regular-expressions/)
processed using the Triple Exponential Derivative algorithm with a 2-value period
and the default hold period and warmup type.
`TRIPLE_EXPONENTIAL_DERIVATIVE(*, 2)`
Returns the field values associated with each field key in the [measurement](/influxdb/v2.5/reference/glossary/#measurement)
processed using the Triple Exponential Derivative algorithm with a 2-value period
and the default hold period and warmup type.
`TRIPLE_EXPONENTIAL_DERIVATIVE()` supports int64 and float64 field value [data types](/influxdb/v2.5/query-data/influxql/explore-data/select/#data-types).
## RELATIVE_STRENGTH_INDEX()
The relative strength index (RSI) is a momentum indicator that compares the magnitude of recent increases and decreases over a specified time period to measure speed and change of data movements.
<sup style="line-height:0; font-size:.7rem; font-style:italic; font-weight:normal;"><a href="https://www.investopedia.com/terms/r/rsi.asp" target="\_blank">Source</a>
Supports `GROUP BY` clauses that [group by tags](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-tags) but not `GROUP BY` clauses that [group by time](/influxdb/v2.5/query-data/influxql/explore-data/group-by/#group-by-time-intervals).
To use `RELATIVE_STRENGTH_INDEX()` with a `GROUP BY time()` clause, see [Advanced syntax](/influxdb/v2.5/query-data/influxql/functions/transformations/#advanced-syntax).
### Basic syntax
```
RELATIVE_STRENGTH_INDEX([ * | <field_key> | /regular_expression/ ], <period>[, <hold_period)[, <warmup_type]])
```
`RELATIVE_STRENGTH_INDEX(field_key, 2)`
Returns the field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Relative Strength Index algorithm with a 2-value period
and the default hold period and warmup type.
`RELATIVE_STRENGTH_INDEX(field_key, 10, 10, 'exponential')`
Returns the field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Relative Strength Index algorithm with a 10-value period,
a 10-value hold period, and the `exponential` warmup type.
`RELATIVE_STRENGTH_INDEX(MEAN(<field_key>), 2) ... GROUP BY time(1d)`
Returns the mean of field values associated with the [field key](/influxdb/v2.5/reference/glossary/#field-key)
processed using the Relative Strength Index algorithm with a 2-value period
and the default hold period and warmup type.
{{% note %}}
**Note:** When aggregating data with a `GROUP BY` clause, you must include an [aggregate function](/influxdb/v2.5/query-data/influxql/functions/aggregates/) in your call to the `RELATIVE_STRENGTH_INDEX()` function.
{{% /note %}}
`RELATIVE_STRENGTH_INDEX(/regular_expression/, 2)`
Returns the field values associated with each field key that matches the [regular expression](/influxdb/v2.5/query-data/influxql/explore-data/regular-expressions/)
processed using the Relative Strength Index algorithm with a 2-value period
and the default hold period and warmup type.
`RELATIVE_STRENGTH_INDEX(*, 2)`
Returns the field values associated with each field key in the [measurement](/influxdb/v2.5/reference/glossary/#measurement)
processed using the Relative Strength Index algorithm with a 2-value period
and the default hold period and warmup type.
`RELATIVE_STRENGTH_INDEX()` supports int64 and float64 field value [data types](/influxdb/v2.5/query-data/influxql/explore-data/select/#data-types).
**Arguments:**
- [period](#period)
- (Optional) [hold_period](#hold_period)
- (Optional) [warmup_type](#warmup_type)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,149 @@
---
title: Manage your data using InfluxQL
description: >
Use InfluxQL data management commands to write and delete data.
menu:
influxdb_2_5:
name: Manage your data
parent: Query with InfluxQL
identifier: manage-database
weight: 204
---
Use the following data management commands to write and delete data with InfluxQL:
- [Write data with INSERT](#write-data-with-insert)
- [Delete series with DELETE](#delete-series-with-delete)
- [Delete measurements with DROP MEASUREMENT](#delete-measurements-with-drop-measurement)
## Write data with INSERT
The `INSERT` statement writes [line protocol](/influxdb/v2.5/reference/syntax/line-protocol/)
to a database and retention policy.
### Syntax
```sql
INSERT [INTO <database>[.<retention-policy>]] <line-protocol>
```
- The `INTO` clause is optional.
If the command does not include `INTO`, you must specify the
database with `USE <database_name>` when using the [InfluxQL shell](/influxdb/v2.5/tools/influxql-shell/)
or with the `db` query string parameter in the
[InfluxDB 1.x compatibility API](/influxdb/v2.5/reference/api/influxdb-1x/) request.
### Examples
- [Insert data into the a specific database and retention policy](#insert-data-into-the-a-specific-database-and-retention-policy)
- [Insert data into the a the default retention policy of a database](#insert-data-into-the-a-the-default-retention-policy-of-a-database)
- [Insert data into the currently used database](#insert-data-into-the-currently-used-database)
#### Insert data into the a specific database and retention policy
```sql
INSERT INTO mydb.myrp example-m,tag1=value1 field1=1i 1640995200000000000
```
#### Insert data into the a the default retention policy of a database
```sql
INSERT INTO mydb example-m,tag1=value1 field1=1i 1640995200000000000
```
#### Insert data into the currently used database
The following example uses the [InfluxQL shell](/influxdb/v2.5/tools/influxql-shell).
```sql
> USE mydb
> INSERT example-m,tag1=value1 field1=1i 1640995200000000000
```
## Delete series with DELETE
The `DELETE` statement deletes all points from a [series](/influxdb/v2.5/reference/glossary/#series) in a database.
### Syntax
```sql
DELETE FROM <measurement_name> WHERE [<tag_key>='<tag_value>'] | [<time interval>]
```
You must include either the [`FROM` clause](/influxdb/v2.5/query-data/influxql/explore-data/select/#from-clause), the [`WHERE` clause](/influxdb/v2.5/query-data/influxql/explore-data/where/), or both.
{{% note %}}
- `DELETE` supports [regular expressions](/influxdb/v2.5/query-data/influxql/explore-data/regular-expressions/)
in the `FROM` clause when specifying measurement names and in the `WHERE` clause
when specifying tag values.
- `DELETE` does not support [fields](/influxdb/v2.5/reference/glossary/#field) in the `WHERE` clause.
{{% /note %}}
### Examples
- [Delete all measurement data](#delete-all-measurement-data)
- [Delete data in a measurement that has a specific tag value](#delete-data-in-a-measurement-that-has-a-specific-tag-value)
- [Delete data before or after specified time](#delete-data-before-or-after-specified-time)
#### Delete all measurement data
Delete all data associated with the measurement `h2o_feet`:
```sql
DELETE FROM "h2o_feet"
```
#### Delete data in a measurement that has a specific tag value
Delete all data associated with the measurement `h2o_quality` and where the tag `randtag` equals `3`:
```sql
DELETE FROM "h2o_quality" WHERE "randtag" = '3'
```
#### Delete data before or after specified time
Delete all data in the database that occur before January 01, 2020:
```sql
DELETE WHERE time < '2020-01-01'
```
A successful `DELETE` query returns an empty result.
If you need to delete points in the future, you must specify the future time period because `DELETE SERIES` runs for `time < now()` by default.
Delete future points:
```sql
DELETE FROM device_data WHERE "device" = 'sensor1" and time > now() and < '2024-01-14T01:00:00Z'
```
Delete points in the future within a specified time range:
```sql
DELETE FROM device_data WHERE "device" = 'sensor15" and time >= '2024-01-01T12:00:00Z' and <= '2025-06-30T11:59:00Z'
```
## Delete measurements with DROP MEASUREMENT
The `DROP MEASUREMENT` statement deletes all data and series from the specified [measurement](/influxdb/v2.5/reference/glossary/#measurement) and deletes the measurement from the index.
#### Syntax
```sql
DROP MEASUREMENT <measurement_name>
```
#### Example
Delete the measurement `h2o_feet`:
```sql
DROP MEASUREMENT "h2o_feet"
```
A successful `DROP MEASUREMENT` query returns an empty result.
{{% warn %}}
The DROP MEASURMENT command is very resource intensive. We do not recommend this command for bulk data deletion. Use the DELETE FROM command instead, which is less resource intensive.
{{% /warn %}}

View File

@ -0,0 +1,318 @@
---
title: InfluxQL mathematical operators
descriptions: >
Use InfluxQL mathematical operators to perform mathematical operations in queries.
menu:
influxdb_2_5:
name: Mathematical operators
parent: Query with InfluxQL
identifier: influxql-mathematical-operators
weight: 209
---
Use InfluxQL mathematical operators to perform mathematical operations in 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)
- [Common Issues with Mathematical Operators](#common-issues-with-mathematical-operators)
## Addition
Perform addition with a constant.
```sql
SELECT "A" + 5 FROM "add"
```
```sql
SELECT * FROM "add" WHERE "A" + 5 > 10
```
Perform addition on two fields.
```sql
SELECT "A" + "B" FROM "add"
```
```sql
SELECT * FROM "add" WHERE "A" + "B" >= 10
```
## Subtraction
Perform subtraction with a constant.
```sql
SELECT 1 - "A" FROM "sub"
```
```sql
SELECT * FROM "sub" WHERE 1 - "A" <= 3
```
Perform subtraction with two fields.
```sql
SELECT "A" - "B" FROM "sub"
```
```sql
SELECT * FROM "sub" WHERE "A" - "B" <= 1
```
## Multiplication
Perform multiplication with a constant.
```sql
SELECT 10 * "A" FROM "mult"
```
```sql
SELECT * FROM "mult" WHERE "A" * 10 >= 20
```
Perform multiplication with two fields.
```sql
SELECT "A" * "B" * "C" FROM "mult"
```
```sql
SELECT * FROM "mult" WHERE "A" * "B" <= 80
```
Multiplication distributes across other operators.
```sql
SELECT 10 * ("A" + "B" + "C") FROM "mult"
```
```sql
SELECT 10 * ("A" - "B" - "C") FROM "mult"
```
```sql
SELECT 10 * ("A" + "B" - "C") FROM "mult"
```
## Division
Perform division with a constant.
```sql
SELECT 10 / "A" FROM "div"
```
```sql
SELECT * FROM "div" WHERE "A" / 10 <= 2
```
Perform division with two fields.
```sql
SELECT "A" / "B" FROM "div"
```
```sql
SELECT * FROM "div" WHERE "A" / "B" >= 10
```
Division distributes across other operators.
```sql
SELECT 10 / ("A" + "B" + "C") FROM "mult"
```
## Modulo
Perform modulo arithmetic with a constant.
```sql
SELECT "B" % 2 FROM "modulo"
```
```sql
SELECT "B" FROM "modulo" WHERE "B" % 2 = 0
```
Perform modulo arithmetic on two fields.
```sql
SELECT "A" % "B" FROM "modulo"
```
```sql
SELECT "A" FROM "modulo" WHERE "A" % "B" = 0
```
## Bitwise AND
You can use this operator with any integers or Booleans, whether they are fields or constants.
It does not work with float or string datatypes, and you cannot mix integers and Booleans.
```sql
SELECT "A" & 255 FROM "bitfields"
```
```sql
SELECT "A" & "B" FROM "bitfields"
```
```sql
SELECT * FROM "data" WHERE "bitfield" & 15 > 0
```
```sql
SELECT "A" & "B" FROM "booleans"
```
```sql
SELECT ("A" ^ true) & "B" FROM "booleans"
```
## Bitwise OR
You can use this operator with any integers or Booleans, whether they are fields or constants.
It does not work with float or string datatypes, and you cannot mix integers and Booleans.
```sql
SELECT "A" | 5 FROM "bitfields"
```
```sql
SELECT "A" | "B" FROM "bitfields"
```
```sql
SELECT * FROM "data" WHERE "bitfield" | 12 = 12
```
## Bitwise Exclusive-OR
You can use this operator with any integers or Booleans, whether they are fields or constants.
It does not work with float or string datatypes, and you cannot mix integers and Booleans.
```sql
SELECT "A" ^ 255 FROM "bitfields"
```
```sql
SELECT "A" ^ "B" FROM "bitfields"
```
```sql
SELECT * FROM "data" 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 tokens in InfluxQL.
However, you can apply the bitwise operators `&`, `|` and `^` to boolean data.
### 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 to you 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 "data"
```
For 16-bit data:
```sql
SELECT "A" ^ 65535 FROM "data"
```
For 32-bit data:
```sql
SELECT "A" ^ 4294967295 FROM "data"
```
In each case the constant you need can be calculated as `(2 ** width) - 1`.
## Common Issues with 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
InfluxDB does not support combining mathematical operations with a wildcard (`*`) or [regular expression](/influxdb/v2.5/query-data/influxql/explore-data/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
The use of mathematical operators inside of function calls is currently unsupported.
Note that InfluxDB 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.5/query-data/influxql/explore-data/subqueries/) which offer similar functionality to using mathematical operators inside a function call.
{{% /note %}}

View File

@ -51,6 +51,7 @@ weight: 9
- [What are the minimum and maximum integers that InfluxDB can store?](#what-are-the-minimum-and-maximum-integers-that-influxdb-can-store)
- [What are the minimum and maximum timestamps that InfluxDB can store?](#what-are-the-minimum-and-maximum-timestamps-that-influxdb-can-store)
- [Can I change a field's data type?](#can-i-change-a-fields-data-type)
- {{% oss-only %}}[How does InfluxDB handle field type discrepancies across shards?](#how-does-influxdb-handle-field-type-discrepancies-across-shards){{% /oss-only %}}
##### Writing data {href="writing-data"}
- [How do I write integer and unsigned integer field values?](#how-do-i-write-integer-and-unsigned-integer-field-values)
@ -413,6 +414,81 @@ Below are some possible workarounds:
|> to(bucket: "example-bucket-2")
```
#### How does InfluxDB handle field type discrepancies across shards?
Field values can be floats, integers, strings, or Booleans.
Field value types cannot differ within a
[shard](/enterprise_influxdb/v1.10/concepts/glossary/#shard), but they can [differ](/enterprise_influxdb/v1.10/write_protocols/line_protocol_reference) across shards.
The
[`SELECT` statement](/enterprise_influxdb/v1.10/query_language/explore-data/#the-basic-select-statement)
returns all field values **if** all values have the same type.
If field value types differ across shards, InfluxDB first performs any
applicable [cast](/enterprise_influxdb/v1.10/query_language/explore-data/#cast-operations)
operations and then returns all values with the type that occurs first in the
following list: float, integer, string, Boolean.
If your data have field value type discrepancies, use the syntax
`<field_key>::<type>` to query the different data types.
#### Example
The measurement `just_my_type` has a single field called `my_field`.
`my_field` has four field values across four different shards, and each value has
a different data type (float, integer, string, and Boolean).
`SELECT *` returns only the float and integer field values.
Note that InfluxDB casts the integer value to a float in the response.
```sql
SELECT * FROM just_my_type
name: just_my_type
------------------
time my_field
2016-06-03T15:45:00Z 9.87034
2016-06-03T16:45:00Z 7
```
`SELECT <field_key>::<type> [...]` returns all value types.
InfluxDB outputs each value type in its own column with incremented column names.
Where possible, InfluxDB casts field values to another type;
it casts the integer `7` to a float in the first column, and it
casts the float `9.879034` to an integer in the second column.
InfluxDB cannot cast floats or integers to strings or Booleans.
```sql
SELECT "my_field"::float,"my_field"::integer,"my_field"::string,"my_field"::boolean FROM just_my_type
name: just_my_type
------------------
time my_field my_field_1 my_field_2 my_field_3
2016-06-03T15:45:00Z 9.87034 9
2016-06-03T16:45:00Z 7 7
2016-06-03T17:45:00Z a string
2016-06-03T18:45:00Z true
```
`SHOW FIELD KEYS` returns every data type, across every shard, associated with
the field key.
#### Example
The measurement `just_my_type` has a single field called `my_field`.
`my_field` has four field values across four different shards, and each value has
a different data type (float, integer, string, and Boolean).
`SHOW FIELD KEYS` returns all four data types:
```sql
> SHOW FIELD KEYS
name: just_my_type
fieldKey fieldType
-------- ---------
my_field float
my_field string
my_field integer
my_field boolean
```
---
## Writing data
@ -762,7 +838,7 @@ the default time range is `1677-09-21 00:12:43.145224194` UTC to [`now()`](/infl
To query data with timestamps that occur after `now()`, `SELECT` statements with
a `GROUP BY time()` clause must provide an alternative **upper** bound in the
[`WHERE` clause](/influxdb/v1.8/query_language/explore-data/#the-where-clause).
[`WHERE` clause](/influxdb/v2.5/query_language/explore-data/#the-where-clause).
For example:
```sql

View File

@ -285,11 +285,13 @@ For more information about different data types, see:
- [Flux](/influxdb/v2.5/reference/flux/language/types/)
- [InfluxDB](/influxdb/v2.5/reference/syntax/line-protocol/#data-types-and-format)
### database
#### database
In InfluxDB {{< current-version >}}, a database represents the InfluxDB instance as a whole.
In InfluxDB 1.x, a database represented a logical container for users, retention
policies, continuous queries, and time series data.
The InfluxDB 2.x equivalent of this concept is an InfluxDB [bucket](/influxdb/v2.4/reference/glossary/#bucket).
Related entries: [continuous query](#continuous-query-cq), <!-- [retention policy](#retention-policy-rp),--> [user](#user)
Related entries: [continuous query](#continuous-query-cq), [retention policy](#retention-policy-rp), [user](#user)
### date-time

View File

@ -0,0 +1,14 @@
---
title: InfluxQL syntax
list_title: InfluxQL
description: InfluxQL is an SQL-like query language for interacting with data in InfluxDB.
menu:
influxdb_2_5_ref:
parent: Syntax
name: InfluxQL
identifier: influxql-syntax
weight: 101
---
{{< children readmore=true hr=true >}}

View File

@ -0,0 +1,163 @@
---
title: InfluxQL internals reference
description: Read about the implementation of InfluxQL.
menu:
influxdb_2_5_ref:
name: InfluxQL internals
parent: influxql-syntax
weight: 106
---
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 provided 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, a statement
such as this:
```sql
SELECT MEAN(value) FROM cpu GROUP BY time(10m)
```
In this case, `MEAN(value)` is a `MeanIterator` wrapping an iterator from the
underlying shards. However, if we can add an additional iterator 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 trasverses 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 which do not need stronger sorting guarantees.
* Sorted Merge Iterator - This iterator also 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/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. It is resource
intensive so it 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 first
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,761 @@
---
title: Influx Query Language (InfluxQL) 2.x specification
description: Reference (spec) for Influx Query Language (InfluxQL) 2.x.
menu:
influxdb_2_5_ref:
name: InfluxQL 2.x specification
parent: influxql-syntax
aliases:
- /influxdb/v2.5/query_languages/spec/
weight: 103
---
InfluxQL is a SQL-like query language used to interact with InfluxDB and work with your times series data.
Find Influx Query Language (InfluxQL) definitions and details, including:
- [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.5/query-data/influxql/explore-data/)
- [Explore your schema with InfluxQL](/influxdb/v2.5/query-data/influxql/explore-schema/)
- [Database management](/influxdb/v2.5/query-data/influxql/manage-database/)
- [Query engine internals](/influxdb/v2.5/reference/syntax/influxql/internals/)
## Notation
The syntax is specified using Extended Backus-Naur Form ("EBNF").
EBNF is the same notation used in the [Go](http://golang.org) programming language specification,
which can be found [here](https://golang.org/ref/spec).
```
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 characters plus the underscore character _ (U+005F) is considered a letter.
Only decimal digits are supported.
```
letter = ascii_letter | "_" .
ascii_letter = "A" … "Z" | "a" … "z" .
digit = "0" … "9" .
```
### Identifiers
Identifiers are tokens which refer to [database](/influxdb/v2.5/reference/glossary/#database) names, [retention policy](/influxdb/v2.5/reference/glossary/#retention-policy-rp) names, [user](/influxdb/v2.5/reference/glossary/#user) names, [measurement](/influxdb/v2.5/reference/glossary/#measurement) names, [tag keys](/influxdb/v2.5/reference/glossary/#tag-key), and [field keys](/influxdb/v2.5/reference/glossary/#field-key).
The rules:
- double quoted identifiers can contain any unicode character other than a new line
- double quoted identifiers can contain escaped `"` characters (i.e., `\"`)
- double quoted identifiers can contain 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 keywords as an
[identifier](/influxdb/v2.5/reference/glossary/#identifier) you will need to
double quote that identifier in every query.
The keyword `time` is a special case.
`time` can be a
database name,
[measurement](/influxdb/v2.5/reference/glossary/#measurement) name,
[retention policy](/influxdb/v2.5/reference/glossary/#retention-policy-rp) name,
[subscription](/influxdb/v2.5/reference/glossary/#subscription) name, and
[user](/influxdb/v2.5/reference/glossary/#user) name.
In those cases, `time` does not require double quotes in queries.
`time` cannot be a [field key](/influxdb/v2.5/reference/glossary/#field-key) or
[tag key](/influxdb/v2.5/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.5/reference/faq/) for more information.
### Literals
#### Integers
InfluxQL supports decimal integer literals.
Hexadecimal and octal literals are not currently supported.
```
int_lit = ( "1" … "9" ) { digit } .
```
#### Floats
InfluxQL supports floating-point literals.
Exponents are not 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 a duration unit 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
The date and time literal format is not specified in EBNF like the rest of this document.
It is specified using Go's date / time parsing format, which is a reference date 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 %}}
**NOTE:** InfluxQL supports using regular expressions when specifying:
* [field keys](/influxdb/v2.5/reference/glossary/#field-key) and [tag keys](/influxdb/v2.5/reference/glossary/#tag-key) in the [`SELECT` clause](/influxdb/v2.5/query-data/influxql/explore-data/select/)
* [measurements](/influxdb/v2.5/reference/glossary/#measurement) in the [`FROM` clause](/influxdb/v2.5/query-data/influxql/explore-data/select/#from-clause)
* [tag values](/influxdb/v2.5/reference/glossary/#tag-value) and string [field values](/influxdb/v2.5/reference/glossary/#field-value) in the [`WHERE` clause](/influxdb/v2.5/query-data/influxql/explore-data/where/)
* [tag keys](/influxdb/v2.5/reference/glossary/#tag-key) in the [`GROUP BY` clause](/influxdb/v2.5/query-data/influxql/explore-data/group-by/)
Currently, InfluxQL does not support using regular expressions to match non-string field values in the `WHERE` clause, [databases](/influxdb/v2.5/reference/glossary/#database), and [retention polices](/influxdb/v2.5/reference/glossary/#retention-policy-rp).
{{% /note %}}
## Queries
A query is composed of one or more statements separated by a semicolon.
```
query = statement { ";" statement } .
statement = delete_stmt |
drop_measurement_stmt |
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
### DELETE
```
delete_stmt = "DELETE" ( from_clause | where_clause | from_clause where_clause ) .
```
#### Examples
```sql
DELETE FROM "cpu"
DELETE FROM "cpu" WHERE time < '2000-01-01T00:00:00Z'
DELETE WHERE time < '2000-01-01T00:00:00Z'
```
### DROP MEASUREMENT
```
drop_measurement_stmt = "DROP MEASUREMENT" measurement .
```
#### Examples
```sql
-- drop the cpu measurement
DROP MEASUREMENT "cpu"
```
### 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 does not support joins, the cost of a 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.
The elements of `EXPLAIN` query plan include:
- 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 on 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, executing 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'
```
May produce an output 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 is not accounted for.
##### 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 the executing the query. For example, the number of series keys required to execute a query affects how quickly the query is planned and the required memory.
First, InfluxDB determines the effective time range of the query and selects the shards to access (in InfluxDB Enterprise, shards may be on remote nodes).
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:
| `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 |
For more information about storage blocks, see [TSM files](/influxdb/v2.5/reference/internals/storage-engine/#time-structured-merge-tree-tsm).
### SELECT
```
select_stmt = "SELECT" fields from_clause [ where_clause ]
[ group_by_clause ] [ order_by_clause ] [ limit_clause ]
[ offset_clause ] [ slimit_clause ] [ soffset_clause ] [ timezone_clause ] .
```
#### Example
Select from measurements grouped by the day with a timezone
```sql
SELECT mean("value") FROM "cpu" GROUP BY region, time(1d) fill(0) tz('America/Chicago')
```
### SHOW CARDINALITY
Refers to the group of commands used to estimate or count exactly the cardinality of measurements, series, tag keys, tag key values, and field keys.
The SHOW CARDINALITY commands are available in two variations: estimated and exact. Estimated values are calculated using sketches and are a safe default for all cardinality sizes. Exact values are counts directly from TSM (Time-Structured Merge Tree) data, but are expensive to run for high cardinality data. Unless required, use the estimated variety.
Filtering by `time` is only supported when Time Series Index (TSI) is enabled on a database.
See the specific SHOW CARDINALITY commands for details:
- [SHOW FIELD KEY CARDINALITY](#show-field-key-cardinality)
- [SHOW SERIES CARDINALITY](#show-series-cardinality)
- [SHOW TAG KEY CARDINALITY](#show-tag-key-cardinality)
- [SHOW TAG VALUES CARDINALITY](#show-tag-values-cardinality)
### SHOW DATABASES
```
show_databases_stmt = "SHOW DATABASES" .
```
#### Example
```sql
-- show all databases
SHOW DATABASES
```
### SHOW FIELD KEY CARDINALITY
Estimates or counts exactly the cardinality of the field key set for the current database unless a database is specified using the `ON <database>` option.
> **Note:** `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 Time Series Index (TSI) is enabled and `time` is not supported in the `WHERE` clause.
```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
```
- [Series cardinality](/influxdb/v2.5/reference/glossary/#series-cardinality) is the major factor that affects RAM requirements. For more information, see:
- [Don't have too many series](/influxdb/v2.5/reference/faq/#why-does-series-cardinality-matter). As the number of unique series grows, so does the memory usage. High series cardinality can force the host operating system to kill the InfluxDB process with an out of memory (OOM) exception.
{{% 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.
```
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

@ -16,15 +16,16 @@ Use the `influx` command line interface (CLI) to create a user.
Additional users cannot be created in the InfluxDB UI.
{{% /note %}}
## Create a user using the influx CLI
To create a new user, use the [`influx user create` command](/influxdb/v2.5/reference/cli/influx/user/create)
and include the following:
To create a new user, you must have an [operator token](/influxdb/v2.5/reference/glossary/#token).
For more information, see how to [create an operator token](/influxdb/v2.5/security/tokens/create-token/#create-an-operator-token).
Use the [`influx user create` command](/influxdb/v2.5/reference/cli/influx/user/create) and include the following:
- Username
- Organization name or organization ID to add the user to _(provided in the output of
[`influx org list`](/influxdb/v2.5/reference/cli/influx/org/list/))_
{{< cli/influx-creds-note >}}
```sh
# Syntax
influx user create -n <username> -o <org-name>

View File

@ -0,0 +1,3 @@
<div class="influxql-table-meta">
{{ .Inner }}
</div>

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB