Loading

ES|QL COUNT function

Embedded
field

Expression that outputs values to be counted. If omitted, equivalent to COUNT(*) (the number of rows).

Returns the total number (count) of input values.

field result
aggregate_metric_double long
boolean long
cartesian_point long
cartesian_shape long
date long
date_nanos long
dense_vector long
double long
exponential_histogram long
geo_point long
geo_shape long
geohash long
geohex long
geotile long
integer long
ip long
keyword long
long long
tdigest long
text long
unsigned_long long
version long
FROM employees
| STATS COUNT(height)
		
COUNT(height):long
100

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

FROM employees
| STATS count = COUNT(*) BY languages
| SORT languages DESC
		
count:long languages:integer
10 null
21 5
18 4
17 3
19 2
15 1

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

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.

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.

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

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

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

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.

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