Fields are where you can spell out what each table field means by using certain clauses, such as its type (TYPE), optional default values (DEFAULT), how writes are normalised (VALUE), what counts as valid data (ASSERT), or who may see or change it (PERMISSIONS). A COMMENT is a good place for comparison rules and invariants that are not fully captured by the type alone.
The examples on this page build the schema of a small shop with three tables: customer, product and order. Each example runs on its own, so it repeats the definitions it needs. The DEFINE FIELD reference has the full syntax and one example for each clause.
You need database-level access and an active USE scope, same as for tables.
Computed fields (derived on every read) have their own learn page: Computed fields.
Example usage
The simplest field definition only gives the field a name. It accepts a value of any type.
-- Declare that customers have an email field
DEFINE FIELD email ON TABLE customer;The fields of an object and the items in an array can be defined individually using the . operator for objects, or the indexing operator for arrays. Here a customer's address is an object with two fields, and last_order is a pair of the date and the total of the customer's most recent order.
-- Fields of an object
DEFINE FIELD address ON TABLE customer TYPE object;
DEFINE FIELD address.city ON TABLE customer TYPE string;
DEFINE FIELD address.postcode ON TABLE customer TYPE string;
-- Items of an array
DEFINE FIELD last_order ON TABLE customer TYPE array;
DEFINE FIELD last_order[0] ON TABLE customer TYPE datetime;
DEFINE FIELD last_order[1] ON TABLE customer TYPE decimal;
CREATE customer:ana SET
address = { city: "Leeds", postcode: "LS1 4AP" },
last_order = [d"2026-11-02", 34.5dec];
//- [{ address: { city: 'Leeds', postcode: 'LS1 4AP' }, id: customer:ana, last_order: [d'2026-11-02T00:00:00Z', 34.5dec] }]Simple data types
A product in the shop has a name, a price, a flag for whether it is on sale, and the date it was added to the catalogue.
DEFINE FIELD name ON TABLE product TYPE string;
DEFINE FIELD price ON TABLE product TYPE decimal;
DEFINE FIELD on_sale ON TABLE product TYPE bool;
DEFINE FIELD added_at ON TABLE product TYPE datetime;
-- Fails, because the price is a string
CREATE product:mug SET
name = "Travel mug",
price = "twelve",
on_sale = false,
added_at = time::now();"Couldn't coerce value for field `price` of `product:mug`: Expected `decimal` but found `'twelve'`"A | vertical bar can be used to allow a field to be one of a set of types. The following example shows a field that can be a UUID or an int, for customers imported from two older systems that numbered their customers in different ways.
DEFINE FIELD legacy_id ON TABLE customer TYPE uuid | int;
CREATE customer:ana SET legacy_id = 40213;
CREATE customer:ben SET legacy_id = u"0190c3c4-8e2a-7a4b-9d1e-5f6a7b8c9d0e";Array type
You can also set a field to have the array data type. The array data type can be used to store a list of values. You can also set the data type of the array's contents, as well as the number of items that it must hold.
-- A list of strings
DEFINE FIELD tags ON TABLE product TYPE array<string>;
-- A list of any values, the same as `array<any>`
DEFINE FIELD notes ON TABLE product TYPE array;
-- A list of objects
DEFINE FIELD variants ON TABLE product TYPE array<object>;
-- Exactly five counts, one for each star rating
DEFINE FIELD star_counts ON TABLE product TYPE array<int, 5>
ASSERT $value.all(|$n| $n >= 0);A set removes duplicates and keeps its values in sorted order, so it holds each value at most once. Combined with a literal type, it can hold the sizes a piece of clothing comes in:
DEFINE FIELD sizes ON TABLE product TYPE set<"S" | "M" | "L" | "XL">;
CREATE product:hoodie SET sizes = ["M", "S", "M", "XL"];[{ id: product:hoodie, sizes: {'M', 'S', 'XL'} }]Making a field optional
A field with a type must hold a value of that type, so a CREATE that leaves it out fails. You can make a field optional by wrapping the inner type in an option, which allows you to store NONE values in the field.
For a nullable field in the SQL sense, use string | null to allow NULL, or option<string | null> to allow both NULL and a missing field. The DEFINE FIELD reference compares the three forms.
-- A customer may give a phone number, but does not have to
DEFINE FIELD phone ON TABLE customer TYPE option<string>;
CREATE customer:ana;[{ id: customer:ana }]The same works for a record link. The referred_by field below can store a record<customer> or NONE, because not every customer was referred by another one.
DEFINE FIELD referred_by ON TABLE customer TYPE option<record<customer>>;Flexible objects in schemafull tables
On a SCHEMAFULL table, objects are schemafull by default. The FLEXIBLE field clause (written after TYPE) marks a field so that every object in its type accepts arbitrary keys. This includes objects nested in arrays, options, and unions - not only a top-level TYPE object field.
An order's delivery details are a good fit: the shop requires a postcode, and each courier adds keys of its own.
DEFINE TABLE order SCHEMAFULL;
DEFINE FIELD customer ON TABLE order TYPE record<customer>;
DEFINE FIELD delivery ON TABLE order TYPE object FLEXIBLE;
DEFINE FIELD delivery.postcode ON TABLE order TYPE string;
CREATE ONLY order:1 SET
customer = customer:ana,
delivery = {
postcode: "SW1A 1AA",
courier: "Royal Mail",
note: "Leave with the neighbour"
};Without FLEXIBLE, the delivery field is a schemafull object and only declared subfields such as delivery.postcode are accepted.
With FLEXIBLE, the field accepts any extra keys on delivery while still requiring customer and a valid delivery.postcode.
{
customer: customer:ana,
delivery: {
courier: 'Royal Mail',
note: 'Leave with the neighbour',
postcode: 'SW1A 1AA'
},
id: order:1
} Using the DEFAULT clause to set a default value
You can set a default value for a field using the DEFAULT clause. The default value will be used if no value is provided for the field. A new customer starts with no loyalty points:
DEFINE FIELD points ON TABLE customer TYPE int DEFAULT 0;
CREATE customer:ana;[{ id: customer:ana, points: 0 }] Using the DEFAULT ALWAYS clause
In addition to the DEFAULT clause, you can use the DEFAULT ALWAYS clause to set a default value for a field. The ALWAYS keyword indicates that the DEFAULT clause is used not only on CREATE, but also on UPDATE if the value is empty (NONE).
DEFINE TABLE product SCHEMAFULL;
-- Stock is 0 whenever no number is given
DEFINE FIELD stock ON product TYPE int DEFAULT ALWAYS 0;With the above definition, the stock field will be set to 0 when a new product is created without a value for the stock field or with a value of NONE. When an existing product is updated with a value specified, the result will be the new value.
In the case of NULL or a mismatching type, an error will be returned.
-- Setup from the example above
DEFINE TABLE product SCHEMAFULL;
DEFINE FIELD stock ON product TYPE int DEFAULT ALWAYS 0;
CREATE product:mug SET stock = NULL;"Couldn't coerce value for field `stock` of `product:mug`: Expected `int` but found `NULL`"On the other hand, if a valid number is provided during creation or update, that number will be used instead of the default value. Setting the field back to NONE gives the default again.
-- Setup from the example above
DEFINE TABLE product SCHEMAFULL;
DEFINE FIELD stock ON product TYPE int DEFAULT ALWAYS 0;
CREATE product:mug;
//- [{ id: product:mug, stock: 0 }]
UPSERT product:mug SET stock = 25;
//- [{ id: product:mug, stock: 25 }]
UPSERT product:mug SET stock = NONE;
//- [{ id: product:mug, stock: 0 }] Using the VALUE clause to set a field's value
The VALUE clause differs from DEFAULT. A default value is only calculated if no other value is given, and otherwise the value given in a query is accepted. An order's placed_at field with a default accepts the date that a query gives it:
DEFINE FIELD placed_at ON TABLE order DEFAULT time::now();
CREATE order:1 SET placed_at = d"2026-11-02T09:30:00Z";
//- [{ id: order:1, placed_at: d'2026-11-02T09:30:00Z' }]
UPDATE order:1 SET placed_at = d"2026-11-03T14:00:00Z";
//- [{ id: order:1, placed_at: d'2026-11-03T14:00:00Z' }]A VALUE clause, on the other hand, will ignore attempts to set the field to any other value. That suits an updated_at field, which should always hold the time of the last write:
DEFINE FIELD updated_at ON TABLE order VALUE time::now();
-- Both statements ignore the date and store the current time
CREATE order:1 SET updated_at = d"2000-01-01";
UPDATE order:1 SET updated_at = d"2000-01-01";
order:1.updated_at > d"2000-01-01";
//- trueAs the example above shows, a VALUE clause sets the value every time a record is modified (created or updated). However, the value will not be recalculated in a SELECT statement, which simply accesses the current set value.
To create a field that is calculated each time it is accessed, a computed field can be used. The example below reads an order twice and compares the two fields:
DEFINE FIELD updated_at ON TABLE order VALUE time::now();
DEFINE FIELD read_at ON TABLE order COMPUTED time::now();
CREATE order:1;
LET $first = SELECT * FROM ONLY order:1;
SLEEP 10ms;
LET $second = SELECT * FROM ONLY order:1;
-- `updated_at` is the same in both reads
$first.updated_at = $second.updated_at;
//- true
-- `read_at` is calculated again for each read
$first.read_at = $second.read_at;
//- falseAltering a passed value
You can alter a passed value using the VALUE clause. This is useful for altering the value of a field before it is stored in the database.
In the example below, the VALUE clause is used to ensure that a customer's email address is always stored in lowercase characters by using the string::lowercase function.
DEFINE FIELD email ON TABLE customer TYPE string
VALUE $value.lowercase();
CREATE customer:ana SET email = "Ana.Silva@Example.COM";[{ email: 'ana.silva@example.com', id: customer:ana }]Asserting rules on fields
You can take your field definitions even further by using asserts. Assert can be used to ensure that your data remains consistent. For example you can use asserts to ensure that a field is always a valid email address, or that a number is always positive.
The customer's email field from the example above can also check that the address is a properly formatted email address:
DEFINE FIELD email ON TABLE customer TYPE string
VALUE $value.lowercase()
ASSERT $value.is_email();
CREATE customer:ben SET email = "ben at example.com";"Found 'ben at example.com' for field `email`, with record `customer:ben`, but field must conform to: $value.is_email()"As the ASSERT clause expects an expression that returns a boolean, an assertion with a custom message can be manually created by returning true in one case and using a THROW clause otherwise.
DEFINE FIELD quantity ON TABLE order TYPE int ASSERT {
IF $value > 0 {
RETURN true
} ELSE {
THROW "Order " + <string>$this.id + " needs a quantity of at least 1, not " + <string>$value
}
};
CREATE order:2 SET quantity = 0;'An error occurred: Order order:2 needs a quantity of at least 1, not 0' Making a field READONLY
The READONLY clause can be used to prevent any updates to a field. This is useful for fields that are set once by the system. To make a field READONLY, add the READONLY clause to the DEFINE FIELD statement. In the example below, the date a customer joined is set when the record is created, and an attempt to change it fails while other fields can still be updated.
DEFINE FIELD joined_at ON TABLE customer TYPE datetime
DEFAULT time::now() READONLY;
CREATE customer:ana;
UPDATE customer:ana SET name = "Ana";
UPDATE customer:ana SET joined_at = d"2020-01-01";"Found changed value for field `joined_at`, with record `customer:ana`, but field is readonly"Use DEFAULT rather than VALUE with READONLY for a field like this. A VALUE clause runs on every write, so VALUE time::now() READONLY would compute a new time on the first update and refuse it.
Setting permissions on fields
By default, the permissions on a field are set to FULL unless otherwise specified. That means once a table allows an operation for a record user, the field is included unless you narrow it with your own PERMISSIONS clause. Tables default the other way: omitting table PERMISSIONS stores PERMISSIONS NONE.
DEFINE FIELD name ON TABLE product TYPE string;
INFO FOR TABLE product;{
events: {},
fields: {
name: 'DEFINE FIELD name ON product TYPE string PERMISSIONS FULL'
},
indexes: {},
lives: {},
tables: {}
}You can set permissions on fields to control who can perform operations on them using the PERMISSIONS clause. The PERMISSIONS clause can be used to set permissions for SELECT, CREATE, and UPDATE operations. The DELETE operation only relates to records and, as such, is not available for fields.
Like table permissions, field permissions apply to record users (and guests when enabled), not to system users.
The shop shows its products to every customer, but the price it paid the supplier is for its staff only:
DEFINE FIELD cost_price ON TABLE product TYPE decimal
PERMISSIONS
FOR select, create, update WHERE $auth.role = "staff";Order of operations when setting a field's value
When a record is written, a field whose VALUE, DEFAULT or COMPUTED clause reads another field is evaluated after that field. In the example below, a product's full_sku reads category and sku, so it is evaluated after both have been converted to uppercase:
DEFINE TABLE product SCHEMAFULL;
DEFINE FIELD category ON TABLE product TYPE string VALUE $value.uppercase();
DEFINE FIELD sku ON TABLE product TYPE string VALUE $value.uppercase();
DEFINE FIELD full_sku ON TABLE product VALUE category + '-' + sku;
CREATE product:mug SET category = "mug", sku = "tm01";[{ category: 'MUG', full_sku: 'MUG-TM01', id: product:mug, sku: 'TM01' }]Fields that do not read each other are evaluated in the order they were defined, and ASSERT clauses run afterwards, once every field holds its final value. Two fields whose values each read the other form a cycle, which SurrealDB refuses when the second field is defined. See Field evaluation order for the details.
Before 3.3.0, fields were evaluated in alphabetical order of their names. On those versions full_sku is evaluated before sku has been converted, and the example above gives 'MUG-tm01'.
Defining a literal on a field
A field can also be defined as a literal type, by specifying one or more possible values and/or permitted types. An order can come without gift wrap, with standard gift wrap, or with gift wrap and a message:
DEFINE FIELD gift_wrap ON TABLE order
TYPE "none" | "standard" | { message: string };
CREATE order:3 SET gift_wrap = { message: "Happy birthday, Sam!" };
//- [{ gift_wrap: { message: 'Happy birthday, Sam!' }, id: order:3 }]
CREATE order:4 SET gift_wrap = "deluxe";"Couldn't coerce value for field `gift_wrap` of `order:4`: Expected `'none' | 'standard' | { message: string }` but found `'deluxe'`"