Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use NULL or an empty string to represent no data in table column?

Null or empty string -- is one better than the other to represent no data in a table column? (I specifically use MySQL, but I'm thinking this is system-independent.) Are there major advantages/disadvantages to using one over the other, or is it simply programmer preference?

like image 651
Justin Stayton Avatar asked Oct 03 '08 17:10

Justin Stayton


People also ask

Is it better to use NULL or empty string?

So, NULL is better. An empty string is useful when the data comes from multiple resources. NULL is used when some fields are optional, and the data is unknown.

Is NULL the same as an empty string?

The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.

How do you represent no data?

A "no data" value in a column should be represented by a default value. Remember that NULL signifies an unknown value, that is, the column can have a value or not but you don't know it as of this time.

What is the point of an empty string?

The empty string is a legitimate string, upon which most string operations should work. Some languages treat some or all of the following in similar ways: empty strings, null references, the integer 0, the floating point number 0, the Boolean value false, the ASCII character NUL, or other such values.


2 Answers

I strongly disagree with everyone who says to unconditionally use NULL. Allowing a column to be NULL introduces an additional state that you wouldn't have if you set the column up as NOT NULL. Do not do this if you don't need the additional state. That is, if you can't come up with a difference between the meaning of empty string and the meaning of null, then set the column up as NOT NULL and use empty string to represent empty. Representing the same thing in two different ways is a bad idea.

Most of the people who told you to use NULL also gave an example where NULL would mean something different than empty string. And in those examples, they are right.

Most of the time, however, NULL is a needless extra state that just forces programmers to have to handle more cases. As others have mentioned, Oracle does not allow this extra state to exist because it treats NULL and empty string as the same thing (it is impossible to store an empty string in a column that does not allow null in Oracle).

like image 177
Greg Smalter Avatar answered Sep 28 '22 15:09

Greg Smalter


Null. An empty string isn't "no data", it's data that happens to be empty.

like image 41
Paul Tomblin Avatar answered Sep 28 '22 17:09

Paul Tomblin