Re: How to return a default value if no result - Mailing list pgsql-novice

From David G Johnston
Subject Re: How to return a default value if no result
Date
Msg-id CAKFQuwbLhgrDQA4MjUxMy9qjRF-CdZLSq=_OPTOf6+0ok+ruog@mail.gmail.com
Whole thread Raw
In response to Re: How to return a default value if no result  ("Rob - TEAM Systems Ltd" <rob@teamsystems.co.uk>)
List pgsql-novice
For a really clean solution you would want to create a composite type.

SELECT COALESCE ( (SELECT ROW(...,...,...)::type FROM ...), ROW(val,val,val)::type )

You can make use of an anonymous/record type here but you will then be unable to expand it back into individual columns.

The "ROW" is optional but makes it clear in examples like this what is intended.

see the CREATE TYPE documentation for the syntax to create a custom composite type.

David J.


On Fri, Aug 22, 2014 at 11:33 AM, Rob Northcott [via PostgreSQL] <[hidden email]> wrote:
Thanks David,
That's actually what we did in the end, works fine in the case where there
is only one field (sorry, column!) in the result.
Just out of curiosity (luckily all the places I need to do this at the
moment will work with coalesce), is there a way to return a default result
with a multiple-column query, without resorting to unions or the long-winded
case statement?
Something like this would be nice (but I don't think such a syntax exists,
at least not that I can find):
SELECT col1, col2, col3 FROM mytable
WHERE key='A'
DEFAULT (0,'No','')


-----Original Message-----
From: [hidden email]
[mailto:[hidden email]] On Behalf Of David G Johnston
Sent: 22 August 2014 15:07
To: [hidden email]
Subject: Re: [NOVICE] How to return a default value if no result

Rob Northcott wrote
> Is there a nice way of forcing a default result somehow?

The Coalesce function is your friend:

SELECT COALESCE( (SELECT subquery), <default> )

David J.



--
View this message in context:
http://postgresql.1045698.n5.nabble.com/How-to-return-a-default-value-if-no-
result-tp5815850p5815860.html
Sent from the PostgreSQL - novice mailing list archive at Nabble.com.


--
Sent via pgsql-novice mailing list ([hidden email]) To make
changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-novice




--
Sent via pgsql-novice mailing list ([hidden email])
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-novice



If you reply to this email, your message will be added to the discussion below:
http://postgresql.1045698.n5.nabble.com/How-to-return-a-default-value-if-no-result-tp5815850p5815879.html
To unsubscribe from How to return a default value if no result, click here.
NAML



View this message in context: Re: How to return a default value if no result
Sent from the PostgreSQL - novice mailing list archive at Nabble.com.

pgsql-novice by date:

Previous
From: "Rob - TEAM Systems Ltd"
Date:
Subject: Re: How to return a default value if no result
Next
From: Marc Richter
Date:
Subject: PG 9.1 much slower than 8.2 ?