Subject: How to select the last value/row?

From: Shaozhong SHI <[email-masked]>
Date: Thu, 6 Jul 2023 16:46:55 +0100

Given,
ID
5
4
3
3
2
1

How to select the last one, to end up with

1

In Python, there are ways to handle ordered list.

In Postgres, is there something similar?

Regards,

David

---

From: "David G. Johnston" <[email-masked]>
Date: Thu, 6 Jul 2023 08:51:09 -0700

> In Postgres, is there something similar?

ORDER BY ASC so the "last item" appears first, then "LIMIT 1"

David J.

---

From: Shaozhong SHI <[email-masked]>
Date: Thu, 6 Jul 2023 17:02:40 +0100

> ORDER BY ASC so the "last item" appears first, then "LIMIT 1"

How about
ID
5
4
3
3
2
3

The last is 3.

Regards,

David

---

From: "David G. Johnston" <[email-masked]>
Date: Thu, 6 Jul 2023 09:09:36 -0700

> The last is 3.
There is no concept of "last" in a query unless you define an order.  If
you really want whatever row really happens to randomly show up in the last
result row the use the "row_number()" window function to give each row a
number and then sort and limit on that.

David J.

---

From: Tom Lane <[email-masked]>
Date: Thu, 06 Jul 2023 12:12:01 -0400

> The last is 3.

You need to reorient your thinking.  In SQL, row sets are unordered sets
of values --- this is not a Postgres deficiency, it's a fundamental tenet
of the relational data model.  If you want some kind of ordering, you have
to express that by an ORDER BY clause, which means you need something
within the data that corresponds to what you want the ordering to be.
Your example above is basically nonsense from the standpoint of SQL.

			regards, tom lane