> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# How to keep the latest row per group: materialized view versus projection

> Get the latest row for each key with LIMIT BY or argMax, then precompute it with an AggregatingMergeTree materialized view or with an aggregate projection.

To get the latest row for each key (a "last point" query), use `LIMIT 1 BY` or the [`argMax`](https://clickhouse.com/docs/reference/functions/aggregate-functions/argMax) aggregate function. Both read every row of the table. To avoid that, keep the `argMax` states precomputed, either in an [`AggregatingMergeTree`](https://clickhouse.com/docs/reference/engines/table-engines/mergetree-family/aggregatingmergetree) table filled by a materialized view, or in an aggregate projection of the source table. Both store the same states. They differ in how you define, query and maintain them.

## Example data

```sql theme={null}
CREATE TABLE device_status
(
    device_id UInt32,
    updated_at DateTime,
    status String,
    battery UInt8
)
ENGINE = MergeTree
ORDER BY (device_id, updated_at);

INSERT INTO device_status VALUES
    (1, '2026-01-01 10:00:00', 'online', 90),
    (1, '2026-01-01 11:00:00', 'idle', 85),
    (1, '2026-01-01 12:00:00', 'online', 80),
    (2, '2026-01-01 10:30:00', 'online', 60),
    (2, '2026-01-01 11:30:00', 'offline', 55);
```

## Compute the latest row at query time

[`LIMIT 1 BY`](https://clickhouse.com/docs/reference/statements/select/limit-by) keeps the first row of each group in the order given by `ORDER BY`:

```sql theme={null}
SELECT *
FROM device_status
ORDER BY device_id ASC, updated_at DESC
LIMIT 1 BY device_id;
```

```text theme={null}
   ┌─device_id─┬──────────updated_at─┬─status──┬─battery─┐
1. │         1 │ 2026-01-01 12:00:00 │ online  │      80 │
2. │         2 │ 2026-01-01 11:30:00 │ offline │      55 │
   └───────────┴─────────────────────┴─────────┴─────────┘
```

For columns that are not `Nullable`, an aggregation gives the same result: `argMax(status, updated_at)` returns the `status` of the row with the largest `updated_at`:

```sql theme={null}
SELECT
    device_id,
    max(updated_at) AS last_updated_at,
    argMax(status, updated_at) AS last_status,
    argMax(battery, updated_at) AS last_battery
FROM device_status
GROUP BY device_id
ORDER BY device_id;
```

```text theme={null}
   ┌─device_id─┬─────last_updated_at─┬─last_status─┬─last_battery─┐
1. │         1 │ 2026-01-01 12:00:00 │ online      │           80 │
2. │         2 │ 2026-01-01 11:30:00 │ offline     │           55 │
   └───────────┴─────────────────────┴─────────────┴──────────────┘
```

Three things to know about this query:

* `argMax` skips the rows in which its first argument is `NULL`, so with `Nullable` columns the values of one result row can come from different source rows. If `status` were `Nullable(String)` and the latest row of a device had `NULL` in it, `argMax(status, updated_at)` would return the `status` of an older row, next to the `battery` of the latest one. To take all values from the same row, pass them as one tuple, for example `argMax((status, battery), updated_at)`: the tuple itself is not `NULL`, so the row is not skipped and the `NULL` inside it is returned. The states that the materialized view and the projection below store behave in the same way.
* If several rows of a group share the largest `updated_at`, the row that `argMax` picks is not deterministic. To break ties, pass a tuple as the second argument, for example `argMax(status, (updated_at, battery))`.
* Give the results names that differ from the source columns. With `max(updated_at) AS updated_at` in the same query, `updated_at` inside `argMax` refers to the alias, and the query fails with `Aggregate function max(updated_at) AS updated_at is found inside another aggregate function in query. (ILLEGAL_AGGREGATION)`. The setting [`prefer_column_name_to_alias`](https://clickhouse.com/docs/reference/settings/session-settings/prefer#prefer_column_name_to_alias) changes this rule.

## Precompute with a materialized view

Create a target table that stores aggregate function states, and a materialized view that writes them with the [`-State`](https://clickhouse.com/docs/reference/functions/aggregate-functions/combinators#-state) combinator:

```sql theme={null}
CREATE TABLE device_status_latest
(
    device_id UInt32,
    last_updated_at SimpleAggregateFunction(max, DateTime),
    last_status AggregateFunction(argMax, String, DateTime),
    last_battery AggregateFunction(argMax, UInt8, DateTime)
)
ENGINE = AggregatingMergeTree
ORDER BY device_id;

CREATE MATERIALIZED VIEW device_status_latest_mv TO device_status_latest AS
SELECT
    device_id,
    max(updated_at) AS last_updated_at,
    argMaxState(status, updated_at) AS last_status,
    argMaxState(battery, updated_at) AS last_battery
FROM device_status
GROUP BY device_id;
```

The view only sees rows inserted after it was created, so [backfill](https://clickhouse.com/docs/guides/clickhouse/data-modelling/backfilling.md) the existing rows with the same `SELECT`. Because `max` and `argMax` return the same result when a row is counted twice, it does no harm if a row arrives through both the view and the backfill.

```sql theme={null}
INSERT INTO device_status_latest
SELECT
    device_id,
    max(updated_at) AS last_updated_at,
    argMaxState(status, updated_at) AS last_status,
    argMaxState(battery, updated_at) AS last_battery
FROM device_status
GROUP BY device_id;
```

New rows now update the target table. Read it with `GROUP BY` and the [`-Merge`](https://clickhouse.com/docs/reference/functions/aggregate-functions/combinators#-merge) combinator, because it holds several rows per `device_id` until background merges combine them:

```sql theme={null}
INSERT INTO device_status VALUES
    (2, '2026-01-01 12:30:00', 'online', 50),
    (3, '2026-01-01 12:45:00', 'online', 100);

SELECT
    device_id,
    max(last_updated_at) AS updated_at,
    argMaxMerge(last_status) AS status,
    argMaxMerge(last_battery) AS battery
FROM device_status_latest
GROUP BY device_id
ORDER BY device_id;
```

```text theme={null}
   ┌─device_id─┬──────────updated_at─┬─status─┬─battery─┐
1. │         1 │ 2026-01-01 12:00:00 │ online │      80 │
2. │         2 │ 2026-01-01 12:30:00 │ online │      50 │
3. │         3 │ 2026-01-01 12:45:00 │ online │     100 │
   └───────────┴─────────────────────┴────────┴─────────┘
```

## Precompute with a projection

A projection needs no second table and no backfill. [`MATERIALIZE PROJECTION`](https://clickhouse.com/docs/reference/statements/alter/projection#materialize-projection) builds it for the parts that already exist, and every later insert writes it together with the new part:

```sql theme={null}
ALTER TABLE device_status
    ADD PROJECTION latest_by_device
    (
        SELECT
            device_id,
            max(updated_at),
            argMax(status, updated_at),
            argMax(battery, updated_at)
        GROUP BY device_id
    );

ALTER TABLE device_status
    MATERIALIZE PROJECTION latest_by_device
    SETTINGS mutations_sync = 1;
```

A projection with `GROUP BY` stores aggregate function states, like the target table of the materialized view above. The [`system.projection_parts_columns`](https://clickhouse.com/docs/reference/system-tables/projection_parts_columns) table shows them: the column `argMax(status, updated_at)` of this projection has the type `AggregateFunction(argMax, String, DateTime)`.

You do not query a projection by name. Run the aggregation on the source table, and ClickHouse reads the projection when the query groups by the same key and only calls aggregate functions that the projection contains, with the same arguments:

```sql theme={null}
EXPLAIN
SELECT
    device_id,
    max(updated_at) AS last_updated_at,
    argMax(status, updated_at) AS last_status,
    argMax(battery, updated_at) AS last_battery
FROM device_status
GROUP BY device_id
ORDER BY device_id;
```

```text theme={null}
    ┌─explain──────────────────────────────────────────────────────────────────────────────────────────────┐
 1. │ Output: device_id, max(updated_at), argMax(status, updated_at), argMax(battery, updated_at)          │
 2. │                                                                                                      │
 3. │ Sorting (Sorting for ORDER BY)                                                                       │
 4. │ │  Sort description: device_id ASC                                                                   │
 5. │ └──Aggregating                                                                                       │
 6. │    │  Keys: device_id                                                                                │
 7. │    │  Aggregates: max(updated_at), argMax(status, updated_at), argMax(battery, updated_at)           │
 8. │    │  Skip merging: 0                                                                                │
 9. │    └──ReadFromMergeTree (latest_by_device)                                                           │
10. │          Read type: Default                                                                          │
11. │          Parts: 2 | Granules: 2                                                                      │
12. │          Output: device_id, max(updated_at), argMax(status, updated_at), argMax(battery, updated_at) │
    └──────────────────────────────────────────────────────────────────────────────────────────────────────┘
```

The layout of the plan depends on the version. The line to look for is `ReadFromMergeTree (latest_by_device)`, which names the projection instead of `default.device_status`. After the query has run, the `projections` column of [`system.query_log`](https://clickhouse.com/docs/reference/system-tables/query_log) lists the projection as well; see [How to confirm if a projection is used by the query](https://clickhouse.com/docs/resources/support-center/knowledge-base/materialized-views/projection-example.md). The `LIMIT 1 BY` query, or an aggregation with different arguments such as `argMax(status, (updated_at, battery))`, reads the base table instead.

## Which one to choose

* A projection is shorter to define, your queries stay unchanged, and it follows the source table: an `ALTER TABLE ... DELETE` mutation rebuilds it. A lightweight `DELETE` on a table with projections fails with `SUPPORT_IS_DISABLED` unless you change the `MergeTree` setting [`lightweight_mutation_projection_mode`](https://clickhouse.com/docs/reference/settings/merge-tree-settings/other#lightweight_mutation_projection_mode).
* The target of a materialized view is an ordinary table with its own sorting key, partitioning and TTL, and the view can filter or join before it aggregates. You have to backfill it and query it explicitly, and it does not change when rows of the source table are deleted or updated.

For the full comparison, see [Materialized views versus projections](https://clickhouse.com/docs/concepts/features/projections/materialized-views-versus-projections.md) and the [projections guide](https://clickhouse.com/docs/concepts/features/projections/projections.md).
