I have a form on a website which has a lot of different fields. Some of the fields are optional while some are mandatory. In my DB I have a table which holds all these values, is it better practice to insert a NULL value or an empty string into the DB columns where the user didn't put any data?
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
I don't know what best practice would be here, but I would generally err in favor of the null unless you want null to mean something different from empty-string, and the user's input matches your empty-string definition.
Note that I'm saying YOU need to define how you want them to be different. Sometimes it makes sense to have them different, sometimes it doesn't. If not, just pick one and stick with it. Like I said, I tend to favor the NULL most of the time.
Oh, and bear in mind that if the column is null, the record is less likely to appear in practically any query that selects (has a where clause, in SQL terms) based off of that column, unless the selection is for a null column of course.
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 pytohn 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.