Stage 03 · Advanced KQL — Production techniques
Audience: SOC analysts advancing to threat hunting, detection engineers, architects. Tables: this stage uses the real Sentinel tables (
SigninLogs,AuditLogs,SecurityEvent, …). They return data only where the relevant connector is ingesting. Empty workspace? Run these anyway. The Sentinel Table Library ships schema-true sample logs for these exact tables — ingest them into an ADX free cluster (or paste alet datatable()from itscsv_to_kql.py) and the real-table queries below run as-is, returning the Operation Quiet Ledger attack data.
⚠️ Real-table reminder: in
SigninLogs,ResultTypeis a string — useResultType != "0", not!= 0. (It's an int only in the demo set.) SigninLogs reference
1. Advanced aggregation
Beyond count() and sum(), KQL has a rich aggregation set: conditional counts (countif), approximate distinct counts (dcount), percentiles (percentile/percentiles), and whole-record retrieval (arg_max/arg_min). Combine several in one summarize.
SigninLogs
| where TimeGenerated > ago(7d)
| summarize TotalLogins = count(),
FailedLogins = countif(ResultType != "0")
by UserPrincipalName
| sort by FailedLogins desc
Latest record per group with arg_max — the * (or a list of columns) returns the rest of the winning row:
SigninLogs
| where TimeGenerated > ago(7d)
| summarize arg_max(TimeGenerated, IPAddress, AppDisplayName) by UserPrincipalName
Always include a time filter (
TimeGenerated > ago(7d)) to bound the scan. Reference: Aggregation functions · arg_max()
2. Time series with bin()
SigninLogs
| where TimeGenerated > ago(30d)
| summarize LoginCount = count() by bin(TimeGenerated, 1d)
| render timechart
bin() is a floor operation on time (or numbers). Pick a size that fits the span — daily for long ranges, hourly for recent detail. Reference: bin()
3. Join types and when to use them
| Flavour | Returns | Use for |
|---|---|---|
inner |
only rows matching on both sides | correlated events present in both datasets |
leftouter |
all left rows + right data where matched | enrichment (e.g. alerts + threat intel) |
rightouter |
all right rows + left where matched | rare; reference set on the right |
leftanti / anti |
left rows with no match on the right | "find what's missing" (logon with no logoff) |
lookup |
left extended with small right table, no key duplication | enriching large data with a small mapping |
Reference: join operator · lookup operator
Example — session duration by correlating logon (4624) and logoff (4634) on stable keys, with the same time filter on both sides:
SecurityEvent
| where TimeGenerated > ago(1d) and EventID == 4624
| project Computer, Account, LogonTime = TimeGenerated
| join kind=inner (
SecurityEvent
| where TimeGenerated > ago(1d) and EventID == 4634
| project Computer, Account, LogoffTime = TimeGenerated
) on Computer, Account
| extend SessionDuration = LogoffTime - LogonTime
| project Account, Computer, LogonTime, LogoffTime, SessionDuration
Best practice: time-filter both sides; join on stable keys (UPN, Computer, IP, CorrelationId); normalise case with
tolower()if needed. To find logons without a logoff, swapkind=innerforkind=leftanti. Reference: Optimize log queries
4. Parsing & extracting fields
Logs often hide data inside strings or dynamic (JSON) columns.
parse— split structured text into columns
🧩 Illustrative pattern — not runnable as-is.
MyTable/Messageare placeholders for whatever table holds a delimited string column. Swap them for a real one (e.g.Syslog/SyslogMessage— see the Syslog sample, whose hunts parse exactly this way).
// Message like: "SrcIP=10.0.0.1; DestIP=10.0.0.5; Action=Allow"
MyTable
| parse Message with "SrcIP=" SrcIp "; DestIP=" DestIp "; Action=" Action
| project SrcIp, DestIp, Action
Use parse kind=regex for regex patterns, or parse-where to keep only rows that matched. Reference: parse operator
extract()— one regex capture, inline
// Pull the domain after the @ in a UPN
SigninLogs
| extend Domain = extract(@"@(.+)$", 1, UserPrincipalName)
The third arg is the source string; 1 is the capture group. No match → null. Reference: extract()
Dynamic / JSON columns — dot notation
Many Sentinel tables have dynamic columns. AuditLogs.InitiatedBy is already dynamic, so you drill straight in with dot notation (no parse_json needed) and cast the leaf with tostring():
AuditLogs
| where TimeGenerated > ago(7d)
| extend Initiator = tostring(InitiatedBy.user.userPrincipalName)
| extend TargetObject = tostring(TargetResources[0].displayName)
| project TimeGenerated, Initiator, OperationName, Result, TargetObject
If a column is a JSON string (not already dynamic), wrap it once with
parse_json()/todynamic()before indexing. Reference: parse_json() · dynamic type
mv-expand— one array element per row
TargetResources is an array. Expand it to aggregate per target:
AuditLogs
| where TimeGenerated > ago(7d)
| mv-expand TargetResource = TargetResources
| extend ResourceName = tostring(TargetResource.displayName)
| summarize Changes = count() by ResourceName
| sort by Changes desc
Filter before expanding to limit row blow-up. Reference: mv-expand operator
5. Modular queries with let
Break complex logic into named parts — clearer and easier to tune.
let failedCountByUser =
SigninLogs
| where TimeGenerated > ago(1d) and ResultType != "0"
| summarize FailedCount = count() by UserPrincipalName;
failedCountByUser
| where FailedCount > 5
Scope time filters inside each subquery so both sides of a union/join are bounded early:
let MinTime = ago(1d);
Heartbeat
| where TimeGenerated > MinTime
| summarize arg_min(TimeGenerated, *) by Computer
| union (
Perf
| where TimeGenerated > MinTime
| summarize arg_min(TimeGenerated, *) by Computer
)
let can also hold a scalar via toscalar() for percentage calculations, thresholds, etc. If a heavy subquery is reused many times, consider materialize().
Reference: let statement
6. ASIM — normalized, source-agnostic queries
The Advanced Security Information Model (ASIM) gives Sentinel a standard schema per activity type, exposed through unifying parsers named _Im_<Schema> (note the leading underscore). One ASIM query covers every source that has a parser for that schema.
✅ Correctness fixes vs. common write-ups:
- The parser name needs the leading underscore:
_Im_Dns,_Im_Authentication— notIm_Dns.- Filtering parameters in the call are lowercase (
starttime=,responsecodename=,eventresult=), even though the output fields are PascalCase (ResponseCodeName,SrcIpAddr). Source: Use ASIM parsers
Note ASIM parsers live in Microsoft Sentinel, not in plain Log Analytics and not in an ADX free cluster. If
_Im_Authenticationreturns "unknown function", you're not in a Sentinel-enabled workspace — that's expected. Study the pattern here and run the raw-table equivalents (e.g. theSigninLogsfailed-auth query in §1) against the table library samples instead.
// Normalized DNS — filtering params (lowercase) run BEFORE parsing for speed
_Im_Dns(starttime=ago(1d), responsecodename='NXDOMAIN')
| summarize count() by SrcIpAddr, bin(TimeGenerated, 15m)
// Failed authentications across every identity source that has a parser
_Im_Authentication(starttime=ago(1h), eventresult='Failure')
| summarize Failures = count() by TargetUserId
| sort by Failures desc
Why prefer ASIM: portable across sources and environments, future-proof (new sources with a parser are picked up automatically), and broad detection coverage from a single query. Always pass at least starttime= for performance. Use raw tables only for one-off exploration or where no parser exists.
7. Shaping output for visualizations
The render engine uses the first column's type to choose the X-axis, and numeric columns as values. Shape the result with project/summarize so it has exactly what the chart needs.
// Timechart: datetime first, numeric next, one string col → separate series
SigninLogs
| where TimeGenerated > ago(24h)
| summarize Count = count() by bin(TimeGenerated, 1h), ResultType
| render timechart
// Columnchart: category first, numeric second
SecurityAlert
| summarize AlertCount = count() by AlertSeverity
| project Severity = AlertSeverity, AlertCount
| render columnchart
- Timechart: datetime, then numeric(s), then at most one string (= series). Extra strings are ignored.
- Bar/column/pie: category first, numeric value second.
- Use friendly column names via
project, or set titles withrender ... with (title="...", ytitle="...").
Reference: render operator · Time chart
8. Advanced operators — know they exist
| Operator / function | What it does |
|---|---|
make-series |
Builds a complete, gap-filled array of values along a time axis — for anomaly detection / forecasting. docs |
series_decompose_anomalies() |
Flags statistically anomalous points in a series (trend/seasonality/residual). docs |
bag_pack() / pack() |
Builds a dynamic property bag (JSON object) from columns. docs |
evaluate bag_unpack() |
Expands a dynamic property bag into individual columns. docs |
mv-apply |
Runs a sub-query per expanded array element. docs |
These power trend analysis, anomaly hunting, and nested-data flattening. Reach for them when filtering and counting aren't enough.
Exercises (adapt to DemoIdentityLogsif you have no real data)
- Per user in
SigninLogs, compute total logins and the failure rate as a percentage. - From
AuditLogs, extract the initiator UPN fromInitiatedByand count operations per initiator. - Use
leftantito find users who appear inSigninLogsbut never inAuditLogs. - Rewrite a failed-auth query using
_Im_Authenticationwith proper lowercase filtering parameters.
Answers
// 1
SigninLogs
| where TimeGenerated > ago(7d)
| summarize Total = count(), Failed = countif(ResultType != "0") by UserPrincipalName
| extend FailureRatePct = round(100.0 * Failed / Total, 1)
| sort by FailureRatePct desc
// 2
AuditLogs
| where TimeGenerated > ago(7d)
| extend Initiator = tostring(InitiatedBy.user.userPrincipalName)
| where isnotempty(Initiator)
| summarize Operations = count() by Initiator
| sort by Operations desc
// 3
SigninLogs
| where TimeGenerated > ago(7d)
| distinct UserPrincipalName
| join kind=leftanti (
AuditLogs
| where TimeGenerated > ago(7d)
| extend UserPrincipalName = tostring(InitiatedBy.user.userPrincipalName)
| distinct UserPrincipalName
) on UserPrincipalName
// 4
_Im_Authentication(starttime=ago(24h), eventresult='Failure')
| summarize Failures = count() by TargetUserId, SrcIpAddr
| sort by Failures desc
You'll know you've completed Stage 03 when you can
- drill into a dynamic/JSON column (
tostring(InitiatedBy.user.userPrincipalName)) andmv-expandan array; - pick the right
joinflavour (inner/leftouter/leftanti/lookup) for the question; - modularise a query with
letand scope the time filter inside each subquery; - write a normalised
_Im_*ASIM query with lowercase call params — and know it needs a Sentinel workspace.
Next: Stage 04 · Threat Hunting — MITRE-mapped hunts across identity and endpoint.
Mission 03 challenge
In SigninLogs, find users who signed in from more than two IP addresses in the last week, and list the apps each one used.
Write it in the box below and check it. Then compare with one answer; others can be right too.
Show one answer
SigninLogs
| where TimeGenerated > ago(7d)
| summarize IPs = dcount(IPAddress), Apps = make_set(AppDisplayName) by UserPrincipalName
| where IPs > 2Check your own query
Write a variation of this lesson's queries, on the practice table DemoIdentityLogs or a real table, and check it against the real schema.
Course by Kaushik Saha. Source: sentinel/kql/03-advanced/README.md at ea5adab001fa. Queries checked with Microsoft.Azure.Kusto.Language 12.4.1 against schema bundle 2026.10.29.