count / count() / countif()

There are three ways to count in KQL, and they produce different column names.

The count operator counts the rows that reach it and returns a single row with a single column called Count:

SecurityEvent
| where EventID == 4625
| count

The count() aggregate is used inside summarize. With by, it counts the rows in each group. Its default column name is count_ (with an underscore), so a later operator refers to it as sort by count_. Naming it is clearer: summarize Failures = count() by IPAddress.

countif(condition) counts only the rows where the condition is true. It lets you compute several counts in one summarize, which is shorter and faster than running two queries. Its default name is countif_.

Things to know

  • count (the operator) takes no parentheses and stands on its own after a pipe; count() (the aggregate) needs them and goes inside summarize.
  • Counts are whole numbers (long). When you divide one count by another, convert one side first with todouble(), or the result is rounded down.
  • To count different values rather than rows, use dcount().

Examples

1 How many rows match? (the count operator)
SigninLogs
| where Location == "BR"
| count

The count operator returns one row with one column, named Count.

2 Rows per group, and failures per group, in one pass
SigninLogs
| summarize count(), countif(ResultType != "0") by AppDisplayName

The default names are count_ and countif_.

3 Two conditional counts side by side
SecurityEvent
| summarize Logons = countif(EventID == 4624), Failures = countif(EventID == 4625) by Computer
| extend FailureShare = todouble(Failures) / (Logons + Failures)

todouble() makes the division a decimal one; dividing two whole numbers would round down to 0.

Practice it