Skip to the page

Learn · Data & files

Queries & mutations

One EdgeQL statement fetches a nested object graph or makes a multi-step change as one 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. Every example on this page builds on the Schema page.

Deployed query stencil

Each saved .edgeql file compiles with every touched access policy into one verified SQL query exposed across SDKs, HTTP and MCP.

Consistent linked snapshot

PostgreSQL evaluates parent rows and nested child arrays against one snapshot with zero N+1 round trips.

Backlinks & inline computeds

Reverse .<author[is Note] walks and derived count() expressions evaluate live in SQL with zero stale counters.

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" }    ]  }]

Both note_count and latest evaluate inline from the notes backlink against a single consistent PostgreSQL snapshot.

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.

Tuple keyset pagination window

Filtering (.created, .id) < ($after_created, $after_id) seeks directly on index on ((.created, .id)) without scanning or policy-checking skipped pages.

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 (for example, <uuid>$id or <optional datetime>$before) and pass values separately in the request’s variables object. 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
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.

Single-statement mutations and atomic FOR batches

Single-row writes, unless conflict upserts and unpacked for … union batches compile into one all-or-nothing SQL statement verified against insert, update read and update write policies.

Insert#

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

Note.author defaults to the Person matching global caller, so omitting author sets the authenticated user automatically. The allow insert policy prevents spoofing another author. 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.edgeql
update Notefilter .id = <uuid>$idset {  title := <str>$title,  tags += 'shipped',}
delete.edgeql
delete Note filter .id = <uuid>$id

update and delete automatically filter target rows by the caller’s update read and delete policies. Before committing, update also verifies the resulting row against update write.

Upsert (insert … unless conflict)#

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

Batch writes with for#

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

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

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 unions and [is Subtype] projections

Querying an abstract type or type union fetches shared base fields and [is Subtype] projections in one round trip, discriminated by .__type__.name.

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;}
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.