Constraint biểu diễn rule dữ liệu như primary key, foreign key, unique, check, not null. Index là cấu trúc truy cập để tăng tốc query hoặc hỗ trợ constraint. Một unique constraint thường tạo unique index phía dưới, nhưng không phải index nào cũng là business constraint.
Ví dụ business invariant nên dùng constraint:
sql
ALTER TABLE users ADD CONSTRAINT users_email_unique UNIQUE (email);
ALTER TABLE orders ADD CONSTRAINT positive_total CHECK (total >= 0);Nếu chỉ tạo index để nhanh hơn, đừng nhầm nó với rule dữ liệu nếu không có uniqueness/check semantics.