# Preamble

The preamble of a pipeline allows the local declaration of functions using `with` statements. These functions can be called from the pipeline, and from other premable functions.

## [](#_syntax)Syntax

```typeql
with <function-declaration>
[with <function-declaration>]
...

<pipeline>
```

where `<function-declaration>` is a [function declaration](../../functions/writing/index.md#declaration).

## [](#_behavior)Behavior

*   The `with` declarations in a data pipeline must precede the pipeline.
    
*   `with` declarations **must** be followed by a data pipeline, i.e. `with` stages by themselves do not consitute a valid data query.
    
*   Function declarations in the preamble of a data pipeline are only valid within that pipeline (declared functions may be called in `match` and `fetch` stages).
    

## [](#_validation)Validation

The usual function validation applies to the function declaration in a with clause.

## [](#_examples)Examples

Schema for the following examples

```typeql
#!test[schema, commit]
define
  entity content owns id;
  entity page sub content,
    owns page-id,
    owns name;
  entity profile sub page,
    owns username;
  entity user sub profile,
    owns phone,
    owns karma;

  attribute id value string;
  attribute page-id sub id;
  attribute username sub page-id;
  attribute name value string;
  attribute phone value string;
  attribute karma value double;
attribute start-date, value date;
relation friendship relates friend @card(0..2), owns start-date;
user plays friendship:friend;
```

1.  Find users with more friends than a specific user and return their usernames
    
    ```typeql
    #!test[read]
    with fun friend_count($user: user) -> integer:
      match friendship($user, $x);
      return count;
    match
      $user1 isa user, has username "<name>";
      $user2 isa user, has username $name;
      friend_count($user1) < friend_count($user2);
    select $name;
    ```
    
2.  Return all “popular” users in the database
    
    ```typeql
    #!test[read]
    with fun friend_count($user: user) -> integer:
      match friendship($user, $x);
      return count;
    
    with fun popular_users() -> { user }:
      match
        $x isa user;
        friend_count($x) > 500;
      return { $x };
    
    match
      let $y in popular_users();
      $y has username $pop_name;
    select $pop_name;
    ```
    

[Reduce](../reduce/index.md) [End](../end/index.md)

[Edit on GitHub](https://github.com/typedb/typedb-docs/edit/3.x-development/typeql-reference/modules/ROOT/pages/pipelines/with.adoc) Edit this page on GitHub.