Loading...

SurrealDB online editor

Write, Run & Share SurrealDB queries online using OneCompiler's SurrealDB online editor for free. It's one of the robust, feature-rich online editors for SurrealDB. Getting started with the OneCompiler's SurrealDB editor is really simple and pretty fast. The editor shows sample boilerplate code when you choose language as 'SurrealDB' and start writing queries to learn and test online without worrying about tedious process of installation.

About SurrealDB

SurrealDB is a next-generation, multi-model database that combines the best of document stores, graph databases, and traditional SQL databases. It uses SurrealQL, a powerful query language similar to SQL but with support for nested documents, graph relations, and real-time subscriptions. SurrealDB is designed for modern applications that need flexible data modeling and powerful querying capabilities.

Syntax help

CREATE

Creates new records in a table. Unlike traditional SQL, SurrealDB uses CREATE with SET syntax. You can specify record IDs using table:id format, or let SurrealDB generate unique IDs automatically. Records are schema-flexible by default, allowing different fields for different records in the same table.

-- Create with specific ID
CREATE employee:1 SET name = 'Clark', dept = 'Sales', salary = 50000;
CREATE employee:2 SET name = 'Dave', dept = 'Accounting', salary = 45000;
CREATE employee:3 SET name = 'Ava', dept = 'Sales', salary = 55000;

-- Create with auto-generated ID
CREATE employee SET name = 'Bob', dept = 'Engineering';

-- Create with nested data
CREATE employee:4 SET
  name = 'Eve',
  dept = 'HR',
  contact = {
    email: '[email protected]',
    phone: '555-0100'
  };

SELECT

Retrieves records from tables with powerful filtering and projection capabilities. SurrealDB SELECT works similarly to SQL but supports nested field access and graph traversals. You can select specific fields, filter with WHERE, and navigate relationships in a single query.

-- Select all
SELECT * FROM employee;

-- Select specific fields
SELECT name, dept FROM employee;

-- Select with condition
SELECT * FROM employee WHERE dept = 'Sales';

-- Select with multiple conditions
SELECT * FROM employee WHERE dept = 'Sales' AND salary > 50000;

-- Select nested fields
SELECT name, contact.email FROM employee;

-- Select by ID
SELECT * FROM employee:1;

UPDATE

Modifies existing records. Use UPDATE with SET to change field values, or MERGE to combine new data with existing data. You can update specific records by ID, or update multiple records matching a WHERE condition. SurrealDB also supports CONTENT to replace the entire record.

-- Update by ID
UPDATE employee:1 SET dept = 'Marketing';

-- Update multiple fields
UPDATE employee:1 SET dept = 'Sales', salary = 55000;

-- Update with condition
UPDATE employee SET salary = salary * 1.10 WHERE dept = 'Engineering';

-- Merge (keeps existing fields, adds/updates specified)
UPDATE employee:1 MERGE {
  title: 'Senior Developer',
  skills: ['SQL', 'Python']
};

DELETE

Removes records from a table. You can delete specific records by ID or delete multiple records matching a WHERE condition. DELETE returns the deleted records, which is useful for confirmation or logging. Use with caution as deletions are permanent.

-- Delete by ID
DELETE employee:1;

-- Delete with condition
DELETE employee WHERE dept = 'Sales';

-- Delete all from table
DELETE employee;

-- Delete and return removed records
DELETE employee:2 RETURN BEFORE;

Relations and Graph

SurrealDB excels at modeling relationships between records. Use RELATE to create graph edges between records, then traverse them with -> and <- operators in SELECT queries. This makes complex relationship queries simple and intuitive without traditional JOIN syntax.

-- Create people
CREATE person:john SET name = 'John', age = 30;
CREATE person:jane SET name = 'Jane', age = 28;
CREATE person:bob SET name = 'Bob', age = 25;

-- Create relationships
RELATE person:john -> knows -> person:jane SET since = '2020-01-01';
RELATE person:john -> knows -> person:bob SET since = '2021-06-15';
RELATE person:jane -> knows -> person:bob SET since = '2022-03-10';

-- Query relationships (who does John know?)
SELECT ->knows->person FROM person:john;

-- Reverse query (who knows Jane?)
SELECT <-knows<-person FROM person:jane;

-- Get relationship details
SELECT ->knows FROM person:john;

Aggregations

SurrealDB supports aggregate functions for data analysis. Use count(), math::sum(), math::mean(), math::min(), and math::max() with GROUP BY for grouped statistics. Aggregations work on both flat data and across graph relationships.

-- Count records
SELECT count() FROM employee;

-- Group by with aggregates
SELECT dept, count() as cnt, math::sum(salary) as total_salary
FROM employee
GROUP BY dept;

-- Multiple aggregates
SELECT
  count() as total,
  math::min(salary) as min_sal,
  math::max(salary) as max_sal,
  math::mean(salary) as avg_sal
FROM employee;

Arrays and Objects

SurrealDB natively supports arrays and nested objects as field values. You can query, filter, and manipulate complex data structures directly. This eliminates the need for separate tables in many cases and makes data modeling more natural for modern applications.

-- Create with array
CREATE product:1 SET
  name = 'Laptop',
  tags = ['electronics', 'computer', 'portable'],
  specs = {
    cpu: 'Intel i7',
    ram: '16GB',
    storage: '512GB SSD'
  };

-- Query array contains
SELECT * FROM product WHERE tags CONTAINS 'electronics';

-- Query nested object
SELECT * FROM product WHERE specs.ram = '16GB';

-- Array operations
SELECT name, array::len(tags) as tag_count FROM product;

Functions

SurrealDB provides built-in functions for various operations including string manipulation, math, array operations, and type conversions. Functions are namespaced (string::, math::, array::, type::) for organization. You can also define custom functions for reusable logic.

-- String functions
SELECT
  string::uppercase('hello') as upper,
  string::lowercase('HELLO') as lower,
  string::length('hello') as len,
  string::concat('Hello', ' ', 'World') as combined;

-- Math functions
SELECT
  math::abs(-5) as absolute,
  math::ceil(4.3) as ceiling,
  math::floor(4.7) as floor,
  math::round(4.5) as rounded;

-- Type functions
SELECT
  type::is::string('hello') as is_str,
  type::is::number(42) as is_num;

Time Functions

SurrealDB has built-in support for datetime values and time-based operations. Use time::now() for current time and various extraction functions to work with date components. Time values can be used in comparisons and arithmetic operations.

-- Current time
SELECT time::now() as current_time;

-- Date extraction
SELECT
  time::year(time::now()) as year,
  time::month(time::now()) as month,
  time::day(time::now()) as day,
  time::hour(time::now()) as hour;

-- Create with timestamp
CREATE event:1 SET
  name = 'Meeting',
  scheduled = '2024-01-15T10:00:00Z';

-- Query by time
SELECT * FROM event WHERE scheduled > '2024-01-01';

Subqueries

SurrealDB supports subqueries for complex filtering and data transformation. Subqueries can be used in SELECT fields, WHERE conditions, and as inline tables. This enables powerful compositional queries without multiple round trips to the database.

-- Subquery in WHERE
SELECT * FROM employee
WHERE salary > (SELECT math::mean(salary) FROM employee);

-- Subquery in SELECT
SELECT
  name,
  salary,
  salary - (SELECT math::mean(salary) FROM employee) as diff_from_avg
FROM employee;

DEFINE TABLE

Explicitly defines table schema and configuration. While SurrealDB allows schema-less operation, DEFINE TABLE lets you enforce structure, add indexes, and set permissions. This is useful for production applications where data integrity is important.

-- Define table with schema
DEFINE TABLE employee SCHEMAFULL;

-- Define fields
DEFINE FIELD name ON employee TYPE string;
DEFINE FIELD dept ON employee TYPE string;
DEFINE FIELD salary ON employee TYPE number;

-- Define index
DEFINE INDEX idx_dept ON employee FIELDS dept;

DELETE TABLE

Removes a table and all its data. Use REMOVE TABLE to delete the table definition entirely. For removing just the data while keeping the structure, delete all records instead. Always backup important data before removing tables.

-- Remove table and all data
REMOVE TABLE employee;

-- Delete all data (keeps table)
DELETE employee;