Skip to content

first()

Get the first value in one column when rows are ordered by another column

Since 0.0.11-beta

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

Get the earliest temperature by device_id:

SELECT device_id, first(temp, time)
FROM metrics
GROUP BY device_id;

This example uses first and last with an aggregate filter, and avoids null values in the output:

SELECT
TIME_BUCKET('5 MIN', time_column) AS interv,
AVG(temperature) as avg_temp,
first(temperature,time_column) FILTER(WHERE time_column IS NOT NULL) AS beg_temp,
last(temperature,time_column) FILTER(WHERE time_column IS NOT NULL) AS end_temp
FROM sensors
GROUP BY interv

The syntax is:

SELECT first(
value = <anyelement>,
time = <anyelement>
);
NameTypeDefaultRequiredDescription
valueANYELEMENT-The value to return
time”any”-The timestamp to use for comparison. Accepts any comparable type such as TIMESTAMPTZ, TIMESTAMP, INTEGER, or BIGINT.
ColumnTypeDescription
firstANY ELEMENTThe value from the value column corresponding to the earliest time within the aggregate group. The return type matches the value input type.