Re: Default value if query returns 0 rows?

From: Christian Mangold <christian(dot)mangold(at)man-it(dot)at>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: Default value if query returns 0 rows?
Date: 2004-09-17 15:54:17
Message-ID: 414B08A9.3090904@man-it.at
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi,

I think

select id from
(select id from map where name like 'foo'
union
select -1 as id order by id desc) a LIMIT 1

should do it in the case id >= 0 for existing names.

-Christian

Lars Kellogg-Stedman schrieb:
> Hello,
>
> I have a simple two-column table mapping names to ids. I'd like to write a
> select statement that will return a default value if a given name isn't
> found in the table. That is, I want something equivalent to the following
> pseudocode:
>
> if exists (select 1 from map where name = 'foo') then
> select id from map where name = 'foo'
> else
> select -1
> end if
>
> I think I can see how to do this by writing a pl/pgsql function, but I'm
> curious if it's possible to do this completely as part of a select
> statement. I've toyed with CASE expressions, but the fact that a missing
> value returns 0 rows continues to foil me.
>
> Thanks,
>
> -- Lars
>

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Lars Kellogg-Stedman 2004-09-17 15:56:57 Re: Default value if query returns 0 rows?
Previous Message Gary Doades 2004-09-17 15:43:18 Re: Default value if query returns 0 rows?