Most slow or misleading hunting queries fail on a few KQL details: the wrong string operator, a join that silently drops rows, or a time filter applied in the wrong place. This cheat sheet is a compact lookup for threat hunters and SOC analysts writing Kusto Query Language (KQL) in Microsoft Sentinel and Microsoft Defender XDR advanced hunting. It covers the operators you use every day, time and string filtering, joins and aggregation, parsing, a set of short defensive hunting patterns for sign-ins, processes and cloud activity, and performance rules. Hunting method, identity-specific hunts and turning hunts into detections are covered in the KQL for Threat Hunting Guide; this page stays a reference.
This is an independent guide from NHI Mgmt Group, based on Microsoft's public KQL and Defender XDR documentation as of November 2026. It is not sponsored or reviewed by Microsoft. Table schemas change, so confirm column names against the schema reference in your portal.
Key takeaways
- Filter on time first. Put the time filter and the cheapest equality filters at the top, before extend, parse or join.
- Use has, not contains, for words. has uses the term index (terms of three characters or more); contains scans every value and is much slower.
- The default join deduplicates. With no kind, join is innerunique and keeps one left row per key. Write kind=inner, leftouter or leftanti explicitly.
- Two engines, two time columns. Defender XDR tables use Timestamp; Sentinel and Log Analytics tables use TimeGenerated. Microsoft says to rely on Timestamp for when a Defender event actually happened.
- Know your retention. Defender tables keep 30 days in advanced hunting unless streamed to Sentinel with longer retention; hunts over longer periods need the Sentinel copy.
How to use this template
- Writing a hunt: pick the table from the table notes in section 5, start with the skeleton below, add filters with section 2, then aggregate with section 3.
- Reviewing a query: check the time column, every string operator against the table in section 2, the join kind, and the performance rules in section 6.
- Adapting the patterns: the snippets in section 5 are defensive starting points. Replace thresholds, allowlists and account names such as [svc-account] with values from your environment, and run them over a known-good period first to measure noise.
- Testing: run with take 100 or count first, then widen the time range.
1 Sample only, based on the public documentation cited. Assess it independently against the current official documentation, test outside production and back up first.
// Hunt skeleton
let lookback = 7d;
TableName
| where TimeGenerated > ago(lookback) // Timestamp for Defender XDR tables
| where Column == "value" // cheapest, most selective filters first
| extend Derived = tostring(DynamicCol.field)
| summarize Count = count(), First = min(TimeGenerated), Last = max(TimeGenerated) by Key
| where Count > 5
| order by Count desc1. Core operators
A KQL query is a tabular expression: a table name followed by operators joined with the pipe character. Statements such as let end with a semicolon.
| Operator | What it does | Hunting use |
|---|---|---|
| where | Filters rows on a predicate | Every query: time, action type, account |
| project, project-away, project-rename | Selects, removes or renames columns | Trim columns before join and for readable output |
| extend | Adds calculated columns | Pull fields out of dynamic columns |
| summarize | Groups rows by columns and calculates aggregations | Counts, distinct counts, first and last seen |
| count | Counts input rows | Size a query before running it in full |
| take (limit) | Returns a set number of rows | Testing a new query |
| top, sort (order by) | Returns first N rows by a column; sorts rows | Rarest or busiest entities |
| distinct | Returns distinct combinations of columns | Build a baseline set |
| join, lookup | Merges two tables on keys; extends a fact table from a dimension table | Correlate process with network, sign-in with audit |
| union | Returns rows from two or more tables | Search one indicator across tables |
| mv-expand | Expands a dynamic array into one row per element | Arrays of targets, roles or IP addresses |
| parse | Extracts columns from a string with a pattern | Free-text fields and command lines |
| make-series | Builds aggregated series along an axis | Volume over time per entity |
| let | Binds a name to a value, list or subquery | Lookback, allowlists, reusable subqueries |
| search | Searches all columns in a table | Avoid unscoped; use search in (TableA, TableB) |
| render | Charts results | Visual triage of a time series |
2. Time and filtering
Time: ago(1h) returns a time relative to query execution; between (ago(14d) .. ago(1d)) gives a window; bin(TimeGenerated, 1h) buckets times for counting; format_datetime() formats output. In Defender XDR advanced hunting, if you filter ingestion of Defender tables into Sentinel rather than streaming them whole, Microsoft advises using the portal's time filter instead of a time filter in the query, to avoid incomplete results.
Strings: KQL splits strings into terms (maximal runs of alphanumeric characters) and indexes terms of three characters or more. Operators ending in _cs are case-sensitive and generally faster.
| Operator | Matches when | Case-sensitive | Notes |
|---|---|---|---|
| ==, != | Exact equality | Yes | Fastest; use for known values |
| =~, !~ | Equality ignoring case | No | Use when case varies in the data |
| in, in~ | Equals any element of a list | in yes, in~ no | Pair with a let list |
| has, has_cs | Right side is a whole term in the left side | has no, has_cs yes | Uses the term index; first choice for words |
| has_any, has_all | Any or all terms in a list are present | No | Indicator lists against command lines |
| hasprefix, hassuffix | A term starts or ends with the value | No (_cs forms exist) | Partial terms such as file extensions |
| contains, contains_cs | Substring anywhere | contains no, contains_cs yes | Scans values; use only when has cannot work |
| startswith, endswith | Value begins or ends with substring | No (_cs forms exist) | Paths and domains |
| matches regex | Regular expression match | Yes | Slowest; filter first, regex last |
| has_ipv4, has_ipv4_prefix | IPv4 address or prefix present as a term | Not applicable | Optimised for IP addresses in text |
Example: "KustoExplorerQueryRun" has "Explorer" is false, because Explorer is not a whole term, while contains "Explorer" is true. Avoid filtering on terms shorter than three characters, which cannot use the index.
3. Joins and summarise
| Join kind | Returns | Typical hunting use |
|---|---|---|
| innerunique (default) | Matching rows after deduplicating the left side by key | Rarely what you want; state the kind instead |
| inner | All matching rows from both sides | Process event joined to its network events |
| leftouter | All left rows, with right columns where matched | Enrich sign-ins with optional context |
| leftanti | Left rows with no match on the right | New since baseline: today minus last 14 days |
| leftsemi | Left rows that have a match, left columns only | Keep only events for watchlisted accounts |
| fullouter, rightouter, rightanti, rightsemi | Mirror forms of the above | Reconciliation between two sources |
Put the smaller table on the left, project only the columns you need on both sides, and filter both sides by time. For high-cardinality keys, hint.shufflekey = Key on join or summarize spreads the work; hint.strategy = broadcast suits a small left table (up to about 100,000 records) against a very large right table.
Aggregations used with summarize: count(), countif(predicate), dcount(col) (approximate distinct count), dcountif(), make_set(col, max) (distinct values), make_list(), min(), max(), sum(), percentiles(), take_any(), and arg_max(TimeGenerated, *) to keep the latest row per key.
// Latest record per device, then first and last seen per account
DeviceLogonEvents
| where Timestamp > ago(7d)
| summarize arg_max(Timestamp, *) by DeviceName
| summarize Devices = dcount(DeviceName), FirstSeen = min(Timestamp), LastSeen = max(Timestamp) by AccountName4. Parsing and extraction
| Need | Use | Example |
|---|---|---|
| Field from a dynamic column | Dot notation with tostring() | tostring(DynamicCol.field) |
| JSON held in a string | parse_json(), then dot notation | parse_json(AdditionalFields).DriveLetter |
| Delimited text | parse (kind simple, regex or relaxed) | parse Msg with * "user=" User " src=" Src |
| Rows that fail to parse not needed | parse-where | Drops non-matching rows |
| Command line arguments | parse_command_line() | Split a process command line into an array |
| File paths, versions, IP addresses | parse_path(), parse_version(), parse_ipv4(), parse_ipv6() | Compare versions or subnets reliably |
| Complex pattern | extract(), extract_all() | Last resort: regular expressions are costly |
| Arrays to rows | mv-expand | One row per target resource |
In parse, kind=simple sets every extracted column to null if any delimiter or type does not match; kind=relaxed nulls only the column that fails its type. Microsoft's advanced hunting guidance is to prefer parse and the dedicated parse functions over matches regex and extract(), and to parse only after filters have reduced the rows.
5. Common hunting patterns
Table notes: Defender XDR tables include DeviceProcessEvents (process creation), DeviceNetworkEvents (network connections), DeviceLogonEvents (device sign-ins), DeviceFileEvents, DeviceRegistryEvents, DeviceEvents (multiple types, including security control events), EmailEvents, IdentityLogonEvents, CloudAppEvents and EntraIdSignInEvents. Sentinel and Log Analytics tables include SigninLogs (ResultType "0" is success), AuditLogs and AzureActivity. In DeviceProcessEvents, InitiatingProcess* columns describe the parent; SHA256 is often empty, so pivot on SHA1. For identity and service principal hunts, see the KQL for Threat Hunting Guide and the Defender for Endpoint Advanced Hunting Tables Guide.
| Pattern | Table | ATT&CK |
|---|---|---|
| Password spray from one source | SigninLogs | T1110.003 Password Spraying |
| Successful single-factor sign-ins from new countries | SigninLogs | T1078.004 Cloud Accounts |
| Encoded PowerShell | DeviceProcessEvents | T1059.001 PowerShell |
| Office application spawning a shell | DeviceProcessEvents | T1059.001 PowerShell |
| Rare process on few devices | DeviceProcessEvents | Triage aid, no single technique |
| Role assignment writes in Azure | AzureActivity | T1098.003 Additional Cloud Roles |
// Password spray: many users, one IP, failed sign-ins (50126 = invalid credentials)
SigninLogs
| where TimeGenerated > ago(1d)
| where ResultType == "50126"
| summarize Users = dcount(UserPrincipalName), Attempts = count() by IPAddress, bin(TimeGenerated, 1h)
| where Users > 10// Successful single-factor sign-ins from a country not seen for that user in the prior 14 days
let known = SigninLogs
| where TimeGenerated between (ago(15d) .. ago(1d)) and ResultType == "0"
| extend Country = Location
| distinct UserPrincipalName, Country;
SigninLogs
| where TimeGenerated > ago(1d) and ResultType == "0"
| where AuthenticationRequirement == "singleFactorAuthentication"
| extend Country = Location
| join kind=leftanti known on UserPrincipalName, Country
| project TimeGenerated, UserPrincipalName, Country, IPAddress, AppDisplayName, ClientAppUsed// Encoded PowerShell command lines
DeviceProcessEvents
| where Timestamp > ago(7d)
| where FileName in~ ("powershell.exe", "pwsh.exe")
| where ProcessCommandLine matches regex @"(?i)\s-(ec|e[ncodema]*)\s+[A-Za-z0-9+/=]{20,}"
| project Timestamp, DeviceName, AccountName, ProcessCommandLine, InitiatingProcessFileName// Office applications starting a command shell or script host
DeviceProcessEvents
| where Timestamp > ago(7d)
| where InitiatingProcessFileName in~ ("winword.exe", "excel.exe", "powerpnt.exe", "outlook.exe")
| where FileName in~ ("cmd.exe", "powershell.exe", "pwsh.exe", "wscript.exe", "cscript.exe", "mshta.exe")
| project Timestamp, DeviceName, AccountName, InitiatingProcessFileName, FileName, ProcessCommandLine// Rare executables: seen on three or fewer devices in 7 days
DeviceProcessEvents
| where Timestamp > ago(7d)
| summarize Devices = dcount(DeviceName), Sample = take_any(ProcessCommandLine) by SHA1, FileName
| where Devices <= 3
| order by Devices asc// Azure role assignment writes, with caller and source IP
AzureActivity
| where TimeGenerated > ago(7d)
| where OperationNameValue =~ "Microsoft.Authorization/roleAssignments/write"
| where ActivityStatusValue == "Succeeded"
| project TimeGenerated, Caller, CallerIpAddress, SubscriptionId, ResourceGroup, Properties_dNotes: PowerShell accepts shortened forms of -EncodedCommand (and the -ec alias), and the flags are too short for the term index, so the encoded command hunt uses a regular expression placed after the cheaper FileName filter. ActivityStatusValue values vary by event (Started, Succeeded, Failed and others), so check your data before relying on the filter.
6. Performance tips
| Do | Instead of | Why |
|---|---|---|
| Time filter on the table column first | Filtering after extend or join | Reduces rows before expensive work |
| Filter on table columns | Filtering on calculated columns | Table columns can use indexes |
| has, has_cs, ==, in | contains, =~, matches regex | Term index and case-sensitive matching are faster |
| project before join | Joining full rows | Less data moved and matched |
| Smaller table on the left of join | Large table on the left | Fewer records to match |
| search in (TableA, TableB) "value" | Unscoped search or union * | Limits the tables scanned |
| count or take while building | Running the full query first | Avoids large results and quota use |
| Specific columns | Checking every column with * | Narrower scans |
The Defender portal shows resource usage as Low, Medium or High for each query; Microsoft says High indicates a query that could be improved, and frequent heavy queries count against quotas. To query Sentinel and Defender data together in the unified advanced hunting page you need at least the Microsoft Sentinel Reader role. For converting queries to other languages, see the Security Query Languages Translation Cheat Sheet.
Measuring hunts: track hunts run per month, the share that produced a finding or a new detection, false positive rate after tuning, median query resource level, and the number of hunts promoted to scheduled analytics rules.
Practitioner checklist
- Use Timestamp for Defender XDR tables and TimeGenerated for Sentinel tables, and know which one each query uses.
- Put the time filter first and the most selective equality filters next.
- Use has or has_any for words and indicators; reserve contains and regex for cases has cannot handle.
- Always write the join kind; use leftanti for "new since baseline" hunts.
- Project needed columns before joins and keep the smaller table on the left.
- Parse after filtering, with parse or dedicated functions before extract().
- Run new hunts over a known-good period to measure noise before acting on results.
- Check retention: use the Sentinel copy for Defender data older than 30 days.
Standards and references
- Microsoft Learn: KQL quick reference
- Microsoft Learn: String operators
- Microsoft Learn: join operator
- Microsoft Learn: parse operator
- Microsoft Learn: Advanced hunting query best practices
- Microsoft Learn: Understand the advanced hunting schema
- Microsoft Learn: Advanced hunting with Microsoft Sentinel data in the Defender portal
- Microsoft Learn: SigninLogs table reference
Related NHI Mgmt Group resources: KQL for Threat Hunting Guide, Microsoft Sentinel Guide, Sigma Rule Syntax Cheat Sheet, Identity Threat Hunting Guide.