pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: David Johnston <polobo@yahoo.com>
To: 'Carlos Mennens' <carlos.mennens@gmail.com>
To: 'PostgreSQL \(SQL\)' <pgsql-sql@postgresql.org>
Subject: Re: Finding Max Value in a Row
Date: Fri, 11 May 2012 15:20:16 -0400
Message-ID: <00ee01cd2fab$1b528b80$51f7a280$@yahoo.com> (raw)
In-Reply-To: <CAAQLLO6EhUi0OUi38BiH+qmgKqY+mY27_hGBQJiC5rbWorXQbw@mail.gmail.com>
References: <CAAQLLO6EhUi0OUi38BiH+qmgKqY+mY27_hGBQJiC5rbWorXQbw@mail.gmail.com>

> -----Original Message-----
> From: pgsql-sql-owner@postgresql.org [mailto:pgsql-sql-
> owner@postgresql.org] On Behalf Of Carlos Mennens
> Sent: Friday, May 11, 2012 3:04 PM
> To: PostgreSQL (SQL)
> Subject: [SQL] Finding Max Value in a Row
> 
> I have a problem in SQL I don't know how to solve and while I'm sure there
> are 100+ ways to do this in ANSI SQL, I'm trying to find the most cleanest
/
> efficient way. I have a table called 'users' and the field 'users_id' is
listed as
> the PRIMARY KEY. I know I can use the COUNT function, then I know exactly
> how many records are listed but I don't know what the maximum or highest
> numeric value is so that I can use the next available # for a newly
inserted
> record. Sadly the architect of this table didn't feel the need to create a
> sequence and I don't know how to find the highest value.
> 
> Thank you for any assistance!
> 

Finding the MAXimium of a given set of data is an aggregate operation and so
you should look in the functions section of the documentation under
"Aggregate"

http://www.postgresql.org/docs/9.0/interactive/functions-aggregate.html

Assuming that the users_id field is an integer:

SELECT MAX(users_id) FROM users; --NO GROUP BY needed since no other fields
are being output...

That said, you really should create and attach a sequence so that you can
avoid race/concurrency issues.

David J.





view thread (18+ messages)  latest in thread

Message-ID: <00ee01cd2fab$1b528b80$51f7a280$@yahoo.com>
Permalink:  ../00ee01cd2fab$1b528b80$51f7a280$@yahoo.com/
Also on:    postgresql.org/message-id/00ee01cd2fab$1b528b80$51f7a280$@yahoo.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: polobo@yahoo.com, carlos.mennens@gmail.com
  Subject: Re: Finding Max Value in a Row
  In-Reply-To: <00ee01cd2fab$1b528b80$51f7a280$@yahoo.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox