Consolidate SQL reference docs (#5712)

* add source frontmatter for importing shared content

* update sql refrences docs to use shared source files

* updated note shortcodes to github-style alerts
pull/5714/head^2
Scott Anderson 2024-12-16 13:08:14 -07:00 committed by GitHub
parent 981683d1cb
commit f9ad60d7e2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
119 changed files with 10813 additions and 31156 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

11
content/shared/_index.md Normal file
View File

@ -0,0 +1,11 @@
---
title: Shared pages
cascade:
draft: true
---
This section is for content shared across multiple products and versions.
The `/shared` directory and all of its children are marked as draft so they
don't get rendered when the site is built, but the contents of each shared
documented is included in pages that use the file as a `source` in their
frontmatter.

View File

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

View File

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

View File

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

View File

@ -0,0 +1,3 @@
<!-- Comment to prevent error from starting with a shortcode -->
{{< children >}}

File diff suppressed because it is too large Load Diff

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

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