Query SQL data sources

The Flux sql package provides functions for working with SQL data sources. sql.from() lets you query SQL data sources like PostgreSQL, MySQL, Snowflake, SQLite, Microsoft SQL Server, Amazon Athena and Google BigQuery and use the results with InfluxDB dashboards, tasks, and other operations.

If you’re just getting started with Flux queries, check out the following:

Query a SQL data source

To query a SQL data source:

  1. Import the sql package in your Flux query
  2. Use the sql.from() function to specify the driver, data source name (DSN), and query used to query data from your SQL data source:

PostgreSQL MySQL Snowflake SQLite SQL Server Athena BigQuery

  1. import "sql"
  2. sql.from(
  3. driverName: "postgres",
  4. dataSourceName: "postgresql://user:password@localhost",
  5. query: "SELECT * FROM example_table",
  6. )
  1. import "sql"
  2. sql.from(
  3. driverName: "mysql",
  4. dataSourceName: "user:password@tcp(localhost:3306)/db",
  5. query: "SELECT * FROM example_table",
  6. )
  1. import "sql"
  2. sql.from(
  3. driverName: "snowflake",
  4. dataSourceName: "user:password@account/db/exampleschema?warehouse=wh",
  5. query: "SELECT * FROM example_table",
  6. )
  1. // NOTE: InfluxDB OSS and InfluxDB Cloud do not have access to
  2. // the local filesystem and cannot query SQLite data sources.
  3. // Use the Flux REPL to query an SQLite data source.
  4. import "sql"
  5. sql.from(
  6. driverName: "sqlite3",
  7. dataSourceName: "file:/path/to/test.db?cache=shared&mode=ro",
  8. query: "SELECT * FROM example_table",
  9. )
  1. import "sql"
  2. sql.from(
  3. driverName: "sqlserver",
  4. dataSourceName: "sqlserver://user:password@localhost:1234?database=examplebdb",
  5. query: "GO SELECT * FROM Example.Table",
  6. )

For information about authenticating with SQL Server using ADO-style parameters, see SQL Server ADO authentication.

  1. import "sql"
  2. sql.from(
  3. driverName: "awsathena",
  4. dataSourceName: "s3://myorgqueryresults/?accessID=12ab34cd56ef&region=region-name&secretAccessKey=y0urSup3rs3crEtT0k3n",
  5. query: "GO SELECT * FROM Example.Table",
  6. )

For information about parameters to include in the Athena DSN, see Athena connection string.

  1. import "sql"
  2. sql.from(
  3. driverName: "bigquery",
  4. dataSourceName: "bigquery://projectid/?apiKey=mySuP3r5ecR3tAP1K3y",
  5. query: "SELECT * FROM exampleTable",
  6. )

For information about authenticating with BigQuery, see BigQuery authentication parameters.

See the sql.from() documentation for information about required function parameters.

Join SQL data with data in InfluxDB

One of the primary benefits of querying SQL data sources from InfluxDB is the ability to enrich query results with data stored outside of InfluxDB.

Using the air sensor sample data below, the following query joins air sensor metrics stored in InfluxDB with sensor information stored in PostgreSQL. The joined data lets you query and filter results based on sensor information that isn’t stored in InfluxDB.

  1. // Import the "sql" package
  2. import "sql"
  3. // Query data from PostgreSQL
  4. sensorInfo = sql.from(
  5. driverName: "postgres",
  6. dataSourceName: "postgresql://localhost?sslmode=disable",
  7. query: "SELECT * FROM sensors",
  8. )
  9. // Query data from InfluxDB
  10. sensorMetrics = from(bucket: "example-bucket")
  11. |> range(start: -1h)
  12. |> filter(fn: (r) => r._measurement == "airSensors")
  13. // Join InfluxDB query results with PostgreSQL query results
  14. join(tables: {metric: sensorMetrics, info: sensorInfo}, on: ["sensor_id"])

Use SQL results to populate dashboard variables

Use sql.from() to create dashboard variables from SQL query results. The following example uses the air sensor sample data below to create a variable that lets you select the location of a sensor.

  1. import "sql"
  2. sql.from(
  3. driverName: "postgres",
  4. dataSourceName: "postgresql://localhost?sslmode=disable",
  5. query: "SELECT * FROM sensors",
  6. )
  7. |> rename(columns: {location: "_value"})
  8. |> keep(columns: ["_value"])

Use the variable to manipulate queries in your dashboards.

Dashboard variable from SQL query results


Use secrets to store SQL database credentials

If your SQL database requires authentication, use InfluxDB secrets to store and populate connection credentials. By default, InfluxDB base64-encodes and stores secrets in its internal key-value store, BoltDB. For added security, store secrets in Vault.

Store your database credentials as secrets

Use the InfluxDB API or the influx CLI to store your database credentials as secrets.

InfluxDB API influx CLI

  1. curl --request PATCH http://localhost:8086/api/v2/orgs/<org-id>/secrets \
  2. --header 'Authorization: Token YOURAUTHTOKEN' \
  3. --header 'Content-type: application/json' \
  4. --data '{
  5. "POSTGRES_HOST": "http://example.com",
  6. "POSTGRES_USER": "example-username",
  7. "POSTGRES_PASS": "example-password"
  8. }'

To store secrets, you need:

  1. # Syntax
  2. influx secret update -k <secret-key>
  3. # Example
  4. influx secret update -k POSTGRES_PASS

When prompted, enter your secret value.

You can provide the secret value with the -v, --value flag, but the plain text secret may appear in your shell history.

  1. influx secret update -k <secret-key> -v <secret-value>

Use secrets in your query

Import the influxdata/influxdb/secrets package and use string interpolation to populate connection credentials with stored secrets in your Flux query.

  1. import "sql"
  2. import "influxdata/influxdb/secrets"
  3. POSTGRES_HOST = secrets.get(key: "POSTGRES_HOST")
  4. POSTGRES_USER = secrets.get(key: "POSTGRES_USER")
  5. POSTGRES_PASS = secrets.get(key: "POSTGRES_PASS")
  6. sql.from(
  7. driverName: "postgres",
  8. dataSourceName: "postgresql://${POSTGRES_USER}:${POSTGRES_PASS}@${POSTGRES_HOST}",
  9. query: "SELECT * FROM sensors",
  10. )

Sample sensor data

The air sensor sample data and sample sensor information simulate a group of sensors that measure temperature, humidity, and carbon monoxide in rooms throughout a building. Each collected data point is stored in InfluxDB with a sensor_id tag that identifies the specific sensor it came from. Sample sensor information is stored in PostgreSQL.

Sample data includes:

  • Simulated data collected from each sensor and stored in the airSensors measurement in InfluxDB:

    • temperature
    • humidity
    • co
  • Information about each sensor stored in the sensors table in PostgreSQL:

    • sensor_id
    • location
    • model_number
    • last_inspected

Download sample air sensor data

  1. Create a bucket to store the data.

  2. Create an InfluxDB task and use the sample.data() function to download sample air sensor data every 15 minutes. Write the downloaded sample data to your new bucket:

    1. import "influxdata/influxdb/sample"
    2. option task = {name: "Collect sample air sensor data", every: 15m}
    3. sample.data(set: "airSensor")
    4. |> to(org: "example-org", bucket: "example-bucket")
  3. Query your target bucket after the first task run to ensure the sample data is writing successfully.

    1. from(bucket: "example-bucket")
    2. |> range(start: -1m)
    3. |> filter(fn: (r) => r._measurement == "airSensors")

Import the sample sensor information

  1. Download and install PostgreSQL.

  2. Download the sample sensor information CSV.

    Download sample sensor information

  3. Use a PostgreSQL client (psql or a GUI) to create the sensors table:

    1. CREATE TABLE sensors (
    2. sensor_id character varying(50),
    3. location character varying(50),
    4. model_number character varying(50),
    5. last_inspected date
    6. );
  4. Import the downloaded CSV sample data. Update the FROM file path to the path of the downloaded CSV sample data.

    1. COPY sensors(sensor_id,location,model_number,last_inspected)
    2. FROM '/path/to/sample-sensor-info.csv' DELIMITER ',' CSV HEADER;
  5. Query the table to ensure the data was imported correctly:

    1. SELECT * FROM sensors;

Import the sample data dashboard

Download and import the Air Sensors dashboard to visualize the generated data:

View Air Sensors dashboard JSON

For information about importing a dashboard, see Create a dashboard.

query flux sql