MySQL, better to insert NULL or empty string?
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
s-
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
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 = ''
.
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.