June 17, 2009 at 1:17 pm
Hi,
Is is it possible to retun a value from a select statement if the record does not exist in the database.
For example,
SELECT price FROM products
WHERE productname = 'bob'
How can I return 0 if there is no product called 'bob'?
Thanks!
June 17, 2009 at 1:57 pm
No, the SELECT statement is designed that way.
You can achieve what you want like this (its not good practise)
IF NOT EXISTS (SELECT * FROM products
WHERE productname = 'bob')
SELECT 0 AS price;
ELSE
SELECT price FROM products
WHERE productname = 'bob';
However - how do you know if the productname 'bob' does exist, but has a price of 0? - you can't tell from the results which condition gave the result, so its not a reliable test for the existance of productname 'bob'
June 17, 2009 at 4:31 pm
There are a couple of different ways to get around this problem. Tom lists the most straight-forward way (IF). If you need to stick to a single SQL statment or something that could be used in a view, you could use either a conditioned UNION or the following trick, an outer join of a single constant as a table source:
SELECT COALESCE(P.price, 0) as price
FROM products as P
RIGHT JOIN (
SELECT 1 as Constant
) as Dummy ON P.productname = 'bob'
[font="Times New Roman"]-- RBarryYoung[/font], [font="Times New Roman"] (302)375-0451[/font] blog: MovingSQL.com, Twitter: @RBarryYoung[font="Arial Black"]
Proactive Performance Solutions, Inc. [/font][font="Verdana"] "Performance is our middle name."[/font]
February 8, 2012 at 3:00 am
Hi,
There is no way to do it in one select query directly from table .But a few work around is there
SELECT
ISNULL(P.price, 0) as price
FROM products as P
RIGHT JOIN (
SELECT
1 as productname) as PROD
ON P.productname = Prod.productname and P.productname ='bob'
make sure that 1 is not available in products table
December 18, 2019 at 6:04 pm
Wonderful solution! Congratulations!
December 18, 2019 at 9:32 pm
Wonderful solution! Congratulations!
Hmmm... wait for it...
--Jeff Moden
Change is inevitable... Change for the better is not.
December 19, 2019 at 12:24 pm
SELECT ISNULL((
SELECT price FROM products
WHERE productname = 'bob'
),0) AS [price]
This will only work if only one or no row is found in matching
Far away is close at hand in the images of elsewhere.
Anon.
January 10, 2020 at 1:14 am
This was removed by the editor as SPAM
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply
This website stores cookies on your computer.
These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media.
To find out more about the cookies we use, see our Privacy Policy