Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty string inserting a zero, not a null

Tags:

null

mysql

zero

My insert statement looks like this:

INSERT INTO foo (bar) VALUES ('');

The bar field was created like so:

bar INT(11)
    COLLATION: (NULL)
    NULL: YES
    DEFAULT: (NULL)

MySQL version: 5.1.

Shouldn’t an empty string insert a NULL? I’m not sure why I’m seeing a zero (0) being stored in the table.

like image 468
gravyface Avatar asked Aug 02 '11 20:08

gravyface


People also ask

Can we insert empty string in NOT NULL column?

Yes you can...

Does an empty string count as NULL?

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. A null string is represented by null .

How do I insert a blank string?

In Oracle, if you insert an empty string ('') to a NUMBER column, Oracle inserts NULL. In SQL Server, if you insert an empty string ('') to an integer column (INT i.e.), SQL Server inserts 0, if you insert an empty string to a decimal column (DECIMAL i.e.), the statement fails.

Is empty string better than NULL?

However, it will throw an error of unique constraint if you use an empty string here. 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.


4 Answers

You're not inserting NULL into the table; you're inserting an empty string (which apparently maps to zero as an int). Remember that NULL is a distinct value in SQL; NULL != ''. By specifying any value (other than NULL), you're not inserting NULL. The default only gets used if you don't specify a value; in your example, you specified a string value to an integer column.

like image 175
Paul Sonier Avatar answered Oct 05 '22 17:10

Paul Sonier


MySQL by default attempts to coerce invalid values for a column to the correct type. Here, the empty string '' is of type string, which is neither an integer nor NULL. I suggest taking the following steps:

  1. Change the query to the following: INSERT INTO foo (bar) VALUES (NULL);
  2. Enable strict mode in MySQL. This prevents as many unexpected type and value conversions from occurring. You will see more error messages when you try to do something MySQL doesn't expect, which helps you to spot problems more quickly.
like image 29
Hammerite Avatar answered Oct 05 '22 16:10

Hammerite


Why should it be a NULL? You're providing a value that has an integer representation: empty strings convert to INT 0.

Only if you didn't provide any value would the default take over.

like image 28
Lightness Races in Orbit Avatar answered Oct 05 '22 16:10

Lightness Races in Orbit


The way to do this is to not fill the field at all. only fill the ones that actually need to have a value.

like image 23
Manuel Avatar answered Oct 05 '22 15:10

Manuel