I have an existing mysql table, and I want to set one field (varchar) so that it must either be unique, or empty (by default). So when user does not enter value, its empty, otherwise user must enter unique value.
how would I do that ?
I have an existing mysql table, and I want to set one field (varchar) so that it must either be unique, or empty (by default). So when user does not enter value, its empty, otherwise user must enter unique value.
how would I do that ?
MySQL includes a constraint type UNIQUE
that allows for exactly this. If you declare a column UNIQUE
and allow NULL
values in it, then all values will be forced to be unique unless they are NULL values. If you want to prevent empty strings (''
) from being stored, you will have to manage that at the code level, because MySQL will treat it as just another string and allow it once in a UNIQUE
column. If no value is passed to such a column, it will automatically default to NULL
, but you can also specify NULL
(not in quotes) programmatically in your code before passing the values to the database.
For the rest of this post I will assume the name of the table is tablename
and the name of the column is columnname
and the size of the varchar field is 255
If you want to modify an existing table, rather than create a new one:
If the column does not already support null values:
ALTER TABLE tablename ALTER COLUMN columnname VARCHAR(255) NULL
To add the unique constraint:
ALTER TABLE tablename ADD CONSTRAINT un_tablename_column UNIQUE (columnname)`
(I always name my constraints so I can refer to them specifically later)
OR if you want to do it on a new table:
CREATE TABLE tablename (
[...]
columnname varchar(255) UNIQUE NULL,
[...]
)
From what I have read, by standard it should not be possible to have a column in a table that allowes null values AND has a unique constraint; if it is, it is down to a special mysql-engine (that will result in unpredictable/unexpected behavior elsewhere also imho)
Also your question seems kind of reverse of this one
You could however enforce this using triggers, you can write a trigger on insert/update to check if the value already exists and immediatly delete it if it does.
I think you better process your data before pass to mysql, or not, you can write a trigger trigger whenever your table is update to make sure it pass your rule