Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return default value from SQL query

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?

like image 221
Marek Kwiendacz Avatar asked Jul 16 '12 11:07

Marek Kwiendacz


People also ask

How do I return a default value in SQL?

I would suggest that the best way to do is that first declare @name . Then set this value based on user id and then if @name is null show default name otherwise show name... That method would be as efficient as any other method and will be more readable.

How does default value work in SQL?

The DEFAULT Constraint is used to fill a column with a default and fixed value. The value will be added to all new records when no other value is provided. Dropping the default constraint will not affect the current data in the table, it will only apply to new rows.

What is default value in SQL table?

The default value is used for the column's value when one is not specified (for example, when you insert a row into the table without specifying a value for the column). You can add a default constraint either when creating a table or after the table already exists.


2 Answers

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   
like image 68
Martin Smith Avatar answered Sep 20 '22 11:09

Martin Smith


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.

like image 22
Matzi Avatar answered Sep 20 '22 11:09

Matzi