#9057·sequelize

Alter queries generated by sequelize.sync with alter: true report syntax problems with UNIQUE columns without an index name

Author: jsantaCreated Feb 15, 2018Updated Sep 23, 2026

What are you doing?

While syncing using alter: true the alter queries generated for a column defined with unique: true have an invalid syntax.

javascript
// Model
const User = sequelize.define('User',
    {
        id: {
            type: Sequelize.INTEGER,
            autoIncrement: true,
            primaryKey: true,
            allowNull: false
        },
        email: {
            type: Sequelize.STRING,
            allowNull: false,
            unique: true,
            set(val) {
                const email = (!val) ? this.getDataValue('username') : val;
                this.setDataValue('email', email.toLowerCase());
            },
            validate: {
                isEmail: true
            }
        },
        isValidated: {
            type: Sequelize.BOOLEAN,
            defaultValue: false
        }
    },
    {
        timestamps: true,
        freezeTableName:true,
        paranoid: true
    }
);

exports.User = User;
// DB Sync
var sequelize = db.sequelize;
    sequelize.sync({
        force: false,
        logging: dbLog,
        alter: true
    }).then(function () { /* ... */ });

What do you expect to happen?

Alter queries executed without any syntax error

What is actually happening?

Alter queries built with an invalid syntax.

Output messages

{
RequestError: Incorrect syntax near the keyword 'UNIQUE'. [...]
sql: 'ALTER TABLE [User] ALTER COLUMN [email] NVARCHAR(255) NOT NULL UNIQUE;'
}

Workaround

Modify the model definition to have a name for the unique index associated for the column:

javascript
// Model
const User = sequelize.define('User',
    {
        id: {
            type: Sequelize.INTEGER,
            autoIncrement: true,
            primaryKey: true,
            allowNull: false
        },
        email: {
            type: Sequelize.STRING,
            allowNull: false,
            unique: 'usr_email',
            set(val) {
                const email = (!val) ? this.getDataValue('username') : val;
                this.setDataValue('email', email.toLowerCase());
            },
            validate: {
                isEmail: true
            }
        },
        isValidated: {
            type: Sequelize.BOOLEAN,
            defaultValue: false
        }
    },
    {
        timestamps: true,
        freezeTableName:true,
        paranoid: true
    }
);

exports.User = User;

Dialect: mssql Dialect version: 4.29.2 Database version: MS Sql 2017 running on Ubuntu Linux Sequelize version: 4.29.2 Tested with latest release: No