@sort
Maintain ordering within array fields at the database level.
Maintains ordering within an array field at the database level. SurrealDB automatically keeps the array sorted after every modification.
Syntax
@sort # ascending order (default)
@sort(true) # ascending order (explicit)
@sort(false) # descending orderAscending Order
@sort or @sort(true) sorts values in ascending order (A–Z, 0–9, earliest–latest):
model Student {
id Record @id
name String
sortedScores Int[] @sort
}await db.Student.create({
data: { name: 'Alice', sortedScores: [85, 42, 97, 63] },
});
// sortedScores stored as: [42, 63, 85, 97]
await db.Student.updateMany({
where: { id: studentId },
data: { sortedScores: { push: [55] } },
});
// sortedScores becomes: [42, 55, 63, 85, 97]Descending Order
@sort(false) sorts values in descending order (Z–A, 9–0, latest–earliest):
model Feed {
id Record @id
name String
recentDates Date[] @sort(false)
}Values are sorted from highest to lowest, so the most recent dates appear first.
Combining with @distinct
@sort and @distinct can be used together for unique, ordered arrays:
model Student {
id Record @id
name String
uniqueSortedTags String[] @distinct @sort
priorities Int[] @distinct @sort(false)
}await db.Student.create({
data: {
name: 'Bob',
uniqueSortedTags: ['zebra', 'apple', 'mango', 'apple'],
priorities: [3, 1, 5, 3, 2],
},
});
// uniqueSortedTags: ['apple', 'mango', 'zebra'] — deduplicated + ascending
// priorities: [5, 3, 2, 1] — deduplicated + descendingOn Object Fields
@sort can be applied to array fields within object definitions:
object Preferences {
favoriteColors String[] @sort
priorityLevels Int[] @sort(false)
}
model User {
id Record @id
preferences Preferences
}The sorting is enforced at the database level, just like on model fields.
Applicable Types
@sort can be applied to any array field (on models or objects):
model Example {
id Record @id
sortedNames String[] @sort
sortedScores Int[] @sort
sortedRatings Float[] @sort
sortedDates Date[] @sort(false)
sortedUuids Uuid[] @sort
sortedDurations Duration[] @sort
sortedNumbers Number[] @sort
sortedBytes Bytes[] @sort
sortedGeometries Geometry[] @sort
sortedAnyValues Any[] @sort
}@sort 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.