Convert SQL UNIQUE Constraints to Sequelize unique Options
See how SQL column-level UNIQUE, table-level UNIQUE constraints, and composite unique indexes are represented in Sequelize model definitions.
Detailed Explanation
Unique Constraints in Sequelize
SQL offers three ways to define unique constraints, and the converter handles all of them: column-level UNIQUE, table-level UNIQUE constraints, and CREATE UNIQUE INDEX statements.
Column-Level UNIQUE
email VARCHAR(255) NOT NULL UNIQUE
-- becomes -->
email: { type: DataTypes.STRING(255), allowNull: false, unique: true }
Table-Level UNIQUE Constraint
CREATE TABLE team_members (
team_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
role VARCHAR(50),
UNIQUE (team_id, user_id)
);
Composite unique constraints become entries in the indexes array:
TeamMember.init({ ... }, {
sequelize,
indexes: [
{ fields: ['team_id', 'user_id'], unique: true },
],
});
CREATE UNIQUE INDEX
External unique index statements are also converted:
CREATE UNIQUE INDEX idx_email_org ON users(email, organization_id);
-- becomes -->
indexes: [
{ fields: ['email', 'organization_id'], unique: true },
]
Single vs Composite
The converter distinguishes between single-column and composite unique constraints:
- Single-column: Sets
unique: trueon the field definition - Multi-column: Adds an entry to the model's
indexesarray withunique: true
Validation Behavior
When unique: true is set, Sequelize performs:
- A pre-insert query to check for duplicates (in some configurations)
- Relies on the database constraint for authoritative enforcement
- Throws a
SequelizeUniqueConstraintErrorif the constraint is violated
This two-layer approach means your application gets a clean JavaScript error rather than a raw database error.
Use Case
You are converting a multi-tenant SaaS database where several tables have composite unique constraints (e.g., unique email per organization). The converter ensures these constraints are properly represented in Sequelize's indexes configuration.
Try It — SQL to Sequelize Model
Related Topics
Convert SQL Composite Primary Keys to Sequelize Indexes
Advanced Features
Convert a Simple SQL Table to a Sequelize Model
Basic Models
Convert SQL FOREIGN KEY to Sequelize belongsTo Association
Associations
Convert SQL DEFAULT Values to Sequelize defaultValue
Advanced Features
Convert SQL Junction Tables to Sequelize belongsToMany
Advanced Features