0

suppose I have a sql like this:

select * from tba

if table tba have data, it will be shown like below:

id    name    num
1     tom     100
2     jack    200

now i need query tba by where conditon

select num from tba where id = 3;

here is the question: there's no data anymore by this sql, will be like this:

id    name    num
//no data, just have column name

so, i want to it tell me that there's no result or only zero, like:

num
0

how can i get the result?

Thanks!!

2 Answers 2

3

Try this:

SELECT COALESCE(MAX(num), 0) AS num
FROM   tba
WHERE  id = 3

If you wanted to select all columns, you can do:

SELECT COALESCE(MAX(id), 0)       AS id,
       COALESCE(MAX(name), 'N/A') AS name,
       COALESCE(MAX(num), 0)      AS num
FROM   tba
WHERE  id = 3;

SQLFiddle Demo

Sign up to request clarification or add additional context in comments.

1 Comment

wow, very good ! I am trying to select all columns and using the same way . Thanks Zane
0
SELECT ISNULL(num,0) AS num
  FROM tba
 WHERE id = 3

3 Comments

1) ISNULL is not supported by PostgreSQL. 2) ISNULL in MySQL returns only either 0 or 1. 3) Without wrapping the num column in an aggregate function, you would return no results even if you made a conditional check on it.
My fault, did not pay attention to the postgresql tag.
@Yaroslav , your answer is also very helpful for me :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.