Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL UPDATE, but only if the old value is null

I have been using a sql like this to update a list of properties in my database:

update my_table set a = ?, b = ?, c = ?, d = ?,  where customer = ?

But I want to update a property with a new value ONLY if it does not have a value in the database already. How can I do that?

like image 579
Miss T Avatar asked Jan 26 '11 15:01

Miss T


People also ask

Can we UPDATE a column value to NULL?

Output: Column value can also be set to NULL without specifying the 'where' condition.

Can we write UPDATE statement without WHERE condition?

The UPDATE statement in SQL is used to update records in the table. We can modify one or multiple records (rows) in a table using UPDATE statement. If you do not use WHERE clause in UPDATE statement, all the records in the table will be updated.

How do I return 0 if NULL in SQL?

We can return 0 for NULL in MySQL with the help of IFNULL() method. The syntax of IFNULL() is as follows. IFNULL(YOUREXPRESSION,0);


1 Answers

In MS SQL something like this (assuming non value means database NULL) should work:

update 
  my_table 
set 
  a = COALESCE(a, ?), 
  b = COALESCE(b, ?), 
  c = COALESCE(c, ?), 
  d = COALESCE(d, ?)
where 
  customer = ?

COALESCE() returns first non null value from its arguments.

like image 147
Grzegorz Gierlik Avatar answered Oct 13 '22 22:10

Grzegorz Gierlik