Many fields in these schemas use COMPUTED fields, available as of SurrealDB version 3.0.0-beta. For versions before this, a data type called a future was used. To use such fields in a version before 3.0.0-beta, replace COMPUTED with VALUE <future> and enter an expression to be calculated inside {} braces.
This page contains a number of sample schemas, each about 50 lines in length, that can be used to get started on a schema of your own for your own industry.
Adding to this page
Have a sample schema of your own that you'd like to add? If it's about 50 lines in length then feel free to make a PR and we'll credit the addition with a link to your profile on a code hosting platform (e.g. GitHub, GitLab, Codeberg).
You can also get in touch with us if you'd like a sample schema that isn't in this page that fits the industry in which you work.
Energy and manufacturing
Project planning
A comprehensive project management schema that demonstrates activity scheduling, milestone tracking, and dependency management using graph relationships. This schema shows how to model complex project workflows with interdependent tasks and progress tracking using futures for calculated fields.
-- Activities in a project schedule DEFINETABLEactivitySCHEMAFULL; DEFINEFIELDnameONactivityTYPEstring; DEFINEFIELDdescriptionONactivityTYPEoption<string>; DEFINEFIELDstartONactivityTYPEdatetime; DEFINEFIELDendONactivityTYPEdatetime; DEFINEFIELDdurationONactivityCOMPUTEDend-start; DEFINEFIELDprogressONactivityTYPEfloatASSERT$valueIN0.0..=1.0; DEFINEFIELDassigned_toONactivityTYPEoption<record<employee>>; DEFINEFIELDfollowed_byONactivityCOMPUTED<-depends_on<-activity;
-- See all graph connections between activity and project records SELECT *, ->?, <-? FROMactivity, project;
-- View the current milestones SELECT * FROMmilestone;
SCADA (Oil and Gas)
Industrial monitoring and control system schema for oil and gas operations. Demonstrates real-time sensor data collection, automated alert generation using events, and time-series data management with composite keys. Shows how to handle flexible external data integration and live query monitoring.
-- Create a sensor CREATEsensor:oneSETtype=["temperature", "pressure"], location= (50.0, 50.0); -- And a reading for the sensor CREATEreading:[sensor:one, time::now()]SET pressure=600, -- JSON object sourced from somewhere else, `weather` field is a schemaless object so can be any object format weather={"temperature": 17.4, "humidity": 52.0, "wind_speed": 12.8};
-- Set up event to generate alerts DEFINEEVENTalert_from_createONreadingWHEN$event="CREATE"THEN{ LET$source = $after.id[0]; LET$time = $after.id[1]; -- Select everything over the past 15 minutes up to but not including the present reading LET$recents_average = math::mean(SELECTVALUEpressureFROMreading:[$source, $time-15m]..[$source, $time]); LET$drop = $recents_average-$after.pressure; IF$drop>15{ CREATEalertSET equipment=$source, severity="high", message="Pressure drop over 15 PSI: drop of "+<string>$drop, triggered_at=time::now(); }; };
-- Some readings with good values FOR$_IN0..10{ -- Sleep to keep timestamp in IDs unique, consider a ULID instead if timestamps may not be unique sleep(10ns); CREATEreading:[sensor:one, time::now()]SETpressure=600; }; -- Pressure has suddenly dropped CREATEreading:[sensor:one, time::now()]SETpressure=500;
-- See the alert SELECT * FROMalert; -- Or use a LIVE SELECT for alerts: https://surrealdb.com/docs/surrealql/statements/live LIVESELECT * FROMalert;
Risk management
Project risk assessment and mitigation tracking schema. Features temporal risk modeling with active/inactive periods, probability-impact calculations, and automated risk scoring using futures. Demonstrates unique constraints and complex mathematical aggregations across related records.
DEFINETABLEriskSCHEMAFULL; DEFINEFIELDprojectONriskTYPErecord<project>REFERENCE; DEFINEFIELDdescriptionONriskTYPEstring; DEFINEFIELDcategoryONriskTYPEstring; -- e.g. "technical", "commercial", "regulatory" DEFINEFIELDlikelihoodONriskTYPEfloatASSERT$valueIN0.0..=1.0; DEFINEFIELDmaximum_impactONriskTYPEint; -- in dollars, etc. DEFINEFIELDstartONriskTYPEdatetime; DEFINEFIELDendONriskTYPEdatetime; -- Use a computed field to calculate value on each SELECT DEFINEFIELDactiveONriskCOMPUTEDtime::now() INstart..=end; -- Ensure no duplicate `risk` records exist for each project DEFINEINDEXrisk_nameONriskFIELDSproject, descriptionUNIQUE;
-- See all total_impact DEFINEFIELDtotal_risk_impactONprojectCOMPUTED math::sum(<~risk.map(|$risk|$risk.maximum_impact*$risk.likelihood));
-- See risks at the current date DEFINEFIELDcurrent_risk_impactONprojectCOMPUTED math::sum(<~risk.filter(|$r|$r.active).map(|$risk|$risk.maximum_impact*$risk.likelihood));
Vendor relationship and contract lifecycle management schema. Covers contract value tracking with change orders, deliverable management, and automated total commitment calculations using futures. Demonstrates complex financial calculations and status tracking across multiple related entities.
-- Vendors who supply goods or services DEFINETABLEvendorSCHEMAFULL; DEFINEFIELDnameONvendorTYPEstring;
-- Contracts awarded under a project DEFINETABLEcontractSCHEMAFULL; DEFINEFIELDprojectONcontractTYPErecord<project>; DEFINEFIELDvendorONcontractTYPErecord<vendor>; DEFINEFIELDtitleONcontractTYPEstring; DEFINEFIELDoriginal_valueONcontractTYPEint; DEFINEFIELDtotal_valueONcontractCOMPUTED original_value+math::sum(SELECTVALUEamountFROMchange_orderWHEREcontract=$parent.id); DEFINEFIELDcurrencyONcontractTYPE"dollars" | "euro"; DEFINEFIELDstartONcontractTYPEdatetime; DEFINEFIELDendONcontractTYPEdatetime;
-- Deliverables expected under a contract DEFINETABLEdeliverableSCHEMAFULL; DEFINEFIELDcontractONdeliverableTYPErecord<contract>; DEFINEFIELDdescriptionONdeliverableTYPEstring; DEFINEFIELDdue_dateONdeliverableTYPEdatetime; DEFINEFIELDreceivedONdeliverableTYPEoption<datetime>; DEFINEFIELDstatusONdeliverableCOMPUTEDIF $parent.received{"complete"}ELSE{"pending"};
-- Change orders during a project DEFINETABLEchange_orderSCHEMAFULL; DEFINEFIELDcontractONchange_orderTYPErecord<contract>; DEFINEFIELDamountONchange_orderTYPEint; DEFINEFIELDdescriptionONchange_orderTYPEstring; DEFINEFIELDsigned_onONchange_orderTYPEoption<datetime>;
-- Total committed value of a project (sum of all contract values) DEFINEFIELDtotal_commitmentONprojectCOMPUTED math::sum((SELECTVALUEvalueFROMcontractWHEREproject=$parent.id));
CREATEproject:one; CREATEvendor:oneSETname="Good vendor"; CREATEcontract:oneSETproject=project:one, currency="euro", start=d'2025-12-01', end=d'2026-01-01', original_value=1000, title="Services for so-and-so project", vendor=vendor:one; CREATEchange_orderSETcontract=contract:one, amount=500, description="Highway wasn't set up yet"; SELECT * FROMcontract;
Incident reporting and investigation schema using graph relationships. Models safety events as edges between employees and projects with severity classification and role identification. Demonstrates graph-style data modeling for complex incident tracking and analysis.
-- Projects and employees (nodes) DEFINETABLEprojectSCHEMAFULL; DEFINETABLEemployeeSCHEMAFULL;
-- Create incidents as edges with properties RELATEemployee:one->incident->project:oneSET severity="moderate", type="safety", description="Pinched hand during pipe fitting", occurred_at=time::now() -5d, role="injured";
RELATEemployee:two->incident->project:oneSET severity="moderate", type="safety", description="Pinched hand during pipe fitting", occurred_at=time::now() -5d, role="witness";
Multi-currency banking system using graph relationships. Demonstrates polymorphic account types (JPY, EUR, CAD, USD) with different field structures, customer-bank relationships, and unique constraint enforcement. Shows how to model complex financial relationships with type-specific behaviors.
Traditional bank-customer schema with advanced features including record references, automated cent handling through events, and historical interest rate tracking. Demonstrates event-driven data validation, parameter usage, and complex relationship management with reference fields.
DEFINETABLEbankSCHEMAFULL; DEFINEFIELDnameONbankTYPEstring; DEFINEFIELDcodeONbankTYPEstring; -- e.g., BIC or internal short code DEFINEFIELDswiftONbankTYPEoption<string>; DEFINEFIELDsupported_currenciesONbankTYPEset<string>ASSERT$valueALLINSIDE$CURRENCIES; DEFINEFIELDinterest_rateONbankTYPEfloatDEFAULT0.0; DEFINEFIELDhistorical_interest_ratesONbankTYPEarray<{rate: float, set_at: datetime}>DEFAULT[]; DEFINEFIELDcustomersONbankCOMPUTED<~customer;
-- No assert for cent field, but event to update when > 100 or < 0 DEFINEEVENTupdate_centsONaccountWHEN$event="UPDATE"THEN{ IFcent>99{ UPDATE$afterSETcent-=100, amount+=1; }ELSEIFcent<0{ UPDATE$afterSETcent+=100, amount-=1; } };
-- No assert for cent field, but event to update when > 100 or < 0 DEFINEEVENTupdate_interest_rateONbankWHEN$event="UPDATE"THEN{ IF$before.interest_rate!=$after.interest_rate{ UPDATE$thisSEThistorical_interest_rates+={rate: $after.interest_rate, set_at: time::now() }; } };
Secure money transfer system with credit-based limits and transaction logging. Features custom functions for atomic transfers, credit level enforcement, and comprehensive audit trails. Demonstrates transaction safety, business rule enforcement, and financial data integrity.
DEFINETABLEcustomerSCHEMAFULL; -- trusted customers can have greater negative amounts DEFINEFIELDamountONcustomerASSERT$value>= -1000*credit_level; DEFINEFIELDcredit_levelONcustomerTYPEintASSERT$valueIN0..=5;
-- Logs for money transfers DEFINETABLEtransferSCHEMAFULL; DEFINEFIELDfromONtransferTYPErecord<customer>; DEFINEFIELDtoONtransferTYPErecord<customer>; DEFINEFIELDamountONtransferTYPEint; DEFINEFIELDtsONtransferTYPEdatetimeDEFAULTtime::now();
DEFINEFUNCTIONfn::send_money($from: record<customer>, $to: record<customer>, $amount: int) { -- Use manual transaction for all statements so all changes are rolled back -- if something is wrong BEGIN; If$amount<1{ THROW"Can't send less than 1 "; }; UPDATE$fromSETamount-=$amount; UPDATE$toSETamount+=$amount; CREATEtransferSETfrom=$from, to=$to, amount=$amount; COMMIT; };
-- customer:one has bad credit, can't be negative fn::send_money(customer:one, customer:two, 500); -- but customer:two can fn::send_money(customer:two, customer:one, 1000);
SELECT * FROMcustomer; SELECT * FROMtransfer;
Loans and repayments
Loan management system with automated interest calculations and repayment scheduling. Features parameterized loan terms, mathematical payment calculations using custom functions, and status tracking. Demonstrates complex financial formulas, temporal data management, and regulatory compliance constraints.
-- Some government-set maximum term for loans DEFINEPARAM$MAX_TERMVALUE84;
DEFINETABLEloanSCHEMAFULL; DEFINEFIELDcustomerONloanTYPErecord<customer>; DEFINEFIELDprincipalONloanTYPEint; -- Total borrowed, in cents DEFINEFIELDinterest_rateONloanTYPEfloat; -- e.g., 5.5 for 5.5% DEFINEFIELDissued_atONloanTYPEdatetime; -- loans issuable at units of 6 months each DEFINEFIELDterm_monthsONloanTYPEintASSERT$value % 6 =0AND$value<=$MAX_TERM; DEFINEFIELDbalanceONloanTYPEint; -- Remaining amount to repay DEFINEFIELDstatusONloanTYPEstringASSERT$valueIN["active", "paid", "defaulted"];
Anti-fraud detection system using events and temporal analysis. Implements velocity checks, new account restrictions, and suspicious transaction pattern detection. Demonstrates real-time fraud prevention, temporal constraints, and complex business rule enforcement through database events.
DEFINEFIELDcreated_atONaccountVALUEtime::now() READONLY; DEFINEEVENTcancel_high_volumeONTABLEsendsWHEN$event="CREATE"THEN{ IF$after.amount>1000ANDtime::now() -$after.in.created_at<1d{ THROW"New accounts can only send up to $1000 per transaction"; } };
DEFINEEVENTcancel_high_volumeONTABLEsendsWHEN$event="CREATE"THEN{ LET$sender = $after.in; LET$receiver = $after.out; -- Disallow more than two transactions within a 5 minute period LET$recents = $sender->sends[WHEREout=$receiver] .filter(|$tx|time::now() -$tx.sent_at<5m); IF$recents.len() >2{ THROW"Can't send that many times within a short period of time"; }; };
Using Surrealist's graph visualization to see fraudulent activities
Tight communities that interact mostly among themselves:
-- Regular community of 200 CREATE |account:200|; -- Smaller community that interacts among itself CREATE |account:5| SETis_sketchy=true;
-- The sketchy community interacts only between itself -- the regular community has more general interactions -- and sometimes sends money to the sketchy accounts FOR$accountINSELECT * FROMaccount{ FOR$_IN0..10{ LET$counterpart = IF$account.is_sketchy{ rand::enum(SELECT * FROMaccountWHEREis_sketchy) }ELSE{ rand::enum(SELECT * FROMaccount) }; RELATE$account->sends_to->$counterpartSETamount=rand::int(100, 1000); } };
SELECTid, ->sends_to->accountFROMaccount;
Circles showing loops of money returning to its origin:
RPG game system with character progression, inventory management, and quest tracking. Features polymorphic item effects, character statistics, and complex game state management. Demonstrates flexible data modeling for gaming applications with rich object structures and relationship tracking.
-- Items in the game world DEFINETABLEitemSCHEMAFULL; DEFINEFIELDnameONitemTYPEstring; DEFINEFIELDtypeONitemTYPEstringASSERT$valueIN["weapon", "armor", "potion"]; DEFINEFIELDrarityONitemTYPEstringASSERT$valueIN["common", "rare", "epic", "legendary"]; DEFINEFIELDeffectsONitemTYPEarray<{str: int} | {heal: int}>; // etc.
-- Items possessed by characters DEFINETABLEownsTYPERELATIONINcharacterOUTitem; DEFINEFIELDequippedONownsTYPEboolDEFAULTfalse;
-- Quests available in the world DEFINETABLEquestSCHEMAFULL; DEFINEFIELDnameONquestTYPEstring; DEFINEFIELDrequired_levelONquestTYPEintDEFAULT1; DEFINEFIELDrewardsONquestTYPE{exp: int, items: array<record<item>>};
-- Character quest progress DEFINETABLEquest_logTYPERELATIONINcharacterOUTquest; DEFINEFIELDstatusONquest_logTYPEstringASSERT$valueIN["active", "completed"]; DEFINEFIELDstarted_atONquest_logTYPEdatetimeDEFAULTtime::now(); DEFINEFIELDcompleted_atONquest_logTYPEoption<datetime>;
-- Create a new character CREATEcharacter:ariaSETname="Aria", class="mage", stats={str: 4, dex: 6, int: 12};
-- Give Aria an item RELATEcharacter:aria->owns->(CREATEONLYitemSETname="Wand of Sparks", type="weapon", rarity="rare", effects={int: 2});
-- Start a quest RELATEcharacter:aria->quest_log->quest:slime_huntSETstatus="active";
Aerospace and astronomy
Telescopes and observations
Astronomical observation tracking system with instrument management and data collection. Features geospatial telescope locations, flexible observation metadata, and scientific data URL management. Demonstrates point data types, complex temporal relationships, and scientific data organization patterns.
-- Telescopes (instruments) DEFINETABLEtelescopeSCHEMAFULL; DEFINEFIELDnameONtelescopeTYPEstring; DEFINEFIELDlocationONtelescopeTYPEpoint; DEFINEFIELDaperture_mmONtelescopeTYPEint; -- e.g. 200 for 8" scope
Space launch monitoring system with real-time telemetry data collection. Features component-level tracking, time-series data management with composite keys, and launch lifecycle status tracking. Demonstrates high-frequency data ingestion, temporal range queries, and live data streaming.
-- A specific launch instance (e.g., Falcon 9 Flight 100) DEFINETABLElaunchSCHEMAFULL; DEFINEFIELDnameONlaunchTYPEstring; DEFINEFIELDvehicle_nameONlaunchTYPEoption<string>; DEFINEFIELDscheduled_atONlaunchTYPEdatetime; DEFINEFIELDliftoff_atONlaunchTYPEoption<datetime>; DEFINEFIELDstatusONlaunchTYPEstringASSERT$valueIN["scheduled", "launched", "scrubbed", "failed", "success"]DEFAULT"scheduled"; DEFINEFIELDcompletedONlaunchTYPEoption<datetime>; -- Components involved in the launch DEFINETABLEcomponentSCHEMAFULL; DEFINEFIELDlaunchONcomponentTYPErecord<launch>; DEFINEFIELDnameONcomponentTYPEstring; -- e.g., "first_stage", "engine_1" DEFINEFIELDtypeONcomponentTYPEstringASSERT$valueIN["stage", "engine", "payload", "fairing"];
-- Time-series telemetry linked to a component DEFINETABLEtelemetrySCHEMAFULL; DEFINEFIELDidONtelemetryTYPE[record<component>, datetime]; -- [component, ulid] DEFINEFIELDaltitude_mONtelemetryTYPEoption<float>; DEFINEFIELDvelocity_mpsONtelemetryTYPEoption<float>; DEFINEFIELDthrust_kNONtelemetryTYPEoption<float>; DEFINEFIELDpressure_kPaONtelemetryTYPEoption<float>; DEFINEFIELDtemperature_CONtelemetryTYPEoption<float>; DEFINEFIELDstatusONtelemetryTYPEoption<string>;
-- Add durations to all datetimes below to simulate passage of time CREATEtelemetry:[component:one, time::now()]SETtemperature_c=30.5, status="good"; CREATEtelemetry:[component:one, time::now() +1s]SETtemperature_c=30.7, status="good"; CREATEtelemetry:[component:one, time::now() +2s]SETtemperature_c=30.9, status="good"; CREATEtelemetry:[component:one, time::now() +3s]SETtemperature_c=35.0, status="good"; CREATEtelemetry:[component:two, time::now()]SETtemperature_c=30.5, status="good"; CREATEtelemetry:[component:two, time::now() +1s]SETtemperature_c=30.7, status="good"; CREATEtelemetry:[component:two, time::now() +2s]SETtemperature_c=30.9, status="good"; CREATEtelemetry:[component:two, time::now() +3s]SETtemperature_c=35.0, status="good";
UPDATElaunch:oneSETcompleted=time::now() +5s;
-- Get all telemetry for component:two during launch:one SELECT * FROMtelemetry:[component:two, launch:one.liftoff_at]..=[component:two, launch:one.completed];
-- Or LIVE SELECT during the flight LIVESELECT * FROMtelemetryWHEREid[0]=component:two;
Defense / mission operations
Missions and tasks
Military mission management system with unit tracking and operational logging. Features hierarchical command structure, real-time status updates, and comprehensive audit trails. Demonstrates complex organizational modeling, geospatial tracking, and mission-critical data management patterns.
E-commerce platform schema with customer profiles, product catalog, and shopping cart management. Features flexible address storage, multi-currency support, and comprehensive timestamp tracking. Demonstrates modern e-commerce data modeling with flexible objects and relationship management.
Order processing and analytics system with review management and business intelligence. Features order lifecycle tracking, automated analytics tables, and full-text search capabilities. Demonstrates complex aggregations, materialized views, and search optimization for e-commerce applications.
Healthcare management system with patient records, encounter tracking, and clinical data management. Features vital signs time-series data, medication tracking, and automated encounter lifecycle management using events. Demonstrates healthcare data modeling with temporal data, clinical workflows, and medical record compliance patterns.