Skip to the page

Learn · Data & files

Queries & mutations

Fetch nested object graphs or run multi-step writes in one EdgeQL statement compiled to a single SQL query.

In the schema
—

Nested shapes#

A selection shape declares the exact fields you want at every level of your object graph. Walk forward links, reverse backlinks and inline computed fields as deeply as your UI needs, and the compiler lowers the entire shape and all touched access policies into one SQL query with zero client-side joins or N+1 round trips.

Saved query files

Query files compile with access policies into HTTP, SDK and MCP endpoints.

Single-snapshot reads

PostgreSQL evaluates parent rows and nested child arrays against one snapshot.

Backlinks and aggregates

Reverse link walks and counts run live in SQL without denormalized counters.

Every example on this page builds on the Schema page. Here both note_count and latest evaluate inline from the notes backlink in one PostgreSQL snapshot.

query.edgeql
select Person {  name,  note_count,  latest := (    select .notes { title, created }    order by .created desc    limit 3  ),}filter .identity = global caller
result.json
[  {    "name": "Maya",    "note_count": 12,    "latest": [      { "title": "Launch checklist",        "created": "2026-10-16T18:04:11.501Z" },      { "title": "Hiring plan",        "created": "2026-10-15T09:30:02.118Z" },      { "title": "Pricing notes",        "created": "2026-10-12T14:12:40.874Z" }    ]  }]

Filtering, ordering and pagination#

Attach filter, order by, offset and limit either at the top level of a query or inside any nested link shape. Checking membership on a multi field uses standard in syntax (such as 'launch' in .tags).

filter.edgeql
select Note { title, tags }filter .visibility = Visibility.Public  and 'launch' in .tagsorder by .created desclimit 10

Keyset pagination on compound sort keys#

Large lists should paginate with keyset cursors instead of offset. An offset 10000 scan still checks access policies on 10,000 skipped rows and sorts the whole prefix before returning the page. Comparing a compound tuple (.created, .id) seeks straight to the next page on a composite B-tree index (index on ((.created, .id))) and never skips or duplicates rows that share the same timestamp.

Keyset cursor pagination

Compound tuple cursors jump straight to the next page on a B-tree index.

Pass the last row’s timestamp and UUID back as optional cursor parameters on the next request.

dbschema/queries/listNotesPage.edgeql
with  after_created := <optional datetime>$after_created,  after_id := <optional uuid>$after_id,select Note {  id,  title,  created,}filter (  not exists after_created  or (.created, .id) < (after_created, after_id ?? <uuid>'ffffffff-ffff-ffff-ffff-ffffffffffff'))order by .created desc then .id desclimit 25

Typed parameters#

Declare runtime inputs with an explicit type cast on $name, such as <uuid>$id or <optional datetime>$before. Query strings never interpolate raw user input, so statements stay immune to injection.

page.edgeql
select Note { title, created }filter .created < (<optional datetime>$before ?? datetime_of_statement())order by .created desclimit 20

Send matching parameter values in the request’s variables JSON object.

variables.json
{ "before": "2026-10-12T00:00:00Z" }

Prefix optional parameters with optional and provide defaults with the coalescing operator ??. Calls that omit a required parameter fail validation before execution.

Mutations#

Data modifications use the same shape, filter and policy primitives as select and always execute as a single atomic SQL statement.

Atomic single-statement writes

Inserts, updates, upserts and batch loops commit or roll back together.

Insert#

Note.author defaults to the Person matching global caller, so omitting author sets the authenticated user automatically while the allow insert policy prevents spoofing another author.

insert.edgeql
insert Note {  title := <str>$title,  tags := {'plans', 'launch'},}

Wrap any mutation in an outer select (insert Note { … }) { id, created } shape to read back computed or server-generated fields in the same round trip.

Update and delete#

update filters target rows through update read policies and verifies the modified row against update write before committing.

update.edgeql
update Notefilter .id = <uuid>$idset {  title := <str>$title,  tags += 'shipped',}

delete removes only rows permitted by the caller’s delete policies.

delete.edgeql
delete Note filter .id = <uuid>$id

Upsert (insert … unless conflict)#

Attach unless conflict on an exclusive property to insert a missing row or update the existing row atomically.

upsert.edgeql
insert Person {  identity := global caller,  name := <str>$name,}unless conflict on .identityelse (  update Person set { name := <str>$name })

Batch writes with for#

A for statement iterates over an unpacked array parameter and runs the loop body for every item inside one atomic SQL query, so either the entire batch commits or nothing is written.

many.edgeql
for title in array_unpack(<array<str>>$titles)union (  insert Note { title := title })

Subqueries#

Bind intermediate expressions in a with block to keep complex queries readable without splitting work across multiple network round trips.

summary.edgeql
with  mine := (select Note filter .author.identity = global caller),  shared := (select mine filter .visibility != Visibility.Private),select {  total := count(mine),  shared := count(shared),  tags := array_agg(distinct mine.tags),}

Grouping and aggregations#

group partitions objects by one or more keys and returns each key alongside its matching elements in a typed nested shape.

group.edgeql
group Note { title }by .visibility

Polymorphic types and unions#

Object types can inherit shared properties, links and access policies from an abstract type. A single query over the base type (or over a union such as ArticlePost | VideoPost) reads common fields alongside subtype-specific fields with [is Subtype] intersections and discriminates each returned row through .__type__.name.

Polymorphic type unions

One query reads shared base fields alongside subtype-specific fields together.

Here ArticlePost and VideoPost inherit shared properties and access policies from Post.

dbschema/default.gel
abstract type FeedItem {  required author: Person;  required created: datetime {    default := datetime_of_statement();  };   access policy signed_in_can_read    allow select    using (exists global caller);} type ArticlePost extending FeedItem {  required headline: str;  required word_count: int32;} type VideoPost extending FeedItem {  required caption: str;  required duration_seconds: int32;}

feed.edgeql selects common Post fields alongside subtype-only fields in a single feed query.

dbschema/queries/feed.edgeql
select FeedItem {  id,  kind := .__type__.name,  created,  author: { name },  [is ArticlePost].headline,  [is ArticlePost].word_count,  [is VideoPost].caption,  [is VideoPost].duration_seconds,}order by .created desclimit 20

napalm generate emits nullable fields for subtype-only projections while keeping base fields non-null, so UI components switch cleanly on kind ('default::ArticlePost' or 'default::VideoPost') without extra round trips.

Sets, cardinality and no NULLs#

Every EdgeQL expression carries both a value type and a static cardinality bound checked at compile time.

One (1)
Always returns exactly one element (such as a required single field, a literal or count(...)).
At most one (0..1)
Returns zero or one element (such as an optional single field or a filter on an exclusive constraint).
Many (0..*, 1..*)
Returns an arbitrary set of elements (such as a multi link or an unfiltered select).

Compile-time checks catch a missing required field and a multi-element set passed where a single value is expected. Every value is a set, so EdgeQL has no SQL NULL. An absent optional value is the empty set {}, and filter clauses avoid three-valued NULL surprises.

Indexing and query evolution#

Every single and multi link indexes target keys automatically, and constraint exclusive creates a unique B-tree index. Declare explicit index on (...) definitions for properties used in frequent filter clauses, order by sorts and access-policy predicates.

Composite filter + sort
Place equality-filtered links or properties first and the sort key last, such as index on ((.author, .visibility, .created)) for filtered backlink feeds.
Replica-routable reads
Keep read queries free of volatile functions (uuid_generate_v4(), random()). Use stable functions such as datetime_of_statement() so reads stay eligible for read replicas and engine caches.
Additive query updates
Adding a new output field to a shape or adding an <optional ...> parameter with ?? preserves existing callers of POST /query/{name}.
Breaking query changes
When changing a required parameter type or removing a field that open browser or mobile clients still read, deploy a new query file (getNoteV2.edgeql) alongside the existing file first.

See Live schema changes for zero-downtime query rollouts and Troubleshooting & auditing for profiling per-policy CPU share with napalm insights.

Project API statement sandbox#

Every Project API call runs one compiled data statement per request and rejects multi-statement scripts, DDL and catalog introspection before execution.

Allowed on the Project APIRejected (400 query_rejected)
Single select, insert, update, delete, group or for statementMulti-statement scripts or explicit transaction commands (start transaction)
Your schema’s types, links, properties, functions and globalsDDL (create, alter, drop), migrations and configure
Reading .__type__.name for subtype discriminationSession state commands (set global, reset) and system catalogs (schema::*, sys::*, cfg::*)
Calling your own schema functions that wrap ext::ai or ext::filesDirect calls to ext::* functions (other than ext::pgcrypto, ext::ai::search, ext::ai::hybrid_search and ext::ai::to_context) or is_private functions

Type a word or two to search every docs page.