Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql unique index EXCEPT empty or null

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?

like image 766
nick Avatar asked Jul 03 '12 02:07

nick


People also ask

Can unique index have NULL values MySQL?

Yes, MySQL allows multiple NULLs in a column with a unique constraint.

Can unique index have NULL values?

Therefore, unique indexes do not enforce primary key constraints by themselves because they allow null values.

IS NULL allowed in unique constraint MySQL?

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.

Can you have unique index on nullable column?

15.00 - Nullable Columns Are Valid for Unique Indexes - Teradata Database.


2 Answers

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.

like image 102
Ray Avatar answered Sep 22 '22 12:09

Ray


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.

like image 38
Parth Doshi Avatar answered Sep 19 '22 12:09

Parth Doshi