SurrealQL reads like SQL. SELECT, WHERE, GROUP BY, ORDER BY and LIMIT do what a SQL reader expects, and statements end with a semicolon. The differences come from how SurrealDB stores data: a table holds records, and a record holds fields of any type, including arrays, objects and links to other records. This page maps familiar SQL to SurrealQL, then takes each difference in turn with an example that runs as written.
Each example has a SurrealQL tab and a PostgreSQL tab with the SQL that does the same job, and the tab that is chosen stays chosen down the page. To move an existing database, see the guides for PostgreSQL and MySQL. To send SQL itself to SurrealDB, the compatibility matrix lists what the PostgreSQL and MySQL dialects run.
SQL and SurrealQL side by side
| SQL | SurrealQL | Difference |
|---|---|---|
SELECT * FROM person WHERE age > 30 | SELECT * FROM person WHERE age > 30 | Identical. |
LIMIT 10 OFFSET 20 | LIMIT 10 START 20 | START takes the place of OFFSET. |
INSERT INTO person (name) VALUES ('Ada') | CREATE person SET name = 'Ada' or INSERT INTO person { name: 'Ada' } | A record gets a generated ID unless the statement gives one. |
INSERT ... ON CONFLICT DO UPDATE | UPSERT person:ada SET ... or INSERT ... ON DUPLICATE KEY UPDATE | See Writing data. |
JOIN | author.name through a record link, or -> through a graph edge | See Links and references instead of joins. |
WHERE post.author_id = 1 to find the posts of an author | author:ada<~post | The field needs REFERENCE. |
COUNT(*) | count() with GROUP ALL | COUNT(*) does not parse. |
AVG(x), SUM(x), MIN(x), MAX(x) | math::mean(x), math::sum(x), math::min(x), math::max(x) | Used with GROUP BY or GROUP ALL. |
COALESCE(a, b) | a ?? b | |
CAST(x AS int) | <int> x | |
WITH name AS (...) | LET $name = ...; | See Subqueries. |
x IS NULL for a missing value | x IS NONE | See NONE and NULL. |
BEGIN; ... COMMIT; | BEGIN; ... COMMIT; | Identical. |
Tables and schemas
In SQL a table is created with its columns before it takes data. In SurrealQL a table is created with DEFINE TABLE, or by the first record written to it, in which case SurrealDB runs the definition itself: INFO FOR DB then shows DEFINE TABLE person TYPE ANY SCHEMALESS PERMISSIONS NONE. A schemaless table takes any fields, including nested arrays and objects. A database defined with STRICT refuses to create tables this way, and every table has to be defined first.
A table that should behave like a SQL table is declared SCHEMAFULL with one field for each column. A field has a type, ASSERT takes the place of CHECK, and a field that is not defined is refused.
DEFINE TABLE person SCHEMAFULL;
DEFINE FIELD name ON person TYPE string;
DEFINE FIELD age ON person TYPE int ASSERT $value >= 0;
CREATE person:ada SET name = 'Ada', age = 36;
//- [{ age: 36, id: person:ada, name: 'Ada' }]
CREATE person:bob SET name = 'Bob', age = '41';
//- "Couldn't coerce value for field `age` of `person:bob`: Expected `int` but found `'41'`"
CREATE person:eve SET name = 'Eve', age = -1;
//- 'Found -1 for field `age`, with record `person:eve`, but field must conform to: $value >= 0'
CREATE person:zed SET name = 'Zed', age = 29, nickname = 'z';
//- "Found field 'nickname', but no such field exists for table 'person'"A record ID has the form table:key, such as person:ada. A statement that names no key, as in CREATE person SET name = 'Ada', gets a random one, so there is no auto-incrementing column. The record IDs page covers the other key types.
A field's type also converts a value into it where no data is lost. A float field takes 1 and stores 1f, and an int field takes 2.0 and stores 2, but it refuses 2.5 rather than round it.
DEFINE TABLE reading SCHEMAFULL;
DEFINE FIELD value ON reading TYPE float;
DEFINE FIELD count ON reading TYPE int;
CREATE reading:1 SET value = 1, count = 2.0;
//- [{ count: 2, id: reading:1, value: 1f }]
CREATE reading:2 SET value = 1, count = 2.5;
//- "Couldn't coerce value for field `count` of `reading:2`: Expected `int` but found `2.5f`"NONE and NULL
A field that a record does not have is NONE, which is a different value from NULL, a stored empty value. A SQL query that tests a missing value with IS NULL therefore needs IS NONE in SurrealQL, and = NULL matches nothing here. None and null describes both values, and ?? supplies a default for a missing field.
-- Setup
CREATE person:ada SET name = 'Ada', age = 36;
CREATE person:bob SET name = 'Bob';
SELECT name FROM person WHERE age IS NONE;
//- [{ name: 'Bob' }]
SELECT name FROM person WHERE age = NULL;
//- []
SELECT name, age ?? 0 AS age FROM person ORDER BY name;
//- [{ age: 36, name: 'Ada' }, { age: 0, name: 'Bob' }]A comparison between different types does not convert one to the other, so 1 = '1' is false, and a value must be cast first. Numbers are the exception, because they compare by value whatever their type: 1 = 1.0 is true.
RETURN 1 = '1';
//- false
RETURN <int> '1' = 1;
//- true
RETURN 1 = 1.0;
//- trueLinks and references instead of joins
A field can hold the ID of another record, which is called a record link. A path through the field reads the linked record, so a query that would need a JOIN in SQL names the field instead. The path author.name reads one field of the author, and author.* reads the whole record.
-- Setup
CREATE author:ada SET name = 'Ada';
CREATE post:1 SET title = 'Engines', author = author:ada;
SELECT title, author.name AS author FROM post;
//- [{ author: 'Ada', title: 'Engines' }]
SELECT title, author.* AS author FROM post;
//- [{ author: { id: author:ada, name: 'Ada' }, title: 'Engines' }]A link points one way. To read it from the other side, a field defined with REFERENCE also records the link on the record it points at, and <~ follows it back. In SQL the same lookup is a WHERE on the foreign key of the other table. The field has to be defined before the records are written, because the references are recorded as the records are written.
DEFINE FIELD author ON post TYPE record<author> REFERENCE;
CREATE author:ada SET name = 'Ada';
CREATE post:1 SET title = 'Engines', author = author:ada;
CREATE post:2 SET title = 'Notes', author = author:ada;
SELECT name, <~post.title AS titles FROM author:ada;
//- [{ name: 'Ada', titles: ['Engines', 'Notes'] }]Many-to-many relationships use graph edges, which RELATE creates and -> follows. The PostgreSQL migration guide shows a four-table JOIN rewritten as one traversal.
Nested values
A field can hold an array or an object, and a query reads inside it in place. The result keeps the nesting, so address.city comes back as an address object that holds city, not as a flat column. Idioms lists the other path forms.
-- Setup
CREATE person:ada SET name = 'Ada', tags = ['maths', 'engines'], address = { city: 'London' };
CREATE person:bob SET name = 'Bob', tags = ['rust'], address = { city: 'Paris' };
SELECT name FROM person WHERE 'rust' IN tags;
//- [{ name: 'Bob' }]
SELECT name, address.city FROM person ORDER BY name;
//- [{ address: { city: 'London' }, name: 'Ada' }, { address: { city: 'Paris' }, name: 'Bob' }]Aggregates
An aggregate function needs a GROUP clause, which is GROUP BY for one result per group and GROUP ALL for one result in total. count() takes the place of COUNT(*), and the other aggregates are in the math functions.
-- Setup
CREATE product:a SET name = 'Shirt', category = 'clothing', price = 6;
CREATE product:b SET name = 'Hat', category = 'clothing', price = 10;
CREATE product:c SET name = 'Mug', category = 'kitchen', price = 4;
SELECT count() AS products, math::max(price) AS highest FROM product GROUP ALL;
//- [{ highest: 10, products: 3 }]
SELECT category, count() AS products, math::mean(price) AS average FROM product GROUP BY category ORDER BY category;
//- [{ average: 8f, category: 'clothing', products: 2 }, { average: 4f, category: 'kitchen', products: 1 }]Writing data
The write statements differ from SQL in what they do when the record exists or does not. CREATE fails if the record is already there. UPDATE changes records that exist and returns nothing for an ID that does not, and an UPDATE with no WHERE clause changes every record in the table. UPSERT creates the record or updates it, which is the closest match to INSERT ... ON CONFLICT. INSERT also takes ON DUPLICATE KEY UPDATE, with the submitted values in $input.
-- Setup
CREATE person:ada SET name = 'Ada', visits = 1;
UPDATE person:nobody SET name = 'Nobody';
//- []
UPSERT person:grace SET name = 'Grace', visits = 1;
//- [{ id: person:grace, name: 'Grace', visits: 1 }]
UPSERT person:grace SET visits += 1;
//- [{ id: person:grace, name: 'Grace', visits: 2 }]
INSERT INTO person { id: 'ada', name: 'Ada Lovelace' } ON DUPLICATE KEY UPDATE name = $input.name, visits += 1;
//- [{ id: person:ada, name: 'Ada Lovelace', visits: 2 }]Subqueries and stored results
A subquery goes in parentheses as in SQL. A WITH name AS (...) expression does not exist in SurrealQL, because the WITH clause chooses indexes. A result that a later statement reuses is stored in a parameter with LET.
-- Setup
CREATE person:ada SET name = 'Ada', age = 36;
CREATE person:bob SET name = 'Bob', age = 41;
LET $adults = SELECT name, age FROM person WHERE age > 40;
SELECT * FROM $adults;
//- [{ age: 41, name: 'Bob' }]See also
Learn: Querying is the guided introduction to SurrealQL.
SELECTlists every clause of the query statement.Record IDs, record links and record references cover the ideas that replace keys and joins.
Migrating from PostgreSQL and from MySQL cover moving the data.