Convert SQL ENUM to Sequelize DataTypes.ENUM
Learn how SQL ENUM column types with predefined values are converted to Sequelize DataTypes.ENUM with the same value constraints in the model definition.
Detailed Explanation
ENUM Types in Sequelize
SQL ENUM columns restrict values to a predefined set. Sequelize provides DataTypes.ENUM which enforces the same constraint at the ORM level and generates appropriate database-level constraints.
Basic ENUM Conversion
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
status ENUM('pending', 'processing', 'shipped', 'delivered') NOT NULL DEFAULT 'pending',
priority ENUM('low', 'medium', 'high') DEFAULT 'medium'
);
Order.init({
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
status: {
type: DataTypes.ENUM('pending', 'processing', 'shipped', 'delivered'),
allowNull: false,
defaultValue: 'pending',
},
priority: {
type: DataTypes.ENUM('low', 'medium', 'high'),
allowNull: true,
defaultValue: 'medium',
},
}, { ... });
Database Compatibility
DataTypes.ENUM behavior varies by database:
- MySQL: Creates a native ENUM column type
- PostgreSQL: Creates a custom type via
CREATE TYPEunder the hood - SQLite: Uses a CHECK constraint to enforce allowed values
- SQL Server: Uses a CHECK constraint
TypeScript Integration
When using TypeScript, define an enum or union type alongside the model:
type OrderStatus = 'pending' | 'processing' | 'shipped' | 'delivered';
interface OrderAttributes {
id: number;
status: OrderStatus;
}
When to Use ENUM vs String
ENUMs are ideal when you have a small, fixed set of values that rarely changes (e.g., status codes, roles, priorities). If the value set changes frequently, consider using a DataTypes.STRING with application-level validation instead, since altering ENUM values requires a database migration.
Use Case
You are converting an e-commerce database where order status and payment method columns use MySQL ENUM types. The Sequelize model needs to preserve these constraints for data integrity.
Try It — SQL to Sequelize Model
Related Topics
Map SQL VARCHAR and TEXT to Sequelize STRING and TEXT
Basic Models
Convert SQL DEFAULT Values to Sequelize defaultValue
Advanced Features
Convert SQL JSON and JSONB to Sequelize DataTypes
Data Types
Convert a Simple SQL Table to a Sequelize Model
Basic Models
Convert SQL UNIQUE Constraints to Sequelize unique Options
Advanced Features