Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL increment integer column even if null

I have this SQL:

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

the views column is nullable. So this only works if the column has a value which is not null.

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

Thanks.

like image 809
Richard Avatar asked Aug 06 '13 16:08

Richard


2 Answers

UPDATE entity_table
SET    views = Coalesce(views, 0) + 1
like image 115
gvee Avatar answered Sep 17 '22 13:09

gvee


You can use Isnull also in place of Coalesce as Isnull is comparatively faster than Coalesce

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

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

like image 40
Rahul Tripathi Avatar answered Sep 20 '22 13:09

Rahul Tripathi