24

There is an excellent SO on MySQL empty strings versus NULL here, MySQL, better to insert NULL or empty string?, however it doesn't take in to account 'uniformity' - i.e. if you want to have just one choice in your tables (i.e. empty string OR NULL), which should it be?

My question is, can I get MySQL to automatically store empty strings as NULLs?

After reading the previous SO I am generally inclined to store NULL but the problem is that I have a lot of PHP forms with optional fields, and (when left blank) these return empty strings.

2 Answers 2

47

You can enclose your strings with NULLIF().

You use it like this:

NULLIF('test','') --> returns 'test'
NULLIF(''    ,'') --> returns NULL
Sign up to request clarification or add additional context in comments.

2 Comments

If the first and second parameters of NULLIF(string1, string2) match, NULL is returned.
2

Alternatively to NULLIF you could set the default to NULL and just not pass empty fields along.

Comments

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.