last()

The last aggregate allows you to get the value of one column as ordered by another. For example, last(temperature, time) will return the latest temperature value based on time within an aggregate group.

Required Arguments

NameDescription
valueThe value to return (anyelement)
timeThe timestamp to use for comparison (TIMESTAMP/TIMESTAMPTZ or integer type)

Sample Usage

Get the temperature every 5 minutes for each device over the past day:

  1. SELECT device_id, time_bucket('5 minutes', time) AS interval,
  2. last(temp, time)
  3. FROM metrics
  4. WHERE time > now () - INTERVAL '1 day'
  5. GROUP BY device_id, interval
  6. ORDER BY interval DESC;

WARNING:The last and first commands do not use indexes, and instead perform a sequential scan through their groups. They are primarily used for ordered selection within a GROUP BY aggregate, and not as an alternative to an ORDER BY time DESC LIMIT 1 clause to find the latest value (which will use indexes).