pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tony Wasson <ajwasson@gmail.com>
To: Mark Fenbers <Mark.Fenbers@noaa.gov>
Cc: pgsql-sql@postgresql.org
Subject: Re: default value for select?
Date: Mon, 9 May 2005 10:30:53 -0700
Message-ID: <6d8daee30505091030f5c7828@mail.gmail.com> (raw)
In-Reply-To: <427F9685.8050104@noaa.gov>
References: <427F9685.8050104@noaa.gov>

On 5/9/05, Mark Fenbers <Mark.Fenbers@noaa.gov> wrote:
>  I want to update a column in myTable.  The value this column is set to
> depends on a nested select statement which sometimes returns 0 rows instead
> of 1.  This is a problem since the column I'm trying to update is set to
> refuse nulls.  Here's a sample:
>  
>  update myTable set myColumn = (Select altColumn from altTable where
> altColumn != 'XXX' limit 1) where myColumn = 'XXX';
>  
>  MyColumn cannot accept nulls, but sometimes "Select altColumn ..." returns
> 0 rows, and thus, the query fails.  
>  
>  Is there a way to set a default value to be inserted into myColumn if and
> when "select altColumn ..." returns zero rows?
>  
>  Mark

Mark, 
You can work around this by using a CASE statement. In this case, test
for a NULL from your subquery. This is not elegant at all, but it
should do what you are wanting.

update myTable set myColumn = (CASE
  WHEN (Select altColumn from altTable where  altColumn != 'XXX'
limit 1) IS NULL
    THEN 'some default value'
  ELSE (Select altColumn from altTable where  altColumn != 'XXX' limit 1)
  END)
where myColumn = 'XXX';

Hope this helps...
Tony



view thread (4+ messages)

Message-ID: <6d8daee30505091030f5c7828@mail.gmail.com>
Permalink:  ../6d8daee30505091030f5c7828@mail.gmail.com/
Also on:    postgresql.org/message-id/6d8daee30505091030f5c7828@mail.gmail.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: ajwasson@gmail.com, Mark.Fenbers@noaa.gov
  Subject: Re: default value for select?
  In-Reply-To: <6d8daee30505091030f5c7828@mail.gmail.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