Join our Newsletter — 33% off our NHI Course
Home› Guides› KQL Threat Hunting Cheat Sheet: Queries for Sign-Ins,…
Template SOC & Detection Engineering

KQL Threat Hunting Cheat Sheet: Queries for Sign-Ins, Processes and Cloud Activity

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 27 November 2026 12 min read
On this page

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.

Sample 1
// 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 desc

1. 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.

OperatorWhat it doesHunting use
whereFilters rows on a predicateEvery query: time, action type, account
project, project-away, project-renameSelects, removes or renames columnsTrim columns before join and for readable output
extendAdds calculated columnsPull fields out of dynamic columns
summarizeGroups rows by columns and calculates aggregationsCounts, distinct counts, first and last seen
countCounts input rowsSize a query before running it in full
take (limit)Returns a set number of rowsTesting a new query
top, sort (order by)Returns first N rows by a column; sorts rowsRarest or busiest entities
distinctReturns distinct combinations of columnsBuild a baseline set
join, lookupMerges two tables on keys; extends a fact table from a dimension tableCorrelate process with network, sign-in with audit
unionReturns rows from two or more tablesSearch one indicator across tables
mv-expandExpands a dynamic array into one row per elementArrays of targets, roles or IP addresses
parseExtracts columns from a string with a patternFree-text fields and command lines
make-seriesBuilds aggregated series along an axisVolume over time per entity
letBinds a name to a value, list or subqueryLookback, allowlists, reusable subqueries
searchSearches all columns in a tableAvoid unscoped; use search in (TableA, TableB)
renderCharts resultsVisual 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.

OperatorMatches whenCase-sensitiveNotes
==, !=Exact equalityYesFastest; use for known values
=~, !~Equality ignoring caseNoUse when case varies in the data
in, in~Equals any element of a listin yes, in~ noPair with a let list
has, has_csRight side is a whole term in the left sidehas no, has_cs yesUses the term index; first choice for words
has_any, has_allAny or all terms in a list are presentNoIndicator lists against command lines
hasprefix, hassuffixA term starts or ends with the valueNo (_cs forms exist)Partial terms such as file extensions
contains, contains_csSubstring anywherecontains no, contains_cs yesScans values; use only when has cannot work
startswith, endswithValue begins or ends with substringNo (_cs forms exist)Paths and domains
matches regexRegular expression matchYesSlowest; filter first, regex last
has_ipv4, has_ipv4_prefixIPv4 address or prefix present as a termNot applicableOptimised 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 kindReturnsTypical hunting use
innerunique (default)Matching rows after deduplicating the left side by keyRarely what you want; state the kind instead
innerAll matching rows from both sidesProcess event joined to its network events
leftouterAll left rows, with right columns where matchedEnrich sign-ins with optional context
leftantiLeft rows with no match on the rightNew since baseline: today minus last 14 days
leftsemiLeft rows that have a match, left columns onlyKeep only events for watchlisted accounts
fullouter, rightouter, rightanti, rightsemiMirror forms of the aboveReconciliation 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.

Sample 1
// 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 AccountName

4. Parsing and extraction

NeedUseExample
Field from a dynamic columnDot notation with tostring()tostring(DynamicCol.field)
JSON held in a stringparse_json(), then dot notationparse_json(AdditionalFields).DriveLetter
Delimited textparse (kind simple, regex or relaxed)parse Msg with * "user=" User " src=" Src
Rows that fail to parse not neededparse-whereDrops non-matching rows
Command line argumentsparse_command_line()Split a process command line into an array
File paths, versions, IP addressesparse_path(), parse_version(), parse_ipv4(), parse_ipv6()Compare versions or subnets reliably
Complex patternextract(), extract_all()Last resort: regular expressions are costly
Arrays to rowsmv-expandOne 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.

PatternTableATT&CK
Password spray from one sourceSigninLogsT1110.003 Password Spraying
Successful single-factor sign-ins from new countriesSigninLogsT1078.004 Cloud Accounts
Encoded PowerShellDeviceProcessEventsT1059.001 PowerShell
Office application spawning a shellDeviceProcessEventsT1059.001 PowerShell
Rare process on few devicesDeviceProcessEventsTriage aid, no single technique
Role assignment writes in AzureAzureActivityT1098.003 Additional Cloud Roles
Sample 1
// 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
Sample 1
// 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
Sample 1
// 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
Sample 1
// 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
Sample 1
// 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
Sample 1
// 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_d

Notes: 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

DoInstead ofWhy
Time filter on the table column firstFiltering after extend or joinReduces rows before expensive work
Filter on table columnsFiltering on calculated columnsTable columns can use indexes
has, has_cs, ==, incontains, =~, matches regexTerm index and case-sensitive matching are faster
project before joinJoining full rowsLess data moved and matched
Smaller table on the left of joinLarge table on the leftFewer records to match
search in (TableA, TableB) "value"Unscoped search or union *Limits the tables scanned
count or take while buildingRunning the full query firstAvoids large results and quota use
Specific columnsChecking 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

Related NHI Mgmt Group resources: KQL for Threat Hunting Guide, Microsoft Sentinel Guide, Sigma Rule Syntax Cheat Sheet, Identity Threat Hunting Guide.

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.