Re: Alternative to MS Access Last() function

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: Scott Ford <Scott(dot)Ford(at)bullfrogpower(dot)com>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: Alternative to MS Access Last() function
Date: 2006-03-01 19:25:18
Message-ID: 20060301192518.GA81805@winnie.fuhr.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

On Wed, Mar 01, 2006 at 01:31:28PM -0500, Scott Ford wrote:
> The LAST function returns the value of the last record in the specified
> field.

The term "last record" is ambiguous. In SQL a table has no particular
order; queries declare the order they want with an ORDER BY clause.
Which record will be "first" or "last" depends on what order the
query specifies.

> Example:
> SELECT LAST(Age) AS highest_age
> FROM Persons
> ORDER BY Age
> --------------
>
> So I think that I should just be able to use MAX(). Right?

For this example, yes, MAX looks equivalent.

SELECT MAX(age) AS highest_age FROM persons;

Another way to write this query is:

SELECT age AS highest_age FROM persons ORDER BY age DESC LIMIT 1;

In other words, order the table by age (descending) and return only
the first row (LIMIT 1) of the resulting row set. In versions of
PostgreSQL prior to 8.1 the second form is generally faster if the
table has an index on age (a lot faster if the table is large).

--
Michael Fuhr

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Michael Fuhr 2006-03-01 20:53:16 Re: delay of function
Previous Message Bruno Wolff III 2006-03-01 19:24:39 Re: Alternative to MS Access Last() function