Cerial
DecoratorsArray

@distinct

Enforce uniqueness within array fields at the database level.

Enforces uniqueness within an array field at the database level. When applied, SurrealDB automatically deduplicates values — duplicate entries are silently removed.

Syntax

model Article {
  id Record @id
  title String
  tags String[] @distinct
}

Behavior

SurrealDB enforces the distinct constraint at the storage level. If you push a value that already exists in the array, the duplicate is automatically removed.

await db.Article.create({
  data: { title: 'Hello', tags: ['typescript', 'tutorial', 'typescript'] },
});
// tags stored as: ['typescript', 'tutorial'] — duplicate removed

await db.Article.updateMany({
  where: { id: articleId },
  data: { tags: { push: ['tutorial'] } },
});
// tags still: ['typescript', 'tutorial'] — duplicate not added

Combining with @sort

@distinct can be combined with @sort to maintain a unique, ordered array:

model Article {
  id Record @id
  categories String[] @distinct @sort
}

When both are applied, values are both deduplicated and kept in sorted order.

await db.Article.create({
  data: { categories: ['zebra', 'apple', 'mango', 'apple'] },
});
// categories stored as: ['apple', 'mango', 'zebra'] — deduplicated and sorted

On Object Fields

@distinct can be applied to array fields within object definitions:

object ContactInfo {
  email Email
  tags String[] @distinct
}

model User {
  id Record @id
  contact ContactInfo
}

The deduplication is enforced at the database level, just like on model fields.

Applicable Types

@distinct can be applied to any array field (on models or objects):

model Example {
  id Record @id
  uniqueTags String[] @distinct
  uniqueScores Int[] @distinct
  uniqueRatings Float[] @distinct
  uniqueFlags Bool[] @distinct
  uniqueDates Date[] @distinct
  uniqueUuids Uuid[] @distinct
  uniqueDurations Duration[] @distinct
  uniqueNumbers Number[] @distinct
  uniqueBytes Bytes[] @distinct
  uniqueGeometries Geometry[] @distinct
  uniqueAnyValues Any[] @distinct
}

@distinct cannot be used on Relation[] fields (virtual) or on Record[] fields that are paired with a Relation (the PK side is implicitly distinct). Use @set if you need both deduplication and sorting.

On this page