Skip site navigation (1) Skip section navigation (2)

Re: Query to get the "next available" unique suffix fora 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 fora name
Date: 2010-09-28 18:33:55
Message-ID: 20100928183355.GL7862@samason.me.uk (view raw or flat)
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

pgsql-general by date

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

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group