Documentation

Query first and last values

See the equivalent InfluxDB v2 documentation: Query first and last values.

Use the first() or last() functions to return the first or last record in an input table.

data
    |> first()

// OR

data
    |> last()

By default, InfluxDB returns results sorted by time, however you can use the sort() function to change how results are sorted. first() and last() respect the sort order of input data and return records based on the order they are received in.

first

first() returns the first non-null record in an input table.

Given the following input:

_time _value
2020-01-01T00:01:00Z 1.0
2020-01-01T00:02:00Z 1.0
2020-01-01T00:03:00Z 2.0
2020-01-01T00:04:00Z 3.0

The following function returns:

|> first()
_time _value
2020-01-01T00:01:00Z 1.0

last

last() returns the last non-null record in an input table.

Given the following input:

_time _value
2020-01-01T00:01:00Z 1.0
2020-01-01T00:02:00Z 1.0
2020-01-01T00:03:00Z 2.0
2020-01-01T00:04:00Z 3.0

The following function returns:

|> last()
_time _value
2020-01-01T00:04:00Z 3.0

Use first() or last() with aggregateWindow()

Use first() and last() with aggregateWindow() to select the first or last records in time-based groups. aggregateWindow() segments data into windows of time, aggregates data in each window into a single point using aggregate or selector functions, and then removes the time-based segmentation.

Given the following input:

_time _value
2020-01-01T00:00:00Z 10
2020-01-01T00:00:15Z 12
2020-01-01T00:00:45Z 9
2020-01-01T00:01:05Z 9
2020-01-01T00:01:10Z 15
2020-01-01T00:02:30Z 11

The following function returns:

|> aggregateWindow(
    every: 1h,
    fn: first,
)
_time _value
2020-01-01T00:00:59Z 10
2020-01-01T00:01:59Z 9
2020-01-01T00:02:59Z 11
|> aggregateWindow(
    every: 1h,
    fn: last,
)
_time _value
2020-01-01T00:00:59Z 9
2020-01-01T00:01:59Z 15
2020-01-01T00:02:59Z 11

Was this page helpful?

Thank you for your feedback!


The future of Flux

Flux is going into maintenance mode. You can continue using it as you currently are without any changes to your code.

Flux is going into maintenance mode and will not be supported in InfluxDB 3.0. This was a decision based on the broad demand for SQL and the continued growth and adoption of InfluxQL. We are continuing to support Flux for users in 1.x and 2.x so you can continue using it with no changes to your code. If you are interested in transitioning to InfluxDB 3.0 and want to future-proof your code, we suggest using InfluxQL.

For information about the future of Flux, see the following: