Simple explanation
stats is one of the most-used commands in all of Splunk — it calculates aggregate statistics over your search results. This lesson goes deep on how it actually works.
Technical explanation
- Basic syntax:
stats <function>(<field>) by <field(s)>— calculates the specified function, grouped by the specified field(s). - Common functions:
count(number of events),sum()(total of a numeric field),avg()(average),min()/max(),values()(list of ALL unique values for a field),list()(list of ALL values, including duplicates),dc()(distinct count — the NUMBER of unique values, distinct fromvalues()which lists them out). - The
byclause — without it,statsproduces one single row summarizing the entire result set; with it, produces one row per unique combination of the grouped field(s). - Multiple statistics in one command:
stats count, avg(response_time) by hostcalculates both in a single pass. statsvs.chartvs.timechart— all are transforming commands using similar function syntax, butstatsproduces a flat table,chartproduces data specifically formatted for visualization with one field as the x-axis, andtimechartspecifically buckets results over time.- Renaming output:
stats count as total_events— withoutas, the output field takes a default name based on the function used.
Synonyms / related terms
| Term | Means | |---|---| | dc() | Distinct count function | | values() | Lists all unique values of a field (as a multi-value result) | | Transforming command | A command (like stats) that converts events into a statistical table |
Concept Check
"A user wants to know exactly HOW MANY different values a field has, not what those values actually are." values(fieldname) is the wrong function here — it returns the LIST of unique values, not a count of them. dc(fieldname) (distinct count) is the correct choice, returning a single number representing how many unique values exist.
Interview-style Q&A
Q: Why would you use stats without a by clause at all? A: "When you want one single summary number or row for the entire search — like 'total event count across everything' or 'average response time across the whole dataset' — rather than broken down by any dimension. It's the simplest form of stats, useful for a quick top-line metric before drilling into any grouping."
Memory trick
"Count the Events, Sum the Numbers, Average the Trend, Distinct-count the Uniques" — four of the most common stats functions, each tied to the specific question it answers.