Junior — Middle
Can you explain what a unique index in an SQL database is and in what cases it is used?
sobes.tech AI
Answer from AI
A unique index in a SQL database is a data structure that ensures the uniqueness of values in one or more columns of a table. This means that in the column or combination of columns on which a unique index is imposed, there cannot be two identical values.
Unique indexes are used for:
- Ensuring data integrity, for example, to prevent duplicates in a column with email or passport number.
- Speeding up searches and queries on unique fields.
Example of creating a unique index in SQL:
CREATE UNIQUE INDEX idx_unique_email ON Users(email);
In C# with Entity Framework, you can set a unique index through Fluent API:
modelBuilder.Entity<User>()
.HasIndex(u => u.Email)
.IsUnique();
Thus, a unique index helps guarantee that the data in the database will not contain duplicate values for the specified fields.