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
ofNULL
isNULL
, aLENGTH
of an empty string is0
.NULL
s are sorted before the empty strings.COUNT(message)
will count empty strings but notNULL
sYou 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
inmytext
, whatever value you pass from the client. To matchNULL
s, 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 = ''
.