• Start

GraphQL

Sample queries

Compare common GraphQL queries against similar SurrealQL SELECT patterns

SurrealDB’s GraphQL layer turns each table into list fields (for example person) and _get_<table> helpers for a single record by id. Under the hood these map to SurrealQL-style reads (typically SELECT). The SurrealQL here is a rough equivalent for the same or similar data shape.

Before trying the examples, enable GraphQL and define data in the current namespace and database (see GraphQL overview using DEFINE CONFIG GRAPHQL AUTO). The snippets below assume:

  • Namespace main, database main

  • Root authentication root / secret

  • A person table with name and age, and records person:simon and person:marcus as in GraphQL via HTTP

Schema and sample data

DEFINE TABLE person SCHEMAFULL;
DEFINE FIELD name ON TABLE person TYPE string;
DEFINE FIELD age ON TABLE person TYPE number;
CREATE person:simon SET name = "Simon", age = 23;
CREATE person:marcus SET name = "Marcus", age = 28;
DEFINE CONFIG GRAPHQL AUTO;

GraphQL here returns a list of objects, similar to SELECT without ONLY.

Query

query {
person {
name
age
}
}

Output

{
"data": {
"person": [
{
"age": 28,
"name": "Marcus"
},
{
"age": 23,
"name": "Simon"
}
]
}
}

Use _get_<table> with the record key (simon, not person:simon in the argument). The GraphQL id field on the result is the full record id.

Query

query {
_get_person(id: "simon") {
id
name
age
}
}

Output

{
"data": {
"_get_person": {
"id": "person:simon",
"name": "Simon",
"age": 23
}
}
}

GraphQL uses limit (and optional start for offset). SurrealQL uses LIMIT / START and ONLY to return a single record as opposed to an array containing a single record.

Query

query {
person(limit: 1) {
name
age
}
}

Output

{
"data": {
"person": [
{
"age": 28,
"name": "Marcus"
}
]
}
}

GraphQL accepts filter or where with the generated input type for the table (for example _filter_person). For a scalar field, use comparison keys such as eq, ne, gt, and lt where the schema allows them.

Query

query {
person(where: { age: { eq: 23 } }) {
name
}
}

Output

{
"data": {
"person": [
{
"name": "Simon"
}
]
}
}

Use an order argument with asc or desc and a field name.

Query

query {
person(order: { asc: age }) {
name
age
}
}

Output

{
"data": {
"person": [
{
"age": 23,
"name": "Simon"
},
{
"age": 28,
"name": "Marcus"
}
]
}
}

For the full configuration surface (tables, functions, limits), see DEFINE CONFIG GRAPHQL.

Was this page helpful?