I've created the following table:
CREATE TABLE MMCompany ( CompanyUniqueID BIGSERIAL PRIMARY KEY NOT NULL, Name VARCHAR (150) NOT NULL, PhoneNumber VARCHAR(20) NOT NULL UNIQUE, Email VARCHAR(75) UNIQUE, CompanyLogo BYTEA );
The email column is unique and it causes a "bug" in my scenario since there could only be one record with null. I'm trying to achieve records of companies without the same email but at the same time allow a companies to have no email.
How can I achieve that?
The primary key column cannot have null values while the Unique Key column can have one null value.
As you know, when you create a UNIQUE constraint on a nullable column, SQL Server allows only one NULL value, thereby maintaining the UNIQUEness. However, there are situations when we need more than one NULL value in the column but still have to maintain uniqueness, ignoring all those NULL values.
Solution 1. Logically, any key which is allowed to contain non duplicate (unique) values is a unique key, NULL is a permissible value in sql server , so it can have NULL for a single time just like any other value.
Although null values represent unknown values, when it comes to indexing, a null value is treated as being equal to other null values. Therefore, if a unique index consists of a single column, only one null value is allowed-more than one null value would violate the unique constraint.
This is a misunderstanding.
The UNIQUE
constraint does exactly what you want. Multiple NULL
values can coexist in a column defined UNIQUE
.
The manual:
In general, a unique constraint is violated when there is more than one row in the table where the values of all of the columns included in the constraint are equal. However, two null values are not considered equal in this comparison. That means even in the presence of a unique constraint it is possible to store duplicate rows that contain a null value in at least one of the constrained columns. This behavior conforms to the SQL standard, but we have heard that other SQL databases might not follow this rule. So be careful when developing applications that are intended to be portable.
Bold emphasis mine.
Be aware that character types allow an empty string (''
), which is not a NULL
value and would trigger a unique violation just like any other non-null value when entered in more than one row.
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