How to return default value from SQL query

Viewed 104854

Is there any easy way to return single scalar or default value if query doesn't return any row?

At this moment I have something like this code example:

IF (EXISTS (SELECT * FROM Users WHERE Id = @UserId))  
    SELECT Name FROM Users WHERE Id = @UserId  
ELSE
    --default value
    SELECT 'John Doe'

How to do that in better way without using IF-ELSE?

8 Answers

If the query is supposed to return at most one row, use a union with the default value then a limit:

SELECT * FROM 
 (
  SELECT Name FROM Users WHERE Id = @UserId`
  UNION
  SELECT 'John Doe' AS Name --Default value
 ) AS subquery
LIMIT 1

Both the query and default can have as many columns as you wish, and you do not need to guarantee they are not null.

Related