NULL vs Empty when dealing with user input

2020-05-28 03:51发布

Yes, another NULL vs empty string question.

I agree with the idea that NULL means not set, while empty string means "a value that is empty". Here's my problem: If the default value for a column is NULL, how do I allow the user to enter that NULL.

Let's say a new user is created on a system. There is a first and last name field; last name is required while first name is not. When creating the user, the person will see 2 text inputs, one for first and one for last. The person chooses to only enter the last name. The first name is technically not set. During the insert I check the length of each field, setting all fields that are empty to NULL.

When looking at the database, I see that the first name is not set. The question that immediately comes to mind is that maybe they never saw the first name field (ie, because of an error). But this is not the case; they left if blank.

So, my question is, how do you decide when a field should be set to NULL or an empty string when receiving user input? How do you know that the user wants the field to be not set without detecting focus or if they deleted a value...or...or...?

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

标签: database null
8条回答
相关推荐>>
2楼-- · 2020-05-28 04:51

I try to keep things simple. In this case, I'd make the first-name column not-nullable and allow blanks. Otherwise, you'll have three cases to deal with anywhere you refer to this field:

  1. Blank first name
  2. Null first name
  3. Non-blank first name

If you go with 'blank is null' or 'null is blank' then you're down to two cases. Two cases are better than three.

To further answer your question: the user entering data probably doesn't (and shouldn't) know anything about what a "null" is and how it compares to an "empty". This issue should be resolved cleanly and consistently in the system--not the UI.

查看更多
劫难
3楼-- · 2020-05-28 04:52

While your example is mostly for strings, I like to say that I use null for numerical and boolean fields. An accountbalance of 0 is very different to me as one that is null. Same for booleans, if people take a multiple choice test with true and false answers, it is very important to know whether someone answered true or false or didn't answer at all. Not using null in these cases would require me to have an extra table or a different setup to see whether someone answered a question. You could use for instance -1 for not filled in 0 for false and 1 for true, but then you're using a numerical field for something that's essentially a boolean.

查看更多
登录 后发表回答