Обсуждение: How to select the last value/row?

Поиск
Список
Период
Сортировка

How to select the last value/row?

От
Shaozhong SHI
Дата:
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

Re: How to select the last value/row?

От
"David G. Johnston"
Дата:
On Thu, Jul 6, 2023 at 8:47 AM Shaozhong SHI <shishaozhong@gmail.com> wrote:
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?

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

David J.

Re: How to select the last value/row?

От
Shaozhong SHI
Дата:


On Thu, 6 Jul 2023 at 16:51, David G. Johnston <david.g.johnston@gmail.com> wrote:
On Thu, Jul 6, 2023 at 8:47 AM Shaozhong SHI <shishaozhong@gmail.com> wrote:
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?

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

David J.


How about 
ID
5
4
3
3
2
3

The last is 3.

Regards,

David 

Re: How to select the last value/row?

От
"David G. Johnston"
Дата:
On Thu, Jul 6, 2023 at 9:02 AM Shaozhong SHI <shishaozhong@gmail.com> wrote:

How about 
ID
5
4
3
3
2
3

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.

Re: How to select the last value/row?

От
Tom Lane
Дата:
Shaozhong SHI <shishaozhong@gmail.com> writes:
> How about
> ID
> 5
> 4
> 3
> 3
> 2
> 3

> 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