The primary key and unique index: in -depth discussion of its differences
In the database design, is the data integrity constraint a basic decision: Should the primary key or the only index? Although the two concepts are similar, choosing one in actual projects may have a significant impact.
Unique index: Maintenance data unique
The only index compulsory restrictions cannot have the same value in the index column. This attribute ensures that the data remain unique in this column. Consider the following example:
In this scene, the only index on the "name" column ensures that there are not two lines of the same name.Primary key: Multiple -way constraints
<code class="language-sql">CREATE TABLE my_table ( id INT NOT NULL, name VARCHAR(255) UNIQUE );</code>
The primary key not only guarantees the uniqueness, but also guarantees that the column is not NULL. This means that each row will have a unique and non -empty value in the primary column. In addition, the table can only have one primary key, and the primary key will automatically establish an index. For example, in the following example:
The "ID" column acts as the primary key, forcing the uniqueness and non -empty value.
advantages and disadvantages
<code class="language-sql">CREATE TABLE my_table ( id INT PRIMARY KEY NOT NULL, name VARCHAR(255) );</code>
The advantages of the only index:
The uniqueness of the data is enforced, and there is no need to force non -empty value.
In MS SQL Server, the primary key plays a vital role in copying. Each table used in copies requires a unique identifier, which is usually implemented as the main key. This unique identifier ensures that the data can be consistent and updated between the databases that can be copied. Therefore, when designing a database you want to copy, the primary key is usually recommended.
The above is the detailed content of Primary Key vs. Unique Index: When Should I Use Which?. For more information, please follow other related articles on the PHP Chinese website!