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.
The way to do this is to not fill the field at all. only fill the ones that actually need to have a value.
You're not inserting
NULL
into the table; you're inserting an empty string (which apparently maps to zero as an int). Remember thatNULL
is a distinct value in SQL;NULL != ''
. By specifying any value (other thanNULL
), you're not insertingNULL
. The default only gets used if you don't specify a value; in your example, you specified a string value to an integer column.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.
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:INSERT INTO foo (bar) VALUES (NULL);