0

I have the following which only inserts to column two if the value is empty:

UPDATE name 
SET one=?,
    two=COALESCE(two, ?),
    three=? 
WHERE id = ?

However, this only works if column two if the value is null. How can I get this to work if it is either NULL OR an empty string.

It should always insert to one and three. It should only insert to two if it is NULL or empty

I am using SQLite with PHP

2 Answers 2

1

If by "empty" you mean an empty string, you can use nullif():

two = COALESCE(NULLIF(two, ''), ?)

The more general solution is a CASE expression.

Sign up to request clarification or add additional context in comments.

Comments

0

Don't store empty strings in TEXT columns.
Update the table to replace all empty strings with NULLs:

UPDATE name
SET two = NULL
WHERE TRIM(two) = ''

Now you can use your query, which is correct and in any other query you only need to check for NULL.

1 Comment

@jefiwo the notion of NULL is that it represents missing information (en.wikipedia.org/wiki/Null_(SQL)), while an empty string is a valid string value. Also, just to be practical. Do you want to check 2 (or more) conditions: if the column is NULL, or if it is empty, or if it consists of spaces?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.