The DEFINE TABLE statement allows you to declare your table by name, enabling you to apply strict controls to a table's schema and access permissions.
The DEFINE TABLE statement allows you to declare your table by name, enabling you to apply strict controls to a table's schema by making it SCHEMAFULL, create a foreign table view, and set permissions specifying what operations can be performed on the table.
Note
The fields of a table are not defined using DEFINE TABLE, but via individual DEFINE FIELD statements.
Requirements
You must be authenticated as a root owner or editor, namespace owner or editor, or database owner or editor before you can use the DEFINE TABLE statement.
Below shows how you can create a table using the DEFINE TABLE statement.
-- Declare the name of a table. DEFINETABLEreading;
The following example uses the DROP portion of the DEFINE TABLE statement. Marking a table as DROP disallows creating or updating records.
DROP tables are useful in combination with events or foreign (view) tables, as you can compute a record and essentially drop the input.
-- By marking a table as DROP, you disallow any records to be created or updated. -- Records that currently exist in the table will not automatically be deleted, you can still remove them manually. DEFINETABLEreadingDROP;
The following expression shows how you can define a CHANGEFEED for a table. After creating, updating, and deleting records in the table as usual, using SHOW CHANGES FOR will show the changes that have taken place during this time.
If an entry holds a change to an existing record, the diff will show the operation needed to modify the record to the state immediately preceding its current state. In other words, the diff included is a reverse diff.
-- Define the changefeed and its duration -- Optionally, append INCLUDE ORIGINAL to include info -- on the current record before a change took place DEFINETABLEreadingCHANGEFEED3d;
-- Create some records in the reading table CREATEreadingSETstory="Once upon a time"; CREATEreadingSETstory="there was a database"; UPDATEreadingSETis_interesting=true;
-- Replay changes to the reading table since a certain date -- Must be after the timestamp at which the changefeed began SHOWCHANGESFORTABLEreadingSINCEd"2025-09-07T01:23:52Z"LIMIT10;
-- Alternatively, show the changes for the table since a version number SHOWCHANGESFORTABLEreadingSINCE0LIMIT10;
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.
Note
Since v2.0.0, schemafull tables are implicitly type NORMAL tables by default.
-- Create schemafull user table. DEFINETABLEuserSCHEMAFULL;
-- Define some fields. DEFINEFIELDfirstNameONTABLEuserTYPEstring; DEFINEFIELDlastNameONTABLEuserTYPEstring; DEFINEFIELDemailONTABLEuserTYPEstring ASSERTstring::is_email($value); DEFINEINDEXuserEmailIndexONTABLEuserCOLUMNSemailUNIQUE;
-- SEE IT IN ACTION -- 1: Add a user with all required fields and an undefined one, 'photoURI'. CREATEuserCONTENT{ firstName: 'Tobie', lastName: 'Hitchcock', email: 'Tobie.Hitchcock@surrealdb.com', photoURI: 'photo/yxCFi22Jw2.webp' }; -- 2: Statement will not fail but photoURI will be ignored as it is not a -- defined field.
-- 3: Query the data SELECT * FROMuser;
Schemaless tables
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.
-- Create schemaless user table. DEFINETABLEuserSCHEMALESS;
-- Define some fields. DEFINEFIELDfirstNameONTABLEuserTYPEstring; DEFINEFIELDlastNameONTABLEuserTYPEstring; DEFINEFIELDemailONTABLEuserTYPEstring ASSERTstring::is_email($value); DEFINEINDEXuserEmailIndexONTABLEuserCOLUMNSemailUNIQUE;
-- SEE IT IN ACTION - Example 1 -- 1: Add a user with all required fields and an undefined one. CREATEuser:tobieSETfirstName='Tobie', lastName='Hitchcock', email='Tobie.Hitchcock@surrealdb.com', photoURI='photo/yxCFi22Jw2.webp'; -- 2: Statement will succeed because user is a SCHEMALESS table.
-- SEE IT IN ACTION - Example 2 -- 1: Add a user with an invalid email address and include a new field that was never defined. CREATEuser:jaimeSETfirstName='Jamie', lastName='Hitchcock', email='Jamie.Hitchcock', photoURI='photo/yxCFi22Jw2.webp'; -- 2: Statement will fail because the value for email was not valid.
Interaction between fields
While a DEFINE TABLE statement represents a template for any subsequent records to be created, a DEFINE FIELD statement pertains to concrete field data of a record. As such, a DEFINE FIELD statement gives access to the record's other fields through their names, as well as the current field through the $value parameter.
// Creates a `person` with the name "Bob Bobson" CREATEpersonSETfirst_name="Bob", last_name="Bobson";
Pre-computed table views
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.
DEFINETABLEreviewDROP; -- Define a table as a view which aggregates data from the review table DEFINETABLEavg_product_reviewTYPENORMALAS SELECT count() ASnumber_of_reviews, math::mean(<float>rating) ASavg_review, ->product.idASproduct_id, ->product.nameASproduct_name FROMreview GROUPBYproduct_id, product_name;
-- Query the projection SELECT * FROMavg_product_review;
There are a few important things which make our views far more powerful than a typical relational database view and a few limitations to keep in mind.
Starting with what makes them powerful. Our pre-computed table views are most similar to event-based, incrementally updating, materialised views. Let's explain what that means.
Event-based, meaning that when you run add or remove data from the underlying table, in our example, the review table, it triggers a matching event on the avg_product_review table view.
Materialised view, meaning that the first time we run the table view query, it will run the query like a normal SELECT statement, but then materialise the result. Instead of normal views which behave like bookmarked SELECT queries, that just look like tables to the user.
Incrementally updating, meaning that for any subsequent run, it will listen for the event trigger and perform the most efficient operation possible to always keep the result up to date, instead of just running the SELECT statement again.
While this functionality can be replicated in many other databases, it is usually only done by expert users as it can be very complicated to set up and maintain. Therefore, the true power of our pre-computed table views is making this advanced functionality accessible to everyone.
As mentioned though, there are a few limitations to keep in mind.
First, while subsequent runs are very efficient, the initial run of large analytical queries can be slow and use a lot of resources, because its just a normal SELECT statement. Therefore indexing and query optimisation are still very important.
Second, while both graph relations and record links are supported, the table view update event, only gets triggered based on the table we have in our FROM clause. In our case, just the review table, not the product we are also using in the query. Meaning that if you delete a review the avg_product_review will reflect that in near real-time. However if you delete a product, it will still show up in avg_product_review.
Also note that table views are not triggered when importing data.
Defining permissions
By default, the permissions on a table will be set to NONE unless otherwise specified.
CREATEsome_table; DEFINETABLEsome_other_table;
INFOFORDB;
Response
{ analyzers: {}, functions: {}, models: {}, params: {}, scopes: {}, tables: { some_other_table: 'DEFINE TABLE some_other_table TYPE ANY SCHEMALESS PERMISSIONS NONE', some_table: 'DEFINE TABLE some_table TYPE ANY SCHEMALESS PERMISSIONS NONE' }, tokens: {}, users: {} }
The following shows how to set table level PERMISSIONS using the DEFINE TABLE statement. This allows you to set independent permissions for selecting, creating, updating, and deleting data.
-- Specify access permissions for the 'post' table DEFINETABLEpostSCHEMALESS PERMISSIONS FORselect -- Published posts can be selected WHEREpublished=true -- A user can select all their own posts ORuser=$auth.id FORcreate, update -- A user can create or update their own posts WHEREuser=$auth.id FORdelete -- A user can delete their own posts WHEREuser=$auth.id -- Or an admin can delete any posts OR$auth.admin=true ;
Using IF NOT EXISTS clause
The IF NOT EXISTS clause can be used to define a table only if it does not already exist. You should use the IF NOT EXISTS clause when defining a table in SurrealDB if you want to ensure that the table is only created if it does not already exist. If the table already exists, the DEFINE TABLE statement will return an error.
It's particularly useful when you want to safely attempt to define a table without manually checking its existence first.
On the other hand, you should not use the IF NOT EXISTS clause when you want to ensure that the table definition is updated regardless of whether it already exists. In such cases, you might prefer using the OVERWRITE clause, which allows you to define a table and overwrite an existing one if it already exists, ensuring that the latest version of the table definition is always in use
-- Create a TABLE if it does not already exist DEFINETABLEIFNOTEXISTSreading;
Using OVERWRITE clause
Available since: v2.0.0
The OVERWRITE clause can be used to define a table and overwrite an existing one if it already exists. You should use the OVERWRITE clause when you want to modify an existing table definition. If the table already exists, the DEFINE TABLE statement will overwrite the existing table definition with the new one.
-- Create an TABLE and overwrite if it already exists DEFINETABLEOVERWRITEexample;
Table with specialized TYPE clause
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.
DEFINETABLEpersonTYPEANY; DEFINETABLEperson;
With TYPE NORMAL, you can specify a table to only store "normal" records, and not relations.
-- Since it's default, we can also omit the TYPE clause DEFINETABLEpersonTYPENORMAL;
With TYPE RELATION, you can specify a table to only store relational type content, and restrict what kind of relations can be stored.
-- Just a RELATION table, no constraints on the type of table DEFINETABLElikesTYPERELATION;
-- Define a relation table, and constrain the type of relation which can be stored DEFINETABLElikesTYPERELATIONFROMuserTOpost; -- OR use IN and OUT alternatively to FROM and TO DEFINETABLElikesTYPERELATIONINuserOUTpost; -- To allow a link to one of a possible set of record types, use the | operator DEFINETABLElikesTYPERELATIONFROMuserTOpost|video; DEFINETABLElikesTYPERELATIONINuserOUTpost|video;
-- Define a relation table, and constrain the type of relation which can be stored DEFINETABLEassigned_toSCHEMAFULLTYPERELATIONINtagOUTsticky PERMISSIONS FORcreate, select, update, delete WHEREin.owner==$auth.idANDout.author==$auth.id;
Using ENFORCED to ensure that related records exist
Available since: v2.0.0
As relations are represented by standalone tables, they can be constructed before any linked records exist.
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.
Inserting data from undefined fields on a SCHEMAFULL table
Available since: v3.0.0
Previously, an insert into a SCHEMAFULL table would work even if extra data was present. The query below shows this behaviour, in which the data inside unneeded_data is simply filtered out.
CREATEONLYuserCONTENT{ name: "Billy", user_num: 100, unneeded_data: { some: "other", needless: "data" } }.{ -- Only pass on the name and user_num data name, user_num };