views:

63

answers:

6

How to select value from a table if it value is not null,and select a default value if not?.I.E:

select coalesce(username,'its null') from tb_user where int_id_user = 0

I try to run this query but its not working,i expect to get 'its null' since int_id_user is 0,but it returns NULL.

+1  A: 
select isnull(column, 'default value')
from table

link text

Telos
thats what i code above...NOT working,it returns NULL
no, it's isnull, not coalesce... isnull does exactly what you are asking for. It tests the column for being null, and if it is it returns the second argument instead.
Telos
@Telos: COALESCE and ISNULL perform the same duty; COALESCE is ANSI syntax. Read the comments in the question for why neither works.
OMG Ponies
Well said Ponies.And ive updated the query,to column name instead "1",and it still returns NULL;
Sorry, I keep forgetting what coalesce does... :(
Telos
A: 

Telos has it right. Coalesce works like isnull for N columns.

COALESCE(column1, column2, 'default value')

Is what you'd want to use if you had more than one column to try before using a default.

Your current query would return 1 because 1 is never null.

mootinator
A: 

If you are using SQL Server (i won't speak for other dbs), then that won't return the result you want anyway.

The syntax is:

coalesce(expr1, [expr n,] expr2)

In your case, you are saying "if the int value 1 is null then return me the text 'not null'". But the value of 1 can never be null, so you'll never get the desired text.

slugster
COALESCE is ANSI, it's the same on all databases that support it: SQL Server 2000+, Oracle 9i+, MySQL 4+...
OMG Ponies
You are right.Actually the code is:select coalesce(username,'nulo') from tb_usuario where int_id_usuario = 0,where username can be NULL
A: 

No, this wont work if there is no row being returned - isnull and coalesce will work if there is a null value in the row, but there should be a row to begin with. If there are no rows, then nothing is returned.

If you are using a stored procedure, it might be better to check the rowcount that the query returns and put some default value whenever it is zero.

Also isnull/coalesce will have to be on some column rather than the integer 1.

Roopesh Shenoy
Thats right!There is no row being returned.
+1  A: 
beach
Best solution for me.
+1  A: 
SELECT  COALESCE(username, 'its null'), COALESCE(user_last_name, 'its also null')
FROM    (
        SELECT  0 AS param
        ) q
LEFT JOIN
        tb_user
ON      int_id_user = param

or, if you only want one field,

SELECT  COALESCE
        (
        (
        SELECT  username
        FROM    tb_user
        WHERE   int_id_user = 0
        ),
        'its null'
        )
Quassnoi