MySQL, better to insert NULL or empty string?

One thing to keep in mind is that NULL might make your codepaths much more difficult. In Python for example most database adapters / ORMs map NULL to None.

So things like:

print "Hello, %(title)s %(firstname) %(lastname)!" % databaserow

might result in "Hello, None Joe Doe!" To avoid it you need something like this code:

if databaserow.title:
    print "Hello, %(title)s %(firstname) %(lastname)!" % databaserow
else:
    print "Hello, %(firstname) %(lastname)!" % databaserow

Which can make things much more complex.


Better to Insert NULL for consistency in your database in MySQL. Foreign keys can be stored as NULL but NOT as empty strings.

You will have issues with an empty string in the constraints. You may have to insert a fake record with a unique empty string to satisfy a Foreign Key constraint. Bad practice I guess.

See also: Can a foreign key be NULL and/or duplicate?


By using NULL you can distinguish between "put no data" and "put empty data".

Some more differences:

  • A LENGTH of NULL is NULL, a LENGTH of an empty string is 0.

  • NULLs are sorted before the empty strings.

  • COUNT(message) will count empty strings but not NULLs

  • You can search for an empty string using a bound variable but not for a NULL. This query:

    SELECT  *
    FROM    mytable 
    WHERE   mytext = ?
    

    will never match a NULL in mytext, whatever value you pass from the client. To match NULLs, you'll have to use other query:

    SELECT  *
    FROM    mytable 
    WHERE   mytext IS NULL
    

One thing to consider, if you ever plan on switching databases, is that Oracle does not support empty strings. They are converted to NULL automatically and you can't query for them using clauses like WHERE somefield = '' .