简体   繁体   中英

Can MySQL INT type be non-zero NULL

I'm creating a MySQL DB which is composed of weekly data sets, going back for the past decade. There are some data points which exist for recent records, but which were not tracked in some of the older data sets. The fields in question all contain integer values, and '0' is a perfectly valid (and frequent) value for the records which did track the data points. I need to be able to distinguish between a value of zero and non-existent data. Therefore, I need to find out if it is possible to store a NULL which is not represented as a '0' (read: BLANK CELL) for an INT type. However, NULL values passed to the DB are represented as '0' (at least, they are in phpMyAdmin), is there any way to change this?

Thanks for your help.

You can set the value to NULL. INSERT INTO table (INT_COLUMN) VALUES (NULL) is valid SQL (with INT_COLUMN being a nullable int column).

The answer is "yes" - you can have nullable int columns. But should you?

Too often, null is misused and misunderstood. In SQL databases, null means "unknown". In your situation, using null is perfect, so "yes - you should"

There are cases when you want to use a specific value for "null", for example -1 for a quantity. This approach is valid and is used to simplify the application code and SQL, because dealing with nulls in queries is a pain in the ass:

  • You have to use the special syntax "IS NULL"
  • Any list containing a null will never match anything , eg WHERE NAME IN (SELECT COL1 FROM SOMETABLE) will never work if any of the selected values is null
  • Null doesn't equal anything else, even another null
  • In strict (eg java) app code, you have a check that a value is null or you'll get a NullPointerException. Using an actual value avoids this

Yes, be sure your table is designed to allow NULL values in the column in question. See the very basic example below:

DROP TABLE IF EXISTS testTable;
CREATE TABLE `testTable` (
  `id` int(11) unsigned NOT NULL auto_increment,
  `data` int(11) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
;

INSERT INTO testTable VALUES
(NULL, 100),
(NULL, 200),
(NULL, NULL),
(NULL, 400);

SELECT * FROM testTable;

The select will have the following result:

+----+------+
| id | data |
+----+------+
|  1 |  100 |
|  2 |  200 |
|  3 | NULL |
|  4 |  400 |
+----+------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM