How can I create a unique constraint that also allows nulls?
How can I create a unique constraint that also allows nulls?
419
11-Jul-2023
Updated on 12-Jul-2023
Aryan Kumar
12-Jul-2023To create a unique constraint that also allows nulls, you can use the following syntax:
SQL
This will create a unique constraint on the
namecolumn, but will allow null values. If you try to insert a row with a non-null value fornamethat is already in the table, the insert will fail. However, you can insert multiple rows with a null value forname.Here is an explanation of the syntax:
CREATE TABLEcreates a new table.mytableis the name of the new table.idis an integer column that is not null.nameis a varchar column that can be null.CONSTRAINT uc_nameis the name of the unique constraint.UNIQUEspecifies that the values in thenamecolumn must be unique.(name)specifies the column that the unique constraint applies to.WHERE name IS NOT NULLspecifies that the unique constraint only applies to rows where thenamecolumn is not null.Tehran Noorani
12-Jul-2023Sure, here's how you can create a unique constraint that also allows null:
SQL
In this example, the
namecolumn is allowed to contain null values. However, theunique_nameconstraint will still prevent duplicate rows from being inserted into the table, even if one or both of thenamevalues are null.Here's an explanation of the code:
CREATE TABLEstatement creates a new table calledmy_table.idcolumn is an integer column that cannot be null.namecolumn is a string column that can be null.CONSTRAINT unique_name UNIQUE (name)clause creates a unique constraint on thenamecolumn. This means that no two rows in the table can have the same value in thenamecolumn, even if one or both of the values are null.To insert a row into the table, you would use the following syntax:
SQL
You could also insert a row with a null value in the
namecolumn:SQL
In either case, the
unique_nameconstraint would prevent you from inserting a second row with the same value in thenamecolumn, even if the value is null.