How to return default value from SQL query
Solution 1:
Assuming the name is not nullable and that Id
is unique so can match at most one row.
SELECT
ISNULL(MAX(Name),'John Doe')
FROM
Users
WHERE
Id = @UserId
Solution 2:
Try ISNULL
or COALESCE
:
SELECT ISNULL((SELECT TOP 1 Name FROM Users WHERE Id = @UserId), 'John Doe')
The inner select will return nothing if no user exist with this id, the isnull will solve this case.
Solution 3:
Try this
`SELECT IFNULL(Name,'John Doe') FROM Users WHERE Id = @UserId)`
Solution 4:
You can drop the if statement using following construct but that doesn't necessarely mean it is better.
SELECT Name FROM Users WHERE Id = @UserId UNION ALL
SELECT 'John Doe' WHERE NOT EXISTS (SELECT Name FROM Users WHERE Id = @UserId)