FQL v4 will be decommissioned on June 30, 2025. Ensure that you complete your migration from FQL v4 to FQL v10 by that date.

For more details, review the migration guide. Contact support@fauna.com with any questions.

Sum

This reference topic applies to FQL v4. Go to this page for the latest FQL v10 reference topics.

Sum( arrayOrSet )
sum( arrayOrSet )
Sum( arrayOrSet )
Sum( arrayOrSet )
Sum( arrayOrSet )

Description

The Sum function returns the sum of all items in arrayOrSet, which is an Array, Page, or Set.

The run time of Sum is dependent on the number of elements in the underlying set or page — it’s linear, or O(n). For very large sets or pages, executing Sum might result in a query timeout error, or "width" error.

For query "width" errors, the underlying set or page involves more than 100K items. This can happen when using a set function, such as Difference, where more than 100K items need to be considered to produce the set that Sum evaluates. To resolve this, use Paginate to limit the set or page size.

For example, instead of:

Sum(
  Difference(
    Match(Index("Index1"), "term1"),
    Match(Index("Index2"), "term2")
  )
)

use:

Sum(
  Paginate(
    Difference(
      Match(Index("Index1"), "term1"),
      Match(Index("Index2"), "term2")
    ),
    { size: 10000 }
  )
)

This does mean that if the entire set must be evaluated to arrive at the correct result, you would have to page through the Paginate results.

For query timeout errors, you may specify a larger query timeout via the driver that you are using.

Parameters

Parameter Type Definition and Requirements

arrayOrSet

Array, Page, or Set

The Array, Page, or Set that should have its items summed.

Returns

A Number representing the sum of all items in arrayOrSet.

Examples

The following query returns the sum of items in the provided array:

client.query(
  q.Sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
)
.then((ret) => console.log(ret))
.catch((err) => console.error(
  'Error: [%s] %s: %s',
  err.name,
  err.message,
  err.errors()[0].description,
))
55
result = client.query(
  q.sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
)
print(result)
55
result, err := client.Query(
	f.Sum(f.Arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}))

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
55
try
{
    Value result = await client.Query(
        Sum(Arr(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
LongV(55)
Sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
55
Query metrics:
  •    bytesIn:  30

  •   bytesOut:  15

  • computeOps:   1

  •    readOps:   0

  •   writeOps:   0

  •  readBytes:   0

  • writeBytes:   0

  •  queryTime: 2ms

  •    retries:   0

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!