ALTER IGNORE TABLE mytbl ADD UNIQUE (columnName);
This will make a filed a unique index but the command deletes all rows with an empty value, is there any way I can avoid that happening. The field may have NULL values if that helps.
Set the "empty" (?) values to NULL and don't use IGNORE. The purpose of ALTER IGNORE is to remove duplicate values. Multiple NULL are not duplicates of each other, since the expression NULL = NULL is not true (and is also not false).
Related
Can you please tell How to alter the table so that it can accept the not null constraint
alter table customer add emp_id int not null foreign key references emp(emp_id)
I have tried as above, but it is showing error:
Msg 4901, Level 16, State 1, Line 1
ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column,
or alternatively if none of the previous conditions are satisfied the table must be
empty to allow addition of this column. Column 'emp_id1' cannot be added to non-empty table 'customer' because it does not satisfy these conditions.
The error is pretty clear.
You are trying to add a non-null column to a table that has data. When you add the column, it has no value. So, the default value is put into the table for the existing rows. There is no default value, so NULL is used.
You can solve this in a few ways. One would be to empty the table truncate table customer, add the new column, then load the data again.
Another way would be to add the column with NULL allowed. Then fill in the value everywhere and then add the NOT NULL constraint.
This question already has answers here:
Unique constraint that allows empty values in MySQL
(3 answers)
Closed 9 years ago.
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
MySQL: UNIQUE, but DEFAULT NULL - allowed by creating of table. More than 1 NULL is allowed to insert. Why?
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
I've just checked and it's allowed to create a table with a column that is NULL by default, although it's a UNIQUE KEY at the same time:
CREATE TABLE IF NOT EXISTS `u789` (
`column1` varchar(10) DEFAULT NULL,
UNIQUE KEY (column1)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
As I understand, it looks odd and has not much sense. I expected the second insert of
INSERT INTO u789 VALUE (NULL);
will fail.
But, it inserts first, second, third NULL value without any problems. Who can explain me why it iserts second and third columns if NULL is already in the table?
This is a theoretical question (as I understand nobody uses DEFAULT NULL + UNIQUE KEY for the same column in most situations), but I want to understand why it doesn't throw an error once one NULL is already in the column. Am I doing something wrong with declaring a unique column?
Thank you.
According to the SQL 92 specification (and how you read it) unique constraints are meant to denote candidate keys and therefore should not allow duplicate values nor NULL values. DB2 implements their unique constraints in this manner. More than a few database vendors (including MySQL) read the specification as ignoring NULL values much like the Group By clause ignores NULL values and thus they implement unique constraints such that it only applies to non-NULL values. Still others, treat the NULL as its own special value and only allow one entry which is NULL. Microsoft SQL Server implements unique constraints this way. The only aspect that is consistent amongst all vendors with respect to unique constraints is that non-NULL values must be unique.
Because NULL is not equal to NULL. Even though some RDMS, SQLServer for instance, treat 2 NULLs as equal when it comes to unique constraints.
I have a column in one of my tables. It's optional, so it can be left blank. However, if a value is provided for that column, it must be unique. Two questions:
How do I implement this in my database design (I'm using MySQL Workbench, by the way)
Is there a potential problem with my model?
Just use a UNIQUE index on the column. See:
http://dev.mysql.com/doc/refman/5.1/en/create-index.html
A UNIQUE index creates a constraint
such that all values in the index must
be distinct. An error occurs if you
try to add a new row with a key value
that matches an existing row. For all
engines, a UNIQUE index permits
multiple NULL values for columns that
can contain NULL. If you specify a
prefix value for a column in a UNIQUE
index, the column values must be
unique within the prefix.
It's can be null (and not blank) and unique. By default value can be null. There is no problem for me.
You can create a UNIQUE index on a table. In MySQL workbench that is the UQ checkbox when creating/editing the table.
Step 1, ALTER the table and MODIFY the field so NULLs are allowed.
ALTER TABLE my_table MODIFY my_field VARCHAR(100) NULL DEFAULT NULL;
Step 2, add a UNIQUE index on the field.
ALTER TABLE my_table ADD UNIQUE INDEX U_my_field (my_field);
It's fine to use -- my only hesitation with putting a UNIQUE index on a nullable field it that it is slightly counter-intuitive at first glance.
1) Move the column to a new table, make it unique and non-nullable. You can now have a row in this new table only when you have a value for it.
2) Yes. Keys and dependencies on keys are the basis of data integrity in a relational database design. If an attribute is supposed to be unique then it should be implemented as a key. A nullable "key" is not a key at all and anyway is never necessary because it can always be moved to a new table and made non-nullable without loss of any information.
I have an email column that I want to be unique. But I also want it to accept null values. Can my database have 2 null emails that way?
Yes, MySQL allows multiple NULLs in a column with a unique constraint.
CREATE TABLE table1 (x INT NULL UNIQUE);
INSERT table1 VALUES (1);
INSERT table1 VALUES (1); -- Duplicate entry '1' for key 'x'
INSERT table1 VALUES (NULL);
INSERT table1 VALUES (NULL);
SELECT * FROM table1;
Result:
x
NULL
NULL
1
This is not true for all databases. SQL Server 2005 and older, for example, only allows a single NULL value in a column that has a unique constraint.
From the docs:
"a UNIQUE index permits multiple NULL
values for columns that can contain
NULL"
This applies to all engines but BDB.
I am unsure if the author originally was just asking whether or not this allows duplicate values or if there was an implied question here asking, "How to allow duplicate NULL values while using UNIQUE?" Or "How to only allow one UNIQUE NULL value?"
The question has already been answered, yes you can have duplicate NULL values while using the UNIQUE index.
Since I stumbled upon this answer while searching for "how to allow one UNIQUE NULL value." For anyone else who may stumble upon this question while doing the same, the rest of my answer is for you...
In MySQL you cannot have one UNIQUE NULL value, however you can have one UNIQUE empty value by inserting with the value of an empty string.
Warning: Numeric and types other than string may default to 0 or another default value.
A simple answer would be : No, it doesn't
Explanation : According to the definition of unique constraints (SQL-92)
A unique constraint is satisfied if and only if no two rows in a table have the same non-null values in the unique columns
This statement can have two interpretations as :
No two rows can have same values i.e. NULL and NULL is not allowed
No two non-null rows can have values i.e NULL and NULL is fine, but StackOverflow and StackOverflow is not allowed
Since MySQL follows second interpretation, multiple NULL values are allowed in UNIQUE constraint column. Second, if you would try to understand the concept of NULL in SQL, you will find that two NULL values can't be compared at all since NULL in SQL refers to unavailable or unassigned value (you can't compare nothing with nothing). Now, if you are not allowing multiple NULL values in UNIQUE constraint column, you are contracting the meaning of NULL in SQL. I would summarise my answer by saying :
MySQL supports UNIQUE constraint but not on the cost of ignoring NULL
values
Avoid nullable unique constraints. You can always put the column in a new table, make it non-null and unique and then populate that table only when you have a value for it. This ensures that any key dependency on the column can be correctly enforced and avoids any problems that could be caused by nulls.