SQL: Traditional SQL powered by the Apache Arrow DataFusion
query engine. The supported SQL syntax is similar to PostgreSQL.
InfluxQL: An SQL-like query language designed to query time series data stored in InfluxDB.
This tutorial walks you through the fundamentals of querying data in InfluxDB and
focuses on using SQL to query your time series data.
The InfluxDB SQL implementation is built using Arrow Flight SQL,
a protocol for interacting with SQL databases using the Arrow in-memory format and the
Flight RPC framework.
It leverages the performance of Apache Arrow with
the simplicity of SQL.
Avoid using the /api/v2/query API endpoint and associated tooling, such as the influx query CLI command and InfluxDB v2 client libraries, with InfluxDB Cloud Serverless.
SQL query basics
The InfluxDB Cloud Serverless SQL implementation is powered by the Apache Arrow DataFusion
query engine which provides an SQL syntax similar to PostgreSQL.
This is a brief introduction to writing SQL queries for InfluxDB.
For more in-depth details, see Query data with SQL.
InfluxDB SQL queries most commonly include the following clauses:
* Required
*SELECT: Identify specific fields and tags to query from a
measurement or use the wildcard alias (*) to select all fields and tags
from a measurement.
*FROM: Identify the measurement to query.
If coming from an SQL background, an InfluxDB measurement is the equivalent
of a relational table.
WHERE: Only return data that meets defined conditions such as falling within
a time range, containing specific tag values, etc.
GROUP BY: Group data into SQL partitions and apply an aggregate or selector
function to each group.
-- Return the average temperature and humidity within time bounds from each room
SELECTavg(temp),avg(hum),roomFROMhomeWHEREtime>='2022-01-01T08:00:00Z'ANDtime<='2022-01-01T20:00:00Z'GROUPBYroom
Example SQL queries
Select all data in a measurement
SELECT*FROMhome
Select all data in a measurement within time bounds
Avoid using the /api/v2/query API endpoint in InfluxDB Cloud Serverless and associated tooling, such as the influx query CLI command and InfluxDB v2 client libraries.
You can’t use SQL or InfluxQL with these tools.
For this example, use the following query to select all the data written to the
get-started bucket between
2022-01-01T08:00:00Z and 2022-01-01T20:00:00Z.
In the schema browser on the left, select the get-started bucket from the
bucket drop-down menu.
The displayed measurements and fields are read-only and are meant to show
you the schema of data stored in the selected bucket.
The following steps include setting up a Python virtual environment already
covered in Get started writing data.
If your project’s virtual environment is already running, skip to step 3.
Create a directory for your project and change into it:
mkdir influx3-query-example &&cd$_
To create and activate a Python virtual environment, run the following command:
Enter the influx3 sql command and your SQL query statement.
influx3 sql "SELECT *
FROM home
WHERE time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'"
influx3 displays query results in your terminal.
Use the influxdb_client_3 client library module to integrate InfluxDB Cloud Serverless with your Python code.
The client library supports writing data to InfluxDB and querying data using SQL or InfluxQL.
The following steps include setting up a Python virtual environment already
covered in Get started writing data.
If your project’s virtual environment is already running, skip to step 3.
Open a terminal in the influxdb_py_client module directory you created in the
Write data section:
To create and activate your Python virtual environment, enter the following command in your terminal:
influxdb3-python*: Provides the InfluxDB influxdb_client_3 Python client library module and also installs the pyarrow package for working with Arrow data returned from queries.
pandas: Provides pandas functions, modules, and data structures for analyzing and manipulating data.
tabulate: Provides the tabulate function for formatting tabular data. pandas requires this module for formatting data as Markdown.
In your terminal, enter the following command:
pip install influxdb3-python pandas tabulate
In your terminal or editor, create a new file for your code–for example: query.py.
In query.py, enter the following sample code:
frominfluxdb_client_3importInfluxDBClient3client=InfluxDBClient3(host=f"cloud2.influxdata.com",token=f"API_TOKEN",database=f"get-started")sql='''
SELECT
*
FROM
home
WHERE
time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
'''table=client.query(query=sql)asserttable['room'],"Expect table to have room column."print(table.to_pandas().to_markdown())
Important: If using Windows, specify the Windows certificate path
When instantiating the client, Python looks for SSL/TLS certificate authority
(CA) certificates for verifying the server’s authenticity.
If using a non-POSIX-compliant operating system (such as Windows), you need to
specify a certificate bundle path that Python can access on your system.
The following example shows how to use the
Python certifi package and
client library options to provide a bundle of trusted certificates to the
Python Flight client:
In your terminal, install the Python certifi package.
pip install certifi
In your Python code, import certifi and call the certifi.where() method to retrieve the root certificate path.
When instantiating the client, pass the flight_client_options.tls_root_certs=<ROOT_CERT_PATH> option with the certificate path–for example:
token: an API token with read access to the specified bucket.
Store this in a secret store or environment variable to avoid exposing
the raw token string.
Defines the SQL query to execute and assigns it to a query variable.
Calls the client.query() method with the SQL query.
query() sends a
Flight request to InfluxDB, queries the database (bucket), retrieves result data from the endpoint, and then returns a
pyarrow.Table
assigned to the table variable.
Calls the print() method to print the markdown table to stdout.
In your terminal, enter the following command to run the program and query InfluxDB Cloud Serverless:
python query.py
View returned markdown table
co
hum
room
temp
time
0
0
35.9
Kitchen
21
2022-01-01 08:00:00
1
0
36.2
Kitchen
23
2022-01-01 09:00:00
2
0
36.1
Kitchen
22.7
2022-01-01 10:00:00
3
0
36
Kitchen
22.4
2022-01-01 11:00:00
4
0
36
Kitchen
22.5
2022-01-01 12:00:00
5
1
36.5
Kitchen
22.8
2022-01-01 13:00:00
6
1
36.3
Kitchen
22.8
2022-01-01 14:00:00
7
3
36.2
Kitchen
22.7
2022-01-01 15:00:00
8
7
36
Kitchen
22.4
2022-01-01 16:00:00
9
9
36
Kitchen
22.7
2022-01-01 17:00:00
10
18
36.9
Kitchen
23.3
2022-01-01 18:00:00
11
22
36.6
Kitchen
23.1
2022-01-01 19:00:00
12
26
36.5
Kitchen
22.7
2022-01-01 20:00:00
13
0
35.9
Living Room
21.1
2022-01-01 08:00:00
14
0
35.9
Living Room
21.4
2022-01-01 09:00:00
15
0
36
Living Room
21.8
2022-01-01 10:00:00
16
0
36
Living Room
22.2
2022-01-01 11:00:00
17
0
35.9
Living Room
22.2
2022-01-01 12:00:00
18
0
36
Living Room
22.4
2022-01-01 13:00:00
19
0
36.1
Living Room
22.3
2022-01-01 14:00:00
20
1
36.1
Living Room
22.3
2022-01-01 15:00:00
21
4
36
Living Room
22.4
2022-01-01 16:00:00
22
5
35.9
Living Room
22.6
2022-01-01 17:00:00
23
9
36.2
Living Room
22.8
2022-01-01 18:00:00
24
14
36.3
Living Room
22.5
2022-01-01 19:00:00
25
17
36.4
Living Room
22.2
2022-01-01 20:00:00
In the influxdb_go_client directory you created in the
Write data section,
create a new file named query.go.
In query.go, enter the following sample code:
packagemainimport("context""fmt""io""os""time""text/tabwriter""github.com/InfluxCommunity/influxdb3-go/influxdb3/v1")funcQuery()error{// INFLUX_TOKEN is an environment variable you created
// for your API read token.
token:=os.Getenv("INFLUX_TOKEN")// Instantiate the client.
client,err:=influxdb3.New(influxdb3.ClientConfig{Host:"https://cloud2.influxdata.com",Token:token,Database:"get-started",})// Close the client when the function returns.
deferfunc(client*influxdb3.Client){err:=client.Close()iferr!=nil{panic(err)}}(client)// Define the query.
query:=`SELECT *
FROM home
WHERE time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'`// Execute the query.
iterator,err:=client.Query(context.Background(),query)iferr!=nil{panic(err)}w:=tabwriter.NewWriter(io.Discard,4,4,1,' ',0)w.Init(os.Stdout,0,8,0,'\t',0)fmt.Fprintln(w,"time\troom\ttemp\thum\tco")// Iterate over rows and prints column values in table format.
foriterator.Next(){row:=iterator.Value()// Use Go time package to format unix timestamp
// as a time with timezone layout (RFC3339).
time:=(row["time"].(time.Time)).Format(time.RFC3339)fmt.Fprintf(w,"%s\t%s\t%d\t%.1f\t%.1f\n",time,row["room"],row["co"],row["hum"],row["temp"])}w.Flush()returnnil}
Defines a Query() function that does the following:
Instantiates influx.Client with InfluxDB credentials.
Host: your InfluxDB Cloud Serverless region URL
Database: The name of your InfluxDB Cloud Serverless bucket
Token: an API token with read permission on the specified bucket.
Store this in a secret store or environment variable to avoid
exposing the raw token string.
Defines a deferred function to close the client after execution.
Defines a string variable for the SQL query.
Calls the influxdb3.Client.Query(sql string) method and passes the
SQL string to query InfluxDB.
The Query(sql string) method returns an iterator for data in the
response stream.
Iterates over rows, formats the timestamp as an
RFC3339 timestamp,and prints the data in table format to stdout.
In your editor, open the main.go file you created in the
Write data section and insert code to call the Query() function–for example:
packagemainfuncmain(){WriteLineProtocol()Query()}
In your terminal, enter the following command to install the necessary
packages, build the module, and run the program:
go mod tidy && go run influxdb_go_client
The program executes the main() function that writes the data and prints the query results to the console.
This tutorial assumes you installed Node.js and npm, and created an influxdb_js_client npm project as described in the Write data section.
In your terminal or editor, change to the influxdb_js_client directory you created in the
Write data section.
If you haven’t already, install the @influxdata/influxdb3-client JavaScript client library as a dependency to your project:
npm install --save @influxdata/influxdb3-client
Create a file named query.mjs. The .mjs extension tells the Node.js interpreter that you’re using ES6 module syntax.
Inside of query.mjs, enter the following sample code:
// query.mjs
import{InfluxDBClient}from'@influxdata/influxdb3-client'import{tableFromArrays}from'apache-arrow';/**
* Set InfluxDB credentials.
*/consthost="https://cloud2.influxdata.com";constdatabase='get-started';/**
* INFLUX_TOKEN is an environment variable you assigned to your
* API READ token value.
*/consttoken=process.env.INFLUX_TOKEN;/**
* Query InfluxDB with SQL using the JavaScript client library.
*/exportasyncfunctionquerySQL(){/**
* Instantiate an InfluxDBClient
*/constclient=newInfluxDBClient({host,token})constsql=`
SELECT *
FROM home
WHERE time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
`constdata={time:[],room:[],co:[],hum:[],temp:[]};constresult=client.query(query,database);forawait(constrowofresult){data.time.push(newDate(row._time))data.room.push(row.room)data.co.push(row.co);data.hum.push(row.hum);data.temp.push(row.temp);}console.table([...tableFromArrays(data)])client.close()}
The sample code does the following:
Imports the following:
InfluxDBClient class
tableFromArrays function
Calls new InfluxDBClient() and passes a ClientOptions object to instantiate a client configured
with InfluxDB credentials.
host: your InfluxDB Cloud Serverless region URL
token: an API token
with read permission on the bucket you want to query.
Store this in a secret store or environment variable to avoid exposing
the raw token string.
Defines a string variable (sql) for the SQL query.
Defines an object (data) with column names for keys and array values for storing row data.
Calls the InfluxDBClient.query() method with the following arguments:
sql: the query to execute
database: the name of the InfluxDB Cloud Serverless bucket to query
query() returns a stream of row vectors.
Iterates over rows and adds the column data to the arrays in data.
Passes data to the Arrow tableFromArrays() function to format the arrays as a table, and then passes the result to the console.table() method to output a highlighted table in the terminal.
Inside of index.mjs (created in the Write data section), enter the following sample code to import the modules and call the functions:
// index.mjs
import{writeLineProtocol}from"./write.mjs";import{querySQL}from"./query.mjs";/**
* Execute the client functions.
*/asyncfunctionmain(){/** Write line protocol data to InfluxDB. */awaitwriteLineProtocol();/** Query data from InfluxDB using SQL. */awaitquerySQL();}main();
In your terminal, execute index.mjs to write to and query InfluxDB Cloud Serverless:
node index.mjs
In the influxdb_csharp_client directory you created in the
Write data section,
create a new file named Query.cs.
In Query.cs, enter the following sample code:
// Query.csusingSystem;usingSystem.Threading.Tasks;usingInfluxDB3.Client;usingInfluxDB3.Client.Query;namespaceInfluxDBv3;publicclassQuery{/**
* Queries an InfluxDB database (bucket) using the C# .NET client
* library.
**/publicstaticasyncTaskQuerySQL(){/** INFLUX_TOKEN is an environment variable you assigned to your
* API READ token value.
**/string?token=System.Environment.GetEnvironmentVariable("INFLUX_TOKEN");/**
* Instantiate the InfluxDB client with credentials.
**/usingvarclient=newInfluxDBClient("https://cloud2.influxdata.com",token:token,database:database);conststringsql=@"
SELECT time, room, temp, hum, co
FROM home
WHERE time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
";Console.WriteLine("{0,-30}{1,-15}{2,-15}{3,-15}{4,-15}","time","room","co","hum","temp");awaitforeach(varrowinclient.Query(query:sql)){{/**
* Iterate over rows and print column values in table format.
* Format the timestamp as sortable UTC format.
*/Console.WriteLine("{0,-30:u}{1,-15}{4,-15}{3,-15}{2,-15}",row[0],row[1],row[2],row[3],row[4]);}}Console.WriteLine();}}
The sample code does the following:
Imports the following classes:
System
System.Threading.Tasks;
InfluxDB3.Client;
InfluxDB3.Client.Query;
Defines a Query class with a QuerySQL() method that does the following:
Calls the new InfluxDBClient() constructor to instantiate a client configured
with InfluxDB credentials.
host: your InfluxDB Cloud Serverless region URL.
token: an API token with read permission on the specified bucket.
Store this in a secret store or environment variable to avoid exposing the raw token string.
database: the name of the InfluxDB Cloud Serverless bucket to query
Defines a string variable for the SQL query.
Calls the InfluxDBClient.Query() method to send the query request with the SQL string.
Query() returns batches of rows from the response stream as a two-dimensional array–an array of rows in which each row is an array of values.
Iterates over rows and prints the data in table format to stdout.
In your editor, open the Program.cs file you created in the
Write data section and insert code to call the Query() function–for example:
To build and execute the program and query InfluxDB Cloud Serverless,
enter the following commands in your terminal:
dotnet run
This tutorial assumes using Maven version 3.9, Java version >= 15, and an influxdb_java_client Maven project created in the Write data section.
In your terminal or editor, change to the influxdb_java_client directory you created in the
Write data section.
Inside of the src/main/java/com/influxdbv3 directory, create a new file named Query.java.
In Query.java, enter the following sample code:
// Query.javapackagecom.influxdbv3;importcom.influxdb.v3.client.InfluxDBClient;importjava.util.stream.Stream;/**
* Queries an InfluxDB database (bucket) using the Java client
* library.
**/publicfinalclassQuery{privateQuery(){//not called}/**
* @throws Exception
*/publicstaticvoidquerySQL()throwsException{/**
* Query using SQL.
*//** Set InfluxDB credentials. **/finalStringhost="https://cloud2.influxdata.com";finalStringdatabase="get-started";/** INFLUX_TOKEN is an environment variable you assigned to your
* API READ token value.
**/finalchar[]token=(System.getenv("INFLUX_TOKEN")).toCharArray();try(InfluxDBClientclient=InfluxDBClient.getInstance(host,token,database)){Stringsql="""
SELECT time, room, temp, hum, co
FROM home
WHERE time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'""";StringlayoutHead="| %-16s | %-12s | %-6s | %-6s | %-6s |%n";System.out.printf("--------------------------------------------------------%n");System.out.printf(layoutHead,"time","room","co","hum","temp");System.out.printf("--------------------------------------------------------%n");Stringlayout="| %-16s | %-12s | %-6s | %.1f | %.1f |%n";try(Stream<Object[]>stream=client.query(sql)){stream.forEach(row->System.out.printf(layout,row[0],row[1],row[4],row[3],row[2]));}}}}
The sample code does the following:
Assigns the com.influxdbv3 package name (the Maven groupId).
Imports the following classes:
com.influxdb.v3.client.InfluxDBClient
java.util.stream.Stream
Defines a Query class with a querySQL() method that does the following:
Calls InfluxDBClient.getInstance() to instantiate a client configured
with InfluxDB credentials.
host: your InfluxDB Cloud Serverless region URL
database: the name of the InfluxDB Cloud Serverless bucket to write to
token: an API token with read access to the specified bucket.
Store this in a secret store or environment variable to avoid exposing the raw token string.
Defines a string variable (sql) for the SQL query.
Defines a Markdown table format layout for headings and data rows.
Calls the InfluxDBClient.query() method to send the query request with the SQL string.
query() returns a stream of rows.
Iterates over rows and prints the data in the specified layout to stdout.
In your editor, open the src/main/java/com/influxdbv3/App.java file and replace its contents with the following sample code:
// App.javapackagecom.influxdbv3;/**
* Execute the client functions.
*
*/publicclassApp{/**
* @param args
* @throws Exception
*/publicstaticvoidmain(finalString[]args)throwsException{// Write data to InfluxDB v3.Write.writeLineProtocol();// Run the SQL query.Query.querySQL();}}
The App, Write, and Query classes belong to the com.influxdbv3 package (your project groupId).
App defines a main() function that calls Write.writeLineProtocol() and Query.querySQL().
In your terminal or editor, use Maven to install dependencies and compile the project code–for example:
mvn compile
Set the --add-opens=java.base/java.nio=ALL-UNNAMED Java option for your environment.
The Apache Arrow Flight library requires this setting for access to the java.nio API package.
For example, enter the following command in your terminal:
Congratulations! You’ve learned the basics of querying data in InfluxDB with SQL.
For a deep dive into all the ways you can query InfluxDB Cloud Serverless, see the
Query data in InfluxDB section of documentation.
Thank you for being part of our community!
We welcome and encourage your feedback and bug reports for InfluxDB and this documentation.
To find support, use the following resources:
InfluxDB v3 enhancements and InfluxDB Clustered is now generally available
New capabilities, including faster query performance and management
tooling advance the InfluxDB v3 product line.
InfluxDB Clustered is now generally available.
InfluxDB v3 performance and features
The InfluxDB v3 product line has seen significant enhancements in query
performance and has made new management tooling available. These enhancements
include an operational dashboard to monitor the health of your InfluxDB cluster,
single sign-on (SSO) support in InfluxDB Cloud Dedicated, and new management
APIs for tokens and databases.
You are currently viewing documentation specific to InfluxDB Cloud
Serverless
powered by the v3 storage engine, which
offers different functionality than InfluxDB Cloud
powered by the TSM storage engine.