[MDEV-21527] NULL values allowing duplicate keys in unique index Created: 2020-01-17  Updated: 2023-06-03  Resolved: 2020-01-20

Status: Closed
Project: MariaDB Server
Component/s: N/A
Affects Version/s: 10.3.18, 10.4.7
Fix Version/s: N/A

Type: Bug Priority: Major
Reporter: Dallas Clarke Assignee: Unassigned
Resolution: Not a Bug Votes: 0
Labels: None
Environment:

both Windows and Linux


Issue Links:
Relates
relates to MDEV-31397 Implement DISTINCT and NOT DISTINCT f... Open

 Description   

NULLs in the index allow for duplicate keys. NULLs are required due to foreign keys.
Demo Script to show that values with zero are unique but records with NULL are in the table twice:-

DROP TABLE IF EXISTS `test_table`; 
CREATE TABLE `test_table` (
	`id1` INT(10) NOT NULL,
	`id2` INT(10) NULL DEFAULT NULL,
	`id3` INT(10) NULL DEFAULT NULL,
	`id4` TIMESTAMP NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
	`data` TEXT,
	UNIQUE INDEX `main` (`id1`, `id2`, `id3`, `id4`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;
INSERT INTO `test_table` (`id1`,`id2`,`id3`,`id4`,`data`) 
VALUES (1,NULL,NULL,'2020-02-20 10:00:00','data1'),
(1,NULL,NULL,'2020-02-20 10:00:00','data2'),
(2,0,0,'2020-02-20 10:00:00','data1'),
(2,0,0,'2020-02-20 10:00:00','data2')
ON DUPLICATE KEY UPDATE `data` = VALUE(`data`);



 Comments   
Comment by Alice Sherepa [ 2020-01-20 ]

This is not a bug, KB says: "In SQL any NULL is never equal to anything, not even to another NULL. Consequently, a UNIQUE constraint will not prevent one from storing duplicate rows if they contain null values" https://mariadb.com/kb/en/getting-started-with-indexes/#unique-index

Comment by Dallas Clarke [ 2020-01-20 ]

Howdy alice

If this is not a bug, maybe you can help me out by describing how I should handle the situation where I need to use NULLs in the index for nonexistent ids that have a foreign key assigned.

Secondly, every implementation of SQL is different and no provider has pedantically followed the specifications. Just because of a shortsighted definition, it shouldn't lead to a ridiculous situation where we have multiple identical entries in a unique index.

Generated at Thu Feb 08 09:07:49 UTC 2024 using Jira 8.20.16#820016-sha1:9d11dbea5f4be3d4cc21f03a88dd11d8c8687422.