简体   繁体   中英

Can we create an index on a column containing NULL values in MySQL 5.7?

Following is the text from the MySQL Documentation :

The primary key for a table represents the column or set of columns that you use in your most vital queries. It has an associated index, for fast query performance. Query performance benefits from the NOT NULL optimization, because it cannot include any NULL values .

I am not understanding the exact meaning of the sentence in bold font from the above text. Someone please explain to me.

Also, let me know whether can we create an index on a column containing NULL values in MySQL 5.7 ? If no, what's the reason?

Thank You.

A PRIMARY key is used to organize the data on disk and because there is a relationship to how the data is physically arranged you cannot have any part of a primary key being NULL.

A non-primary index CAN have one or more columns that allow NULLs. demo

CREATE TABLE `my_docs` (
  `id` int(6) unsigned NOT NULL AUTO_INCREMENT,
  `rev` int(3) ,
  `content` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;


INSERT INTO `my_docs` (`rev`, `content`) VALUES
  (1, 'The earth is flat'),
  (1, 'One hundred angels can dance on the head of a pin'),
  (NULL, 'The earth is flat and rests on a bull\'s horn'),
  (3, 'The earth is like a ball.');

alter table `my_docs` add key my_added_index (`rev`);

SELECT id, rev, content
FROM `my_docs`
where rev = 3

| id | rev |                   content |
|----|-----|---------------------------|
|  4 |   3 | The earth is like a ball. |


+---+-------------+-----------+------+----------------+----------------+---------+-------+------+----------+-------+
| d | select_type |   table   | type | possible_keys  |      key       | key_len |  ref  | rows | filtered | Extra |
+---+-------------+-----------+------+----------------+----------------+---------+-------+------+----------+-------+
| 1 |    SIMPLE   |   my_docs | ref  | my_added_index | my_added_index |       5 | const |    1 |   100.00 |       |
+---+-------------+-----------+------+----------------+----------------+---------+-------+------+----------+-------+

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