I have a MySQL MyISAM table with ISBNs. I want to create a UNIQUE index that won't throw "duplicate" error if the value is empty or null.
Is this possible?
Yes, MySQL allows multiple NULLs in a column with a unique constraint.
Therefore, unique indexes do not enforce primary key constraints by themselves because they allow null values.
You can insert NULL values into columns with the UNIQUE constraint because NULL is the absence of a value, so it is never equal to other NULL values and not considered a duplicate value.
15.00 - Nullable Columns Are Valid for Unique Indexes - Teradata Database.
Since you're using MyISAM (or INNODB) storage engine, the short answer is no. Multiple empty strings won't work for the unique index constraint, even though multiple nulls would. Your best bet if you want a SQL only solution, is to create a regular index on the ISBN field, and then use a stored procedure to act as an insertion proxy--one that checks for uniqueness if not null or empty.
If just nulls work for you, here is a basic create:
CREATE TABLE `books` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`isbn` int(13) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `isbn` (`isbn`)
)
Just a note... Remember the '13' specified for int is only the number of digits it will show when returning in a query, not the size of the integer.
you can use something like this,
ALTER TABLE tbl_name ADD UNIQUE index_name (column_list):
This statement creates an index for which values must be unique (with the exception of NULL values, which may appear multiple times). Refer MySQL INDEXES.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With