Skip to content

Unique constraints

Unique constraints are defined in the constraints object of table definition using the unique function.

Single column

ts
import { table, text, unique } from "@monolayer/pg/schema";

export const users = table({
  columns: {
    name: text(), 
    email: text(),
  },
  constraints: {
    unique: unique(["name"]), 
  },
});

Multiple columns

ts
import { table, text, unique } from "@monolayer/pg/schema";

export const users = table({
  columns: {
    name: text(), 
    email: text(), 
  },
  constraints: {
    unique: unique(["name", "email"]), 
  },
});

With NULLS NOT DISTINCT

Since NULL values are not considered equal to each other, multiple duplicated rows with NULL values on the constrained column(s) are allowed to exist without violating the unique constraint.

If you want to prevent this, you can use the nullsNotDistinct to consider null values NOT DISTINCT.

ts
import { table, text, unique } from "@monolayer/pg/schema";

export const users = table({
  columns: {
    name: text(), 
    email: text(),
  },
  constraints: {
    unique: unique(["name"]).nullsNotDistinct(), 
  },
});