473,385 Members | 1,798 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Default value if query returns 0 rows?

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

--
Lars Kellogg-Stedman <la**@oddbit.com>

---------------------------(end of broadcast)---------------------------
TIP 2: you can get off all lists at once with the unregister command
(send "unregister YourEmailAddressHere" to ma*******@postgresql.org)

Nov 23 '05 #1
8 10226
On Fri, Sep 17, 2004 at 11:03:48 -0400,
Lars Kellogg-Stedman <la**@oddbit.com> wrote:
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.


If there can be at most one match you can use a subselect and coalesce.

---------------------------(end of broadcast)---------------------------
TIP 9: the planner will ignore your desire to choose an index scan if your
joining column's datatypes do not match

Nov 23 '05 #2

On Fri, 17 Sep 2004 11:03:48 -0400 (EDT), la**@oddbit.com (Lars
Kellogg-Stedman) wrote:
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

try something like:

select case
when count(*) > 0 then (select id from map where name = 'foo')
when count(*) = 0 then -1
end as id
from map where name = 'foo'
cheers,
Gary.

Nov 23 '05 #3
On Fri, 17 Sep 2004, Bruno Wolff III wrote:

if exists (select 1 from map where name = 'foo') then
select id from map where name = 'foo'
else
select -1
end if


If there can be at most one match you can use a subselect and coalesce.


Bruno,

Thanks for the suggestion. I've come up with the following that appears to
work:

SELECT
COALESCE((SELECT id FROM map WHERE name = $1), -1)
FROM map_level
LIMIT 1

-- Lars

--
Lars Kellogg-Stedman <la**@oddbit.com>

---------------------------(end of broadcast)---------------------------
TIP 5: Have you checked our extensive FAQ?

http://www.postgresql.org/docs/faqs/FAQ.html

Nov 23 '05 #4
Lars Kellogg-Stedman <la**@oddbit.com> writes:
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


Is the name unique? If so you could do

select * from
(select id from map where name = 'foo'
union all
select -1) ss
limit 1;

This is an abuse of SQL of course --- mainly, it relies on the
assumption that UNION ALL is implemented in the "obvious" way.
But it certainly will work in current and foreseeable versions
of Postgres. A bigger problem is that I don't see how to extend
the approach if there might be more than one 'foo' row, and you
want them all and only want the -1 when there are none.

Another way is a subselect:

select coalesce((select id from map where name = 'foo'), -1);

but this one will actively blow up if there are multiple 'foo' rows,
so it doesn't solve that problem either.

regards, tom lane

---------------------------(end of broadcast)---------------------------
TIP 3: if posting/reading through Usenet, please send an appropriate
subscribe-nomail command to ma*******@postgresql.org so that your
message can get through to the mailing list cleanly

Nov 23 '05 #5
[snip]
Another way is a subselect:

select coalesce((select id from map where name = 'foo'), -1); Then why not:

select coalesce((select id from map where name = 'foo' limit 1), -1);

This should work even if there are more rows with foo.

but this one will actively blow up if there are multiple 'foo' rows,
so it doesn't solve that problem either.

regards, tom lane


---------------------------(end of broadcast)---------------------------
TIP 4: Don't 'kill -9' the postmaster

Nov 23 '05 #6
Tom Lane wrote:

Is the name unique? If so you could do

select * from
(select id from map where name = 'foo'
union all
select -1) ss
limit 1;
Another way is a subselect:

select coalesce((select id from map where name = 'foo'), -1);

but this one will actively blow up if there are multiple 'foo' rows,
so it doesn't solve that problem either.


Can't you just:

select coalesce(id, -1) from map where name = 'foo' ?

Or am I missing something?
Nov 23 '05 #7
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

---------------------------(end of broadcast)---------------------------
TIP 1: subscribe and unsubscribe commands go to ma*******@postgresql.org

Nov 23 '05 #8
> Thanks for the suggestion. I've come up with the following that appears to
work:

SELECT
COALESCE((SELECT id FROM map WHERE name = $1), -1)
FROM map_level
LIMIT 1


And in fact I see that this should simply be:

SELECT COALESCE((SELECT id FROM map WHERE name = $1), -1)

No need for me to be making things all complicated.

Thanks again!

-- Lars

--
Lars Kellogg-Stedman <la**@deas.harvard.edu>
IT Operations Manager
Division of Engineering and Applied Sciences
Harvard University


---------------------------(end of broadcast)---------------------------
TIP 9: the planner will ignore your desire to choose an index scan if your
joining column's datatypes do not match

Nov 23 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Bruce A. Julseth | last post by:
I know the following $sql will fail since there is no Customer='Smith'. I want to determine how to test a failure of mysql_query. I thought mysql_query returned false if a query failed. The test...
6
by: Jason | last post by:
I have a function which performs a query and returns a table. The one parameter that can get passed in is a date which defaults to NULL. There is an IF statement in the function that will set the...
2
by: Adam | last post by:
In my MYISAM table I have an index (Index_A) on 2 fields (Field_A, Field_B). There are millions of rows in the table. The cardinality of Index_A is 53. I think a query to count the number of rows...
5
by: Mike Nolan | last post by:
I notice that 7.4 doesn't do default ordering on a 'group by', so you have to throw in an 'order by' clause to get the output in ascending group order. Is this something that most RDB's have...
1
by: Ken | last post by:
I wrote a function to use in queries that takes a date and adds or subtracts a certain length time and then returns the new value. There are times when my function needs to return Null values. ...
2
by: Viorel | last post by:
Adding new row with default values. In order to insert programmatically a new row into a database table, without direct "INSERT INTO" SQL statement, I use the well-known DataTable.NewRow,...
2
by: Brian Brane | last post by:
I have properties that wrap DataRow columns as in: public int aNumber { get{ return m_DataRow; } set{ m_DataRow = value; } } If the column happens to contain DBNull, I get a cast exception...
1
by: Kevin Murphy | last post by:
This is probably a stupid question, but ... I'd like to be able to take an existing query and modify it to return a single row if that's what the base query returns, and 0 rows if the base query...
3
by: =?Utf-8?B?UmljaCBIdXRjaGlucw==?= | last post by:
I'm not really sure how to ask this question because I'm still getting my feet wet with data access and VB.NET, but here goes: To start off with, I'm using VB 2005 Express to connect to an Access...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.