Back to Elasticsearch

Count

docs/reference/query-languages/esql/_snippets/functions/examples/count.md

9.4.02.1 KB
Original Source

% This is generated by ESQL's AbstractFunctionTestCase. Do not edit it. See ../README.md for how to regenerate it.

Examples

esql
FROM employees
| STATS COUNT(height)
COUNT(height):long
100

To count the number of rows, use COUNT() or COUNT(*)

esql
FROM employees
| STATS count = COUNT(*) BY languages
| SORT languages DESC
count:longlanguages:integer
10null
215
184
173
192
151

The expression can use inline functions. This example splits a string into multiple values using the SPLIT function and counts the values.

esql
ROW words="foo;bar;baz;qux;quux;foo"
| STATS word_count = COUNT(SPLIT(words, ";"))
word_count:long
6

To count the number of times an expression returns TRUE use a WHERE command to remove rows that shouldn’t be included.

esql
ROW n=1
| WHERE n < 0
| STATS COUNT(n)
COUNT(n):long
0

To count the number of times multiple expressions return TRUE use a WHERE inside the STATS.

esql
FROM employees
| STATS
    gte20 = COUNT(*) WHERE height >= 2,
    lte18 = COUNT(*) WHERE height <= 1.8
gte20:longlte18:long
2056

COUNTing a multivalued field returns the number of values. COUNTing NULL returns 0. COUNTing true returns 1. COUNTing false returns 1.

esql
ROW mv = [1, 2], n = NULL, t = TRUE, f = FALSE
| STATS COUNT(mv), COUNT(n), COUNT(t), COUNT(f)
COUNT(mv):longCOUNT(n):longCOUNT(t):longCOUNT(f):long
2011

You may see a pattern like COUNT(<expression> OR NULL). This has the same meaning as COUNT() WHERE <expression>. This relies on COUNT(NULL) to return 0 and builds on the three-valued logic (3VL): TRUE OR NULL is TRUE, but FALSE OR NULL is NULL. Prefer the COUNT() WHERE <expression> pattern.

esql
ROW n=1
| STATS COUNT(n > 0 OR NULL), COUNT(n < 0 OR NULL)
COUNT(n > 0 OR NULL):longCOUNT(n < 0 OR NULL):long
10