Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't update column if update value is null

I have a query like this (in a function):

UPDATE some_table SET   column_1 = param_1,   column_2 = param_2,   column_3 = param_3,   column_4 = param_4,   column_5 = param_5 WHERE id = some_id; 

Where param_x is a parameter of my function. Is there a way to NOT update those columns, for which the param is NULL? For example - if param_4 and param_5 are NULL, then update only the first three columns and leave old values for column_4 and column_5.

The way I am doing it now is:

SELECT * INTO temp_row FROM some_table WHERE id = some_id;  UPDATE some_table SET   column_1 = COALESCE(param_1, temp_row.column_1),   column_2 = COALESCE(param_2, temp_row.column_2),   column_3 = COALESCE(param_3, temp_row.column_3),   column_4 = COALESCE(param_4, temp_row.column_4),   column_5 = COALESCE(param_5, temp_row.column_5) WHERE id = some_id; 

Is there a better way?

like image 416
Przemek Avatar asked Nov 09 '12 10:11

Przemek


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.

Is NULL in UPDATE query in SQL?

Null Values can be replaced in SQL by using UPDATE, SET, and WHERE to search a column in a table for nulls and replace them. In the example above it replaces them with 0. Cleaning data is important for analytics because messy data can lead to incorrect analysis. Null values can be a common form of messy data.

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

Drop the SELECT statement, there is no need for, just use the current value:

UPDATE some_table SET   column_1 = COALESCE(param_1, column_1),   column_2 = COALESCE(param_2, column_2),   column_3 = COALESCE(param_3, column_3),   column_4 = COALESCE(param_4, column_4),   column_5 = COALESCE(param_5, column_5) WHERE id = some_id; 
like image 56
Frank Heikens Avatar answered Sep 21 '22 22:09

Frank Heikens