# Reduce operator

## [](#_reduce)Reduce

### [](#_syntax)Syntax

```typeql
reduce <var> = <operator> [ (<var>) ] [ , ... ];
```

TypeQL supports the following reduce operators:

*   `count` — total number of answers, or, when used with a variable, number of distinct values of the variable,
    
*   `max` — the **maximum** value of the variable,
    
*   `min` — the **minimum** value of the variable,
    
*   `mean` — the **arithmetic mean** of the values of the variable,
    
*   `median` — the **median** value of the variable,
    
*   `std` — the **sample standard deviation** of the values of the variable,
    
*   `sum` — the sum of the values of the variable,
    
*   `list` — Coming with lists: reduces the stream to a list of occurrences of a specified variable.
    

### [](#_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;
  attribute last-login, value date;
  user owns last-login;

  attribute size-kb, value double;
  entity file, owns size-kb;

  relation located, relates country, relates user;
  entity country, plays located:country;
  user plays located:user;
```

Count the number of logins since `2025-01-01`:

```typeql
#!test[read]
match
  $user isa user, has last-login >= 2025-01-01;
reduce $logins = count;
```

Get disk usage statistics of the files:

```typeql
#!test[read]
match
  $file isa file, has size-kb $s;
reduce $total = sum($s), $mean = mean($s), $max = max($s);
```

## [](#_grouping)Grouping

When `groupby` is used within a reduce, the answer stream is subdivided into groups based on the value of the grouping variable. The reduction is then performed separately within each such group. The output of a `reduce` with `groupby` is a stream of rows, one for each value of the grouping variable.

### [](#_syntax_2)Syntax

```typeql
reduce <var> = <operator> [ (<var>) ] [ , ... ] groupby <var>;
```

### [](#_example)Example

Get the number of users per country:

```typeql
#!test[read]
match
  $user isa user;
  $country isa country;
  {
    located($user, $country);
  } or {
    located($user, $place);
    located($place, $country);
  };
reduce $user-count = count groupby $country;
```

[Offset](../offset/index.md) [With](../with/index.md)

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