Back to Influxdb

Order By

content/shared/influxql-v3-reference/order-by.md

latest2.6 KB
Original Source

Use the ORDER BY clause to sort data by time in ascending or descending order. InfluxQL only supports sorting data by time.

Syntax

sql
SELECT_clause FROM_clause [WHERE_clause] [GROUP_BY_clause] ORDER BY time [ASC|DESC]
  • If the the ORDER BY clause is not included, the default behavior is to sort data by time in ascending order: ORDER BY time ASC.
  • If the query includes WHERE and GROUP BY clauses, the ORDER BY clause must come after these clauses.

Sort orders

  • ASC (ascending): The first row in the results has the oldest timestamp. The last row in the results has the most recent timestamp.
  • DESC (descending): The first row in the results has the most recent timestamp. The last row in the results has the oldest timestamp.

Examples

The following examples use the Home sensor sample data.

{{< expand-wrapper >}}

{{% expand "Sort data with the oldest points first" %}}

[!Tip] Ordering data by time in ascending order is the default behavior. Including ORDER BY time ASC in the query isn't necessary, but it is supported.

{{% influxdb/custom-timestamps %}}

sql
SELECT *
FROM home
WHERE
  room = 'Kitchen'
  AND time >= '2022-01-01T08:00:00Z'
  AND time <= '2022-01-01T12:00:00Z'
ORDER BY time ASC

{{% influxql/table-meta %}} Name: home {{% /influxql/table-meta %}}

timecohumroomtemp
2022-01-01T08:00:00Z035.9Kitchen21
2022-01-01T09:00:00Z036.2Kitchen23
2022-01-01T10:00:00Z036.1Kitchen22.7
2022-01-01T11:00:00Z036Kitchen22.4
2022-01-01T12:00:00Z036Kitchen22.5

{{% /influxdb/custom-timestamps %}} {{% /expand %}}

{{% expand "Sort data with the newest points first" %}}

{{% influxdb/custom-timestamps %}}

sql
SELECT *
FROM home
WHERE
  room = 'Kitchen'
  AND time >= '2022-01-01T08:00:00Z'
  AND time <= '2022-01-01T12:00:00Z'
ORDER BY time DESC
timecohumroomtemp
2022-01-01T12:00:00Z036Kitchen22.5
2022-01-01T11:00:00Z036Kitchen22.4
2022-01-01T10:00:00Z036.1Kitchen22.7
2022-01-01T09:00:00Z036.2Kitchen23
2022-01-01T08:00:00Z035.9Kitchen21

{{% /influxdb/custom-timestamps %}} {{% /expand %}}

{{< /expand-wrapper >}}