5

I have a PHP/MySQL application that stores "blank" values in some cases as '' (empty strings) and in other cases as NULLs.

Having this mixed format certainly causes a problem when comparing, so I’m wondering which one is the better storage mechanism? '' or NULL?

3
  • AFAIK, comparison to NULL is faster than comparison to an empty string. Commented Aug 4, 2011 at 10:02
  • stackoverflow.com/questions/6638291/… Commented Aug 4, 2011 at 11:59
  • Thanks @Damir for that reference - cant imagine doing that! Very scary! Commented Aug 15, 2011 at 7:41

1 Answer 1

8

While this is confusing, actually you should store null for a number of reasons :

  1. Checking against null is usually faster than checking an empty string in most databases
  2. Null commonly means "i don't know", empty string means "I know : it's empty". It gives you better semantics.
Sign up to request clarification or add additional context in comments.

5 Comments

When writing to the database, if there is no content for a field, shouldnt I be saving it as NULL?
Yes, no content is NULL if it indicates unknown or unknowable value. For instance if you entered my 'full' name into a DB the only value you could use for my middle name is probably NULL. I know whether the string that descibes my middle name is '' or 'Laurence'. Think of an empty string a like 0, a defined value where that value is nothing and NULL as 'don't know' or 'can't know'
Yes, but if for example you take data from an HTML form, for fields the user has not filled, an empty string is usually sent. If you don't check for it, and "compose" the update using parameters from the HTML form directly, you end up inserting empty strings instead of nulls.
So what's the better approach? Storing NULLs or blank strings? @Karl as well
I recommend storing NULLS unless you know that the real value is ""; meaning we know there is no value here. This can mean having to deal with empty string to NULL conversions, e.g. @SimoneGianni's HTML form example. I also beleive that for performance and logical reason it is better to utilise NULLs.

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.