Re: Query to get the "next available" unique suffix for a name

From: Sam Mason <sam(at)samason(dot)me(dot)uk>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: Query to get the "next available" unique suffix for a name
Date: 2010-09-28 18:33:55
Message-ID: 20100928183355.GL7862@samason.me.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Mon, Sep 27, 2010 at 06:36:25PM -0700, Mike Christensen wrote:
> Thus, the users table already has:
>
> MikeChristensen1
> MikeChristensen2
> MikeChristensen3
> MikeChristensen4
>
> I want to write a SQL query that figures out that MikeChristensen5 is
> the next available username and thus suggest it.

Why not do something like:

SELECT max(nullif(substring(username FROM '[0-9]*$'),'')::numeric) AS lastnum
FROM users
WHERE username ~ '^MikeChristensen[0-9]*$';

It's a pretty direct translation from what I'd do in any imperative
language.

--
Sam http://samason.me.uk/

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Scott Ribe 2010-09-28 18:46:36 Re: PostgreSQL 9 Mac OS X one-click install - PL/perl broken
Previous Message Larry Leszczynski 2010-09-28 18:23:23 Re: PostgreSQL 9 Mac OS X one-click install - PL/perl broken