STATS … BY
12 min · 2 ejercicio(s)
STATS groups rows and calculates aggregates per group. It replaces the whole table with one row per group:
FROM lab-auth
| WHERE event.outcome == "failure"
| STATS failures = COUNT(*) BY source.ip
| SORT failures DESC
| LIMIT 10Common aggregation functions:
| Function | Meaning |
|---|---|
COUNT(*) / COUNT(field) |
Number of rows / rows where the field has a value |
COUNT_DISTINCT(field) |
Number of different values (approximate on very large data) |
SUM, AVG, MIN, MAX, MEDIAN |
Numeric aggregates. MIN/MAX also work on dates |
VALUES(field) |
All distinct values as a multi-value column |
TOP(field, n, "desc") |
The top n values |
You can calculate several aggregates at once and group by several fields:
FROM lab-auth
| STATS logons = COUNT(*), users = COUNT_DISTINCT(user.name), first_seen = MIN(@timestamp) BY source.ip, service.nameThis "stack counting" is the bread and butter of threat hunting: the rare and the extreme values are where attacks hide.
🔎 Profundiza: funciones, errores habituales y práctica
Aggregation functions you will use most
| Function | Example | Note |
|---|---|---|
COUNT(*) |
number of rows | COUNT(field) counts only rows where the field is not null |
COUNT_DISTINCT(field) |
distinct users per IP | approximate (HyperLogLog++), exact up to ~3,000 values by default |
SUM, AVG, MIN, MAX |
bytes per host | MIN/MAX also on dates: first/last seen |
MEDIAN, PERCENTILE(f, 99) |
typical vs. extreme values | robust against outliers |
VALUES(field) |
all user names of an IP | returns a multi-value column |
TOP(field, 3, "desc") |
top 3 values | multi-value result |
MEDIAN_ABSOLUTE_DEVIATION, STD_DEV |
spread | outlier detection |
Filtering per aggregate
You can filter one aggregate without filtering the whole query:
FROM lab-auth
| STATS failures = COUNT(*) WHERE event.outcome == "failure",
successes = COUNT(*) WHERE event.outcome == "success"
BY source.ip
| WHERE failures > 10 AND successes > 0This one query finds "brute force followed by success" for every source at once.
Stack counting
Hunting rule of thumb: group by a behaviour and look at the least frequent values (SORT count ASC). Malware is rare in an environment, normal software is common. COUNT_DISTINCT(host.name) per process name is a classic: a binary seen on only one host deserves a look.