Skip to content

Tables and fields

Tables

A table is the first structural unit most people define: it is a named home for records. The examples on this page build the tables of a small shop, with customers, products, orders and the purchases that link them. Even a SELECT statement requires a table to be defined before it will work.

SELECT * FROM product;
//- "The table 'product' does not exist"
DEFINE TABLE product;
SELECT * FROM product;
//- []

As a convenience, the creation of a record in a non-strict database will define the table for you. The following example does not return any errors because the table definition will exist once CREATE is executed.

CREATE product:mug SET name = "Travel mug";
SELECT * FROM product;
Output
[{ id: product:mug, name: 'Travel mug' }]

DEFINE TABLE can also set high-level rules, such as whether new fields are allowed without a definition, whether records are normal documents or graph edges, whether the table is a pre-computed view, and who may select / create / update / delete. A COMMENT is optional, and is useful when the table's role, record-ID convention, or graph edges would otherwise be unclear to readers or to agents that load the schema via INFO or MCP.

Individual fields still use DEFINE FIELD; the table statement does not replace that.

You need appropriate auth (root, namespace, or database owner/editor) and an active USE for namespace and database. Full grammar and every clause live under DEFINE TABLE in the reference.

A CHANGEFEED records every change to a table's records for a period of time. After creating, updating, and deleting records in the table as usual, SHOW CHANGES FOR returns the mutations recorded in that window, starting from a version number or a datetime after the changefeed began. If an entry reflects an update to an existing record and the feed stores differences (INCLUDE ORIGINAL), the diff is a reverse diff, namely the operations needed to reach the state immediately before that write. See DEFINE TABLE for full examples and response shapes.

The shop keeps three days of changes to its orders, so that another service can read what changed:

-- Keep three days of changes to the order table
DEFINE TABLE order CHANGEFEED 3d;

CREATE order:1 SET total = 25;
UPDATE order:1 SET total = 30;

-- Read the changes since version 0
SHOW CHANGES FOR TABLE order SINCE 0 LIMIT 10;

The output holds one entry for the table definition and one for each write, each with a versionstamp that differs on every run:

Example output
[
	{
		changes: [
			{
				define_table: {
					changefeed: { expiry: 3d, original: false },
					drop: false,
					id: 0,
					kind: { kind: 'ANY' },
					name: 'order',
					permissions: { create: false, delete: false, select: false, update: false },
					schemafull: false
				}
			}
		],
		versionstamp: 117624152836407296
	},
	{
		changes: [{ update: { id: order:1, total: 25 } }],
		versionstamp: 117624152836472832
	},
	{
		changes: [{ update: { id: order:1, total: 30 } }],
		versionstamp: 117624152836472833
	}
]

The following example demonstrates the SCHEMAFULL portion of the DEFINE TABLE statement. When a table is defined as schemafull, the database strictly enforces any schema definitions that are specified using the DEFINE TABLE statement. New fields can not be added to a SCHEMAFULL table unless they are defined via the DEFINE FIELD statement.

DEFINE TABLE customer SCHEMAFULL;
DEFINE FIELD name ON TABLE customer TYPE string;
DEFINE FIELD email ON TABLE customer TYPE string
  ASSERT $value.is_email();

-- Succeeds, as every field is defined and valid
CREATE customer:ana CONTENT {
    name: 'Ana Silva',
    email: 'ana@example.com'
};
//- [{ email: 'ana@example.com', id: customer:ana, name: 'Ana Silva' }]

-- Fails, because `newsletter` is not a defined field
CREATE customer:ben CONTENT {
    name: 'Ben Okafor',
    email: 'ben@example.com',
    newsletter: true
};
Error output
"Found field 'newsletter', but no such field exists for table 'customer'"

The following example demonstrates the SCHEMALESS portion of the DEFINE TABLE statement. This allows you to explicitly state that the specified table has no schema. The fields that are defined are still checked, and any other field is accepted.

DEFINE TABLE customer SCHEMALESS;
DEFINE FIELD name ON TABLE customer TYPE string;
DEFINE FIELD email ON TABLE customer TYPE string
  ASSERT $value.is_email();

-- Succeeds even with the extra `newsletter` field
CREATE customer:ana CONTENT {
    name: 'Ana Silva',
    email: 'ana@example.com',
    newsletter: true
};
//- [{ email: 'ana@example.com', id: customer:ana, name: 'Ana Silva', newsletter: true }]

-- Fails, because `email` does not pass validation
CREATE customer:ben CONTENT {
    name: 'Ben Okafor',
    email: 'ben.okafor',
    newsletter: false
};
Error output
"Found 'ben.okafor' for field `email`, with record `customer:ben`, but field must conform to: $value.is_email()"

In SurrealDB, like in other databases, you can create views. The way you create views is using the DEFINE TABLE statement like you would for any other table, then adding the AS clause at the end with your SELECT query.

DROP tables are useful in combination with events or foreign (view) tables, as you can compute a record and drop the input. The shop counts how often each product page is viewed, without keeping a record of every single view:

-- Records written to page_view are not stored
DEFINE TABLE page_view DROP;
-- A view that counts the page views of each product
DEFINE TABLE product_views AS
    SELECT count() AS views, product
    FROM page_view
    GROUP BY product;

CREATE page_view SET product = product:mug;
CREATE page_view SET product = product:mug;
CREATE page_view SET product = product:lamp;

SELECT * FROM product_views;
//- [{ id: product_views:[product:lamp], product: product:lamp, views: 1 }, { id: product_views:[product:mug], product: product:mug, views: 2 }]
SELECT * FROM page_view;
//- []

Table PERMISSIONS control what record users (and guests, when guest access is enabled) may do with records in that table. They do not restrict system users at the root, namespace, or database level, as those users are governed by roles instead.

If you omit the clause, SurrealDB will default to PERMISSIONS NONE which denies SELECT, CREATE, UPDATE, and DELETE for record users until you grant access explicitly. The opposite shorthand is PERMISSIONS FULL, which allows all four operations. The output of INFO FOR DB shows the default for a table defined by a CREATE statement and for one defined by DEFINE TABLE:

CREATE customer:ana;
DEFINE TABLE order;

INFO FOR DB;
Output
{
	accesses: {},
	analyzers: {},
	apis: {},
	buckets: {},
	compatibility: 4,
	configs: {},
	extensions: {},
	functions: {},
	models: {},
	params: {},
	sequences: {},
	tables: {
		customer: 'DEFINE TABLE customer TYPE ANY SCHEMALESS PERMISSIONS NONE',
		order: 'DEFINE TABLE order TYPE ANY SCHEMALESS PERMISSIONS NONE'
	},
	types: {},
	users: {}
}

You can also set independent rules for selecting, creating, updating, and deleting data. Each FOR clause is a SurrealQL expression evaluated in the context of the current authentication (often using the $auth parameter which is set when a record user authenticates).

In the shop, a customer signs in as a record user and sees only their own orders, while staff see and manage all of them:

DEFINE TABLE order SCHEMALESS
	PERMISSIONS
		FOR select
			-- A customer sees their own orders, and staff see every order
			WHERE customer = $auth.id OR $auth.role = "staff"
		FOR create
			-- A customer can only place an order for themselves
			WHERE customer = $auth.id
		FOR update, delete
			-- Only staff change or cancel an order
			WHERE $auth.role = "staff";

Field permissions work the same way but default to PERMISSIONS FULL instead of NONE. The table is the main access gate, while field permissions only narrow further when you need to (for example hiding a password). With FULL, a field follows the table's rules without adding its own. See Setting permissions on fields and Permissions & row-level security.

When defining a table in SurrealDB, you can specify the type of data that can be stored in the table. This can be done using the TYPE clause, followed by either ANY, NORMAL, or RELATION.

With TYPE ANY, you can specify a table to store any type of data, whether it's a normal record or a relational record.

With TYPE NORMAL, you can specify a table to only store "normal" records, and not relations. When a table is defined as TYPE NORMAL, it will not be able to store relations. This can be useful when you want to restrict the type of data that can be stored in a table in schemafull mode.

Finally, with TYPE RELATION, you can specify a table to only store relational type content. This can be useful when you want to restrict the type of data that can be stored in a table.

DEFINE TABLE order TYPE ANY;
-- The same definition, as TYPE ANY is the default
DEFINE TABLE OVERWRITE order;

With TYPE NORMAL, you can specify a table to only store "normal" records, and not relations. A customer is a normal record, never a link between two others:

DEFINE TABLE customer TYPE NORMAL;

With TYPE RELATION, you can specify a table to only store relational type content, and restrict what kind of relations can be stored. The shop's bought table links a customer to what they bought:

-- Only relations, between any two records
DEFINE TABLE bought TYPE RELATION;

-- Only relations from a customer to a product
DEFINE TABLE OVERWRITE bought TYPE RELATION FROM customer TO product;
-- IN and OUT are the same as FROM and TO
DEFINE TABLE OVERWRITE bought TYPE RELATION IN customer OUT product;
-- Use | to allow one of several tables
DEFINE TABLE OVERWRITE bought TYPE RELATION FROM customer TO product | gift_card;
DEFINE TABLE OVERWRITE bought TYPE RELATION IN customer OUT product | gift_card;

A relation that goes the wrong way is refused:

DEFINE TABLE bought TYPE RELATION FROM customer TO product;
CREATE customer:ana, product:mug;

RELATE product:mug->bought->customer:ana;
Error output
"Couldn't coerce value for field `in` of `bought:03u2q4cy5qtmki73eg3q`: Expected `record<customer>` but found `product:mug`"

As relations are represented by standalone tables, they can be constructed before any linked records exist. A query that starts from the linked records finds nothing until those records are created. Here the customer table does not exist yet, so the first SELECT returns an error.

-- Succeeds, although neither record exists
RELATE customer:ana->bought->product:mug SET quantity = 2;

SELECT ->bought->product FROM customer;
//- "The table 'customer' does not exist"

CREATE customer:ana, product:mug;
SELECT ->bought->product FROM customer;
//- [{ "->bought": { "->product": [product:mug] } }]

If this behaviour is not desirable, the ENFORCED clause can be used on a table of TYPE RELATION to disallow a RELATE statement from working unless it points to existing data.

DEFINE TABLE bought TYPE RELATION IN customer OUT product ENFORCED;
CREATE customer:ana;

-- Fails, because the shop has no product:lamp
RELATE customer:ana->bought->product:lamp SET quantity = 1;
Error output
"The record 'product:lamp' does not exist"

Was this page helpful?

Last updated