Constraints and indexes
postgrelize extensions
Sections marked postgrelize extension describe options, methods and statements that Sequelize v6 does not have. Everything else here behaves as in v6. All extensions are listed on the extensions page.
addIndex and addConstraint cover the Sequelize v6 shapes (see Schema). This page lists the PostgreSQL additions. They are new options: existing option shapes and defaults do not change.
Expression indexes postgrelize extension
await queryInterface.addIndex('accounts', {
name: 'accounts_lower_email',
unique: true,
fields: [{ expression: 'lower(email)' }],
include: ['nick'],
});
await queryInterface.addIndex('accounts', {
name: 'accounts_nick_search',
fields: [
{ name: 'nick', collate: 'C', operator: 'text_pattern_ops', order: 'DESC', nulls: 'LAST' },
],
});- An index field is a column (
'email',{ name: 'email' }) or an expression ({ expression: 'lower(email)' }). Every field acceptsorder,nulls('FIRST'/'LAST'),collate(a quoted collation name) andoperator(operator class);includeadds covering columns. - The
expressionis SQL you write. It is wrapped in parentheses and is not escaped: never build it from user input. See Security. - A name cannot be derived from an expression, so an index with an expression field needs an explicit
name. - Model
indexesaccept the same fields. An expression must be immutable (PostgreSQL rejectsdate_truncontimestamptz, for example).
EXCLUDE constraints postgrelize extension
await queryInterface.addConstraint('bookings', {
type: 'exclude',
name: 'bookings_no_overlap',
using: 'gist',
exclude: [
{ name: 'room', with: '=' },
{ name: 'period', with: '&&' },
],
});addConstraint(table, { type: 'exclude', exclude: [{ name | expression, with }], using, where, include, deferrable }). Each element is a column or an expression with the operator it is compared with (with), and acceptscollate,operator(operator class),orderandnulls.- Scalar columns with
=in agist/spgistexclusion need thebtree_gistextension (createExtension('btree_gist')). - The operator is checked against a pattern of operator characters (
=,&&,-|-,<->); a name or expression cannot be smuggled in. Expressions are trusted SQL (see above).whereis a where-object compiled like a partial-index condition;deferrabletakes aDeferrableconstant. - Without
namethe constraint is called<table>_<columns>_excl; with an expression element give aname. - A violation raises
ExclusionConstraintError.
NOT VALID and VALIDATE CONSTRAINT postgrelize extension
await queryInterface.addConstraint('products', {
type: 'check',
fields: ['price'],
name: 'products_price_positive',
where: { price: { [Op.gt]: 0 } },
notValid: true,
});
await sequelize.query('UPDATE products SET price = 1');
await queryInterface.validateConstraint('products', 'products_price_positive');notValid: true (check and foreign key constraints) adds the constraint without scanning existing rows, so it takes only a short lock; new and updated rows are checked at once. After cleaning the old rows, validateConstraint(table, name) scans the table without blocking writes. Using notValid with another constraint type throws.
Declarative partitioning postgrelize extension
await queryInterface.createTable(
'events',
{ at: DataTypes.DATE, kind: DataTypes.TEXT },
{ partitionBy: { strategy: 'range', columns: ['at'] } },
);
await queryInterface.createPartition('events', 'events_2026', {
from: ['2026-01-01'],
to: ['2027-01-01'],
});
await queryInterface.createPartition('events', 'events_other', { default: true });
await queryInterface.createTable('events_2027', { at: DataTypes.DATE, kind: DataTypes.TEXT });
await queryInterface.attachPartition('events', 'events_2027', {
from: ['2027-01-01'],
to: ['2028-01-01'],
});
await queryInterface.detachPartition('events', 'events_2026');createTable(name, attributes, { partitionBy: { strategy: 'range' | 'list' | 'hash', columns } })creates the partitioned parent. Columns are names or{ name | expression, collate, operator }; anexpressionis trusted SQL. Primary and unique keys must include every partition column (PostgreSQL rule).createPartition(parent, name, bound, { partitionBy, ifNotExists })bounds:{ in: [...] }for list,{ from: [...], to: [...] }for range (PartitionBound.MINVALUE/MAXVALUEare markers, a string'MINVALUE'is just a string),{ modulus, remainder }for hash and{ default: true }. Values are literals.partitionBymakes the partition itself partitioned.attachPartition(parent, existingTable, bound)anddetachPartition(parent, partition, { concurrently, finalize }).concurrentlycannot run inside a transaction.- Partitions are real tables:
showAllTableslists them,describeTableworks on parent and partitions, and queries and models on the parent work as usual.syncdoes not create partitions: create them withcreatePartition.
PostgreSQL 18 constraints postgrelize extension
await queryInterface.addConstraint('rooms', {
type: 'primary key',
name: 'rooms_pk',
fields: ['id', 'validAt'],
withoutOverlaps: true,
});
await queryInterface.addConstraint('stays', {
type: 'foreign key',
name: 'stays_room_fk',
fields: ['roomId', 'during'],
period: true,
references: { table: 'rooms', field: 'id', fields: ['id', 'validAt'] },
});await queryInterface.addConstraint('stays', {
type: 'check',
name: 'stays_nights_positive',
fields: ['nights'],
where: { nights: { [Op.gt]: 0 } },
enforced: false,
});These options render PostgreSQL 18 syntax. Older servers reject the statement with their own syntax error; nothing is sent differently by version.
withoutOverlaps: true(unique and primary key): the last field is a range or multirange column and no two rows with equal other fields may overlap. Scalar columns in a temporal key need thebtree_gistextension.period: true(foreign key): the last field and the last referenced field arePERIODcolumns; the referenced table needs awithoutOverlapskey. List the referenced columns withreferences.fields(references.fieldstays the single-column form).enforced: false(check and foreign key):NOT ENFORCEDrecords the constraint without checking it, so it documents a rule or helps the planner. It can be combined withnotValid.