Junior — Middle
Is it possible to create a unique composite index in a database?
sobes.tech AI
Answer from AI
Yes, in databases, you can create a unique composite index that ensures the uniqueness of a combination of values across multiple columns.
For example, in SQL:
CREATE UNIQUE INDEX idx_unique_name_email ON users (name, email);
This guarantees that there will be no two rows in the users table with the same combination of name and email.
A composite unique index is useful when uniqueness is not determined by a single field but by a combination of several.
In ORM, for example in SQLAlchemy (Python), it can be defined as:
from sqlalchemy import UniqueConstraint
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
__table_args__ = (
UniqueConstraint('name', 'email', name='uix_name_email'),
)
Thus, a unique composite index is a standard practice to ensure uniqueness across multiple columns.