Skip to content
Advertisement

Update SQLite row only if a column is empty

I have the following:

$query = $db->prepare("UPDATE name SET one=?,two=?,three=? WHERE id = ?");
$query->bindParam(1, $one);
$query->bindParam(2, $two);
$query->bindParam(3, $three);
$query->bindParam(4, $id);

one and three should always be updated.

However, how can I update two only if it is null/empty?

I can do this in a separate command, though how can I achieve this in one prepared statement?

I am using SQLite3

Advertisement

Answer

Use a CASE expression for column two:

UPDATE name 
SET one=?,
    two=CASE WHEN two IS NULL THEN ? ELSE two END,
    three=? 
WHERE id = ?

Or with COALESCE():

UPDATE name 
SET one=?,
    two=COALESCE(two, ?),
    three=? 
WHERE id = ?
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement