Compare values in SQL queries
Use SQL window functions to compare values across different rows in your time series data.
Window functions like LAG and LEAD let you access values from previous or subsequent rows without using self-joins, making it easy to calculate changes over time.
Common use cases for comparing values include:
- Calculating the difference between the current value and a previous value
- Computing rate of change or percentage change
- Detecting significant changes or anomalies
- Comparing values at specific time intervals
- Handling counter metrics that reset to zero
To compare values across rows:
- Use a window function such as
LAGorLEADwith anOVERclause. - Include a
PARTITION BYclause to group data by tags (likeroomorsensor_id). - Include an
ORDER BYclause to define the order for comparisons (typically bytime). - Use arithmetic operators to calculate differences, ratios, or percentage changes.
Examples of comparing values
Sample data
The following examples use the Get started home sensor sample data. To run the example queries and return results, write the sample data to your InfluxDB Cloud Serverless database before running the example queries.
- Calculate the difference from the previous value
- Calculate the percentage change
- Compare values at regular intervals
- Compare values with exact time offsets
- Handle counter metrics and resets
Calculate the difference from the previous value
Use the LAG function to access the value from the previous row and calculate the difference.
This is useful for detecting changes over time.
The first row in each partition returns NULL for temp_change because there’s no previous value.
To use a default value instead of NULL, provide a third argument to LAG:
LAG(temp, 1, 0) -- Returns 0 if no previous value existsCalculate the percentage change
Calculate the percentage change between the current value and a previous value by dividing the difference by the previous value.
Compare values at regular intervals
For regularly spaced time series data (like hourly readings), use LAG with an offset parameter to compare values from a specific number of rows back.
The following query compares each temperature reading with the reading from one hour earlier (assuming hourly data):
Compare values with exact time offsets
For irregularly spaced time series data or when you need to compare values from an exact time offset (like exactly 1 hour ago, not just the previous row), use a self-join with interval arithmetic.
This self-join approach works when:
- Your data points don’t fall at regular intervals
- You need to compare against a specific time offset regardless of when the previous data point occurred
- You want to ensure the comparison is against a value from exactly 1 hour ago (or any other specific interval)
Handle counter metrics and resets
Counter metrics track cumulative values that increase over time, such as total requests, bytes transferred, or errors. Unlike gauge metrics (which can go up or down), counters typically only increase, though they may reset to zero when a service restarts.
Use GREATEST with LAG to handle counter resets by treating negative differences as zero.
InfluxDB 3 SQL and counter metrics
InfluxDB 3 SQL doesn’t provide built-in equivalents to Flux’s increase()
or InfluxQL’s NON_NEGATIVE_DIFFERENCE() functions.
Use the patterns shown below to achieve similar results.
Calculate non-negative differences (counter rate)
Calculate the increase between consecutive counter readings, treating negative differences (counter resets) as zero.
LAG(requests) retrieves the previous counter value, requests - LAG(requests) calculates the difference, and GREATEST(..., 0) returns 0 for negative differences (counter resets).
PARTITION BY host ensures comparisons are only within the same host.
Calculate cumulative counter increase
Calculate the total increase in a counter over time, handling resets. Use a Common Table Expression (CTE) to first calculate the differences, then sum them.
The CTE computes non-negative differences for each row, then SUM(requests_increase) OVER (...) creates a running total.
The cumulative increase continues to grow despite the counter reset at 03:00.
Aggregate counter increases by time interval
Calculate the total increase in a counter for each time interval (for example, hourly totals).
The CTE calculates differences for each row.
DATE_BIN() assigns each timestamp to a 1-hour interval, SUM(requests_increase) aggregates all increases within each interval, and WHERE requests_increase > 0 filters out zero increases (first row and counter resets).
Was this page helpful?
Thank you for your feedback!
Support and feedback
Thank you for being part of our community! We welcome and encourage your feedback and bug reports for InfluxDB Cloud Serverless and this documentation. To find support, use the following resources:
Customers with an annual or support contract can contact InfluxData Support.