With

All top-level EdgeQL statements (select, insert, update, and delete) can be prefixed with a with block. These blocks contain declarations of standalone expressions that can be used in your query.

  1. db>
  2. ...
  1. with my_str := "hello world"
  2. select str_title(my_str);
  1. {'Hello World'}

The with clause can contain more than one variable. Earlier variables can be referenced by later ones. Taken together, it becomes possible to write “script-like” queries that execute several statements in sequence.

  1. db>
  2. ...
  3. ...
  4. ...
  1. with a := 5,
  2. b := 2,
  3. c := a ^ b
  4. select c;
  1. {25}

Subqueries

There’s no limit to the complexity of computed expressions. EdgeQL is fully composable; queries can be embedded inside each other simply. The following query fetches a list of all movies featuring at least one of the original six Avengers.

  1. db>
  2. ...
  3. ...
  4. ...
  5. ...
  6. ...
  7. ...
  8. ...
  9. ...
  10. ...
  1. with avengers := (select Hero filter .name in {
  2. 'Iron Man',
  3. 'Black Widow',
  4. 'Captain America',
  5. 'Thor',
  6. 'Hawkeye',
  7. 'The Hulk'
  8. })
  9. select Movie {title}
  10. filter avengers in .characters;
  1. {
  2. default::Movie {title: 'Iron Man'},
  3. default::Movie {title: 'The Incredible Hulk'},
  4. default::Movie {title: 'Iron Man 2'},
  5. default::Movie {title: 'Thor'},
  6. default::Movie {title: 'Captain America: The First Avenger'},
  7. ...
  8. }

Query parameters

A common use case for with clauses is the initialization of query parameters.

  1. with user_id := <uuid>$user_id
  2. select User { name }
  3. filter .id = user_id;

For a full reference on using query parameters, see EdgeQL > Parameters.

Module selection

By default, the active module is default, so all schema objects inside this module can be referenced by their short name, e.g. User, BlogPost, etc. To reference objects in other modules, we must use fully-qualified names (default::Hero).

However, with clauses also provide a mechanism for changing the active module on a per-query basis.

  1. db>
  2. ...
  1. with module schema
  2. select ObjectType;

This with module clause changes the default module to schema, so we can refer to schema::ObjectType (a built-in EdgeDB type) as simply ObjectType.

See also

Reference > Commands > With