Creating a Unique Index
In SQL Server, you can create a unique ssn
) column in the employee
emp_id
), and you want to ensure Social Security numbers are unique, create a unique index on ssn
. If the user enters the same Social Security number for more than one employee, the database displays an error and cannot save the table.
When you create or modify a unique index, you can set an option to ignore duplicate
For example, if you try to update "Smith" to "Jones" in a table where "Jones" already exists, you end up with one "Jones" and no "Smith" in the resulting table. The original "Smith" row is lost because an UPDATE statement is actually a DELETE followed by an INSERT. "Smith" was deleted and the attempt to insert an additional "Jones" failed. The whole transaction cannot be rolled back because the purpose of this option is to allow a transaction in spite of the presence of duplicates.
To create a unique index
- In your database diagram, select the table you want to index, right-click the table, and choose Indexes/Keys from the shortcut menu.
-or-
Open the Table Designer for the table you want to index, right-click in the Table Designer, and choose Indexes/Keys from the shortcut menu.
- Choose New. The Selected index list displays the system-assigned name of the new index.
- Under Column name, select the columns you want to index. You can select up to 16 columns. For optimal performance, select only one or two columns per index. For each column you select, indicate whether the index arranges values of this column in ascending or descending order.
- Select the Create UNIQUE check box.
- Select the Index option.
- Select the Ignore duplicate keys option if you want to ignore new or updated data that would create a duplicate key in the index (with the INSERT or UPDATE statement).
The index is created in the database when you save the table or diagram.
Note You cannot create a unique index on a single column if that column contains NULL in more than one row. Similarly, you cannot create a unique index on multiple columns if the combination of columns contains NULL in more than one row. These are treated as duplicate values for indexing purposes.
See Also
Creating a Unique Constraint | Defining a Primary Key | Indexes | Saving, Displaying, and Updating an Index Definition | Unique Constraints