Integer column with SQL index, even if null

I have this SQL:

update entity_table set views = views + 1 where id = {id of entity} 

The view column is NULL. Thus, this only works if the column has a value that is not null.

How can I make this statement set to 1 if it is null and increment otherwise?

Thanks.

+7
sql-server sql-server-2008
source share
3 answers
 UPDATE entity_table SET views = Coalesce(views, 0) + 1 
+14
source share

You can use Isnull also instead of Coalesce , since Isnull compares faster than Coalesce

 UPDATE entity_table SET views = isnull(views, 0) +1 

See this link for an understanding of the performance difference between the two: - http://weblogs.sqlteam.com/mladenp/articles/2937.aspx

+5
source share

I prefer the other two answers, but it may be useful to you in other situations.

 update entity_table set views = CASE WHEN views IS NULL THEN 1 ELSE views + 1 END 
+1
source share

All Articles