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

From Rob - TEAM Systems Ltd
Subject Re: How to return a default value if no result
Date
Msg-id 002901cfbdfc$555de9a0$0019bce0$@teamsystems.co.uk
Whole thread Raw
In response to How to return a default value if no result  ("Rob - TEAM Systems Ltd" <rob@teamsystems.co.uk>)
Responses Re: How to return a default value if no result  (David G Johnston <david.g.johnston@gmail.com>)
List pgsql-novice

OK, we’ve thought of another possibility, still seems a bodge though:

 

Select case when exists(Select vat_rate from vatrates where vat_code=’1’ and vat_date<=’2014-08-01’)

Then (Select vat_rate from vatrates where vat_code=’1’ and vat_date<=’2014-08-01’ order by vat_date desc limit 1)

Else (select 0 as vat_rate from vatrates limit 1)

 

From: pgsql-novice-owner@postgresql.org [mailto:pgsql-novice-owner@postgresql.org] On Behalf Of Rob - TEAM Systems Ltd
Sent: 22 August 2014 12:19
To: pgsql-novice@postgresql.org
Subject: [NOVICE] How to return a default value if no result

 

I want my query to return at least one row with a default result even if there are no matches in the database.

As a simple example, getting the valid VAT rate for a transaction date and VAT code:

Select vat_rate from vatrates where vat_code=’1’ and vat_date<=’2014-08-01’ order by vat_date desc limit 1

 

This is fine as long as there is a match.  If there are no matches, I’d like it to return a default (0) rather than no result.

I could make sure there is always a result by having a UNION with a hard-coded record, but this doesn’t let me order by a field not in the result.

 

In this example I could just make sure there is a dummy row in the table with a very old date and do something like this:

Select vat_rate from vatrates where (vat_code=’1’ or vat_code=’DUMMY’) and vat_date<=’2014-08-01’ order by vat_date desc limit 1

But it seems like a bodge to me.

 

Is there a nice way of forcing a default result somehow?

 

Thanks,

 

Rob

pgsql-novice by date:

Previous
From: "Rob - TEAM Systems Ltd"
Date:
Subject: How to return a default value if no result
Next
From: David G Johnston
Date:
Subject: Re: How to return a default value if no result