# Why is \`last\` Aggregation Slower than \`ORDER BY\` and \`LIMIT\`?

**URL:** <https://community.questdb.com/t/why-is-last-aggregation-slower-than-order-by-and-limit/41>\
**Category:** Community\
**Tags:** sql, question\
**Created:** [June 26, 2024, 6:18pm UTC](https://community.questdb.com/t/why-is-last-aggregation-slower-than-order-by-and-limit/41 "2024-06-26T18:18:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![system](https://canada1.discourse-cdn.com/flex004/uploads/questdb/original/1X/b6b1b349e598d0550947e63d7923a9d7df0279eb.png) [@system](https://community.questdb.com/u/system)\
**Post date:** [June 26, 2024, 6:18pm UTC](https://community.questdb.com/t/why-is-last-aggregation-slower-than-order-by-and-limit/41/1 "2024-06-26T18:18:07Z")

</div>

I’m getting a big difference in performance when selecting the most recent timestamp from a table in QuestDB using these two queries.

This query takes ~46ms.

```auto
SELECT timestamp FROM <table_name> ORDER BY timestamp DESC LIMIT 1

```

This one takes ~165ms.

```auto
SELECT last(timestamp) FROM <table_name>

```

Both queries return the same, but when using `last` is way slower. Am I missing something here?

---

<div class="post-metadata">

**Author:** ![nwoolmer](https://yyz2.discourse-cdn.com/flex004/user_avatar/community.questdb.com/nwoolmer/32/24_2.png) [@nwoolmer](https://community.questdb.com/u/nwoolmer)\
**Post date:** [June 26, 2024, 6:18pm UTC](https://community.questdb.com/t/why-is-last-aggregation-slower-than-order-by-and-limit/41/2 "2024-06-26T18:18:26Z")

</div>

The query with `ORDER BY` and `LIMIT` is highly optimized, especially when using the designated timestamp. Data in questdb tables is physically stored sorted by incremental timestamp, so we can efficiently retrieve the most recent entry.

The `last` aggregation function is internally treated as a `GROUP BY`, so it needs to do a full scan to get the last value. At the moment QuestDB has no optimisations for no-op cases (i.e. when there is no meaningful aggregation). For those queries, you are better off rewriting with an alternative like you did.

By the way, QuestDB accepts a negative limit, so you can do

```auto
SELECT timestamp FROM <table_name> LIMIT -1

```

To access the last row, as data is sorted by incremental designated timestamp.

There is a related [issue on GitHub to optimize First and Last aggregate functions](https://github.com/questdb/questdb/issues/4231) automatically, but at the moment your best option is a query rewrite
