KQL Queries for Security Monitoring: Hunting and Detection in Sentinel and Defender
KQL, the Kusto Query Language, is how you search logs in Microsoft Sentinel and Defender XDR advanced hunting. This guide covers how a query is put together, the operators that do most of the work, worked queries for common attacker behaviour, and how to turn a hunting query into an analytics rule that doesn't flood the queue.
By the Security Monitoring Review editors · Updated
What KQL is
KQL is a read-only query language for large volumes of log and telemetry data. Microsoft built it for Azure Data Explorer (whose engine is called Kusto), and the same language runs in Azure Monitor Log Analytics, Microsoft Sentinel, Defender XDR advanced hunting and Microsoft Fabric. For a security team it is the language of every Sentinel analytics rule, hunting query and workbook.
A query starts with a table and passes rows through a chain of operators separated by pipes (|). Each step filters, reshapes or aggregates what the previous one returned, so a query reads top to bottom in the order it runs. Anyone who has written Splunk SPL will recognise the pattern; anyone who knows SQL will recognise most of the operations under different names.
Detections written in a vendor-neutral format such as Sigma can be converted into KQL, but most Sentinel and Defender content — Microsoft's own rules, community hunting queries, vendor solutions — is written in KQL directly, so reading it is a day-one skill.
Anatomy of a query
The query below looks for one IP address failing to sign in as many different accounts in Microsoft Entra ID — the shape of a password spray.
SigninLogs
| where TimeGenerated > ago(1d)
| where ResultType == "50126" // invalid username or password
| summarize
Attempts = count(),
TargetedUsers = dcount(UserPrincipalName),
FirstSeen = min(TimeGenerated),
LastSeen = max(TimeGenerated)
by IPAddress
| where TargetedUsers >= 10
| order by TargetedUsers desc- The table —
SigninLogsholds Entra ID interactive sign-ins. Every query starts by naming one (or aunionof several). - Time first —
TimeGenerated > ago(1d)limits the scan to the last day. Filtering on time before anything else is the single biggest factor in how fast a query runs. - Filters —
wherekeeps the rows that match.ResultTypeis the Entra error code as a string;0is success. - Aggregation —
summarizegroups rowsbyone or more columns and computes counts, distinct counts, minimums and other aggregates for each group. - Threshold and order — a second
whereafter the aggregation keeps only the groups worth looking at;order byputs the worst first.
Lines beginning with // are comments. Table and column names are case-sensitive: signinlogs will not work.
The operators that do most of the work
| Operator | What it does | Example |
|---|---|---|
where | Keeps rows that match a condition. | where EventID == 4625 |
project | Chooses, renames and orders columns. project-away drops columns instead. | project TimeGenerated, Computer, Account |
extend | Adds a calculated column. | extend Hour = hourofday(TimeGenerated) |
summarize | Aggregates rows into groups. | summarize count() by Computer |
bin() | Rounds time into buckets, for counts over time. | summarize count() by bin(TimeGenerated, 1h) |
join | Combines two tables on a shared column. The default kind de-duplicates the left side; say kind=inner when you mean it. | join kind=inner (DeviceInfo) on DeviceId |
union | Stacks rows from several tables. | union SecurityEvent, WindowsEvent |
let | Names a value, a list or a whole sub-query for reuse. | let lookback = 7d; |
top, take | top returns the first N by a column; take returns any N rows, for a quick look at a table. | top 20 by Attempts |
parse, extract() | Pull values out of free-text fields. | extend User = extract(@"user=(\S+)", 1, Message) |
mv-expand | Turns an array column into one row per element. | mv-expand Recipient = RecipientList |
render | Draws the result as a chart in the portal. | render timechart |
String comparisons trip people up more than anything else:
| Operator | Matches | Case |
|---|---|---|
== / =~ | The whole value. | == is case-sensitive, =~ is not. |
has | A whole term inside the value (terms are split on spaces and punctuation). | Insensitive. Uses the term index, so it is fast. |
contains | Any substring. | Insensitive. Scans every value, so it is slower. |
startswith, endswith | A prefix or suffix. | Insensitive; _cs versions are case-sensitive. |
in / in~ | Any value in a list. | in is case-sensitive, in~ is not. |
matches regex | A regular expression. | Sensitive unless the pattern says otherwise. The slowest; use it last. |
Prefer has over contains whenever you are matching a whole word, such as a process name or a command-line switch. Each has a negated form (!has, !contains, !in).
Security queries to adapt
Each query below targets a table that only exists if its data connector is enabled. Run TableName | take 10 first to confirm the table is there and to see its columns. In Sentinel, Defender XDR tables use TimeGenerated; in Defender's own advanced hunting the same column is called Timestamp.
A signed Windows binary used to download a file. certutil.exe with its URL-cache option is a common way to pull a payload onto a host. Matching the original file name as well catches a renamed copy.
DeviceProcessEvents
| where Timestamp > ago(7d)
| where FileName =~ "certutil.exe" or ProcessVersionInfoOriginalFileName =~ "CertUtil.exe"
| where ProcessCommandLine has "urlcache" and ProcessCommandLine has "http"
| project Timestamp, DeviceName, AccountName, ProcessCommandLine,
InitiatingProcessFileName, InitiatingProcessCommandLineAccounts added to privileged groups. Windows Security events 4728, 4732 and 4756 record a member added to a security-enabled global, local and universal group.
let privileged = dynamic(["Administrators", "Domain Admins", "Enterprise Admins", "Schema Admins"]);
SecurityEvent
| where TimeGenerated > ago(1d)
| where EventID in (4728, 4732, 4756)
| where TargetUserName in~ (privileged)
| project TimeGenerated, Computer, AddedBy = SubjectUserName, MemberName, Group = TargetUserNameA spraying IP that then got in. A let sub-query finds the IPs behind the password spray above; the main query looks for a successful sign-in from any of them.
let lookback = 1d;
let sprayIPs = SigninLogs
| where TimeGenerated > ago(lookback)
| where ResultType == "50126"
| summarize TargetedUsers = dcount(UserPrincipalName) by IPAddress
| where TargetedUsers >= 10
| project IPAddress;
SigninLogs
| where TimeGenerated > ago(lookback)
| where ResultType == "0"
| where IPAddress in (sprayIPs)
| project TimeGenerated, UserPrincipalName, IPAddress, AppDisplayName, LocationA change in volume. Counting events per hour and charting them is the quickest way to see whether a spike, or a gap, is worth investigating — a log source that suddenly stops sending is a monitoring failure in its own right.
SecurityEvent
| where TimeGenerated > ago(7d)
| where EventID == 4625 // failed logon
| summarize FailedLogons = count() by bin(TimeGenerated, 1h)
| render timechartThresholds such as >= 10 are starting points, not recommendations. The right number depends on your user count, your applications and how your network presents addresses (a shared egress IP or VPN can make one IP look like a spray); set it from your own data, as described below.
Writing queries that run fast
- Filter on time first, then on the most selective column, before any
extend,parseorjoin. - Use `has` and `==` rather than
containsandmatches regexwherever the match allows it. - `project` early in long queries so later steps carry only the columns they need.
- Put the smaller table on the left of a `join`, and filter both sides before joining.
- **Avoid
search *andunion *** outside quick exploration; they scan every table in the workspace. - Aggregate before you sort or render.
summarizefirst shrinks the data everything after it has to handle.
Queries also have limits on run time, result size and memory, and these differ between Log Analytics, advanced hunting and Azure Data Explorer. Microsoft's query best-practices pages for each product list the current values.
From hunting query to analytics rule
A query becomes a detection when it runs on a schedule and raises an alert when it returns rows. In Microsoft Sentinel that is a scheduled analytics rule; in Defender XDR, a custom detection rule created from advanced hunting.
- Query frequency and lookback. A Sentinel scheduled rule runs every so often over a window of data. Make the lookback at least as long as the frequency, or events fall between runs; ingestion delay means a small overlap is safer still.
- Alert threshold. The rule fires when the result count passes a threshold — usually more than zero, with the real threshold written into the query itself.
- Entity mapping. Map columns such as
UserPrincipalName,IPAddress,DeviceNameand file hashes to Sentinel entities so alerts can be grouped into incidents and investigated across tables. - Alert and incident grouping. Grouping related alerts into one incident by entity stops a single spray from opening a hundred tickets.
- Required columns in Defender. Custom detections in Defender XDR need specific columns in the result (a time column and identifiers for the event and the affected entity). Microsoft's custom detection documentation lists exactly which.
Keep rule queries in source control and deploy them as code — Sentinel rules can be exported and deployed as ARM or Bicep templates or through Sentinel's repositories feature. Our piece on detection-as-code workflows covers the pipeline around them.
Keeping KQL detections quiet
Most noisy Sentinel deployments got that way by enabling rule templates unchanged. A rule written for every tenant knows nothing about yours: your service accounts, your admin tooling, your VPN ranges. These habits keep KQL rules from adding to the queue that alert triage has to work through:
- Backtest before enabling. Run the query over as much history as your workspace retains (30 days where you have it) with the threshold removed, and look at what would have fired. If most of it is legitimate, tune before anyone is paged.
- Set thresholds from the data. Use
summarizewithpercentile()ormake-seriesto see the normal range of a count per user, host or IP, and set the threshold above it rather than guessing. - Keep exclusions in watchlists. Store approved admin hosts, scanner IPs and service accounts in a Sentinel watchlist and exclude them with
_GetWatchlist('alias'), so tuning one rule never means editing its logic and the list is reused across rules. - Exclude by stable identifiers. Filter on an account's object ID, a device ID or a signer rather than a display name or path an attacker can copy.
- Close known-benign patterns automatically. Sentinel automation rules can close or suppress incidents that match a known-benign pattern, but prefer fixing the query: an automation rule hides the noise without removing its cost.
- Review rules by outcome. Track each rule's incident count and how often it is closed as benign or false positive; rewrite or retire the worst offenders on a schedule.
let approvedAdmins = _GetWatchlist('ApprovedAdminHosts') | project SearchKey;
DeviceProcessEvents
| where TimeGenerated > ago(1h)
| where FileName =~ "psexec.exe" or ProcessVersionInfoOriginalFileName =~ "psexec.c"
| where DeviceName !in (approvedAdmins)String matches on a command line are easy to sidestep with a different flag, path or encoding; our piece on why rule-based SIEM detection fails against modern TTPs covers where that breaks down. Where you can, key KQL rules to behaviour — parent and child processes, original file names, sequences of events joined by user or host — rather than single strings.
Where to find queries and documentation
- KQL documentation — the language reference for every operator and function.
- Azure/Azure-Sentinel — Microsoft's repository of Sentinel analytics rules, hunting queries, workbooks and solutions, including community contributions. Defender XDR hunting queries are kept there too.
- The schema reference for Sentinel tables and for Defender XDR advanced hunting tables, on Microsoft Learn — the authority on which columns each table has.
- The Azure Data Explorer help cluster — a free cluster with sample databases for practising the language without a Sentinel workspace.
- Kusto Detective Agency — Microsoft's free set of KQL puzzles, a practical way to learn joins, parsing and time-series functions.
- Rule templates from vendors and the community are a starting point: check each one's table, columns and thresholds against your own data before enabling it.
Common questions
Is KQL the same as SQL? No, though it covers the same ground: filtering, grouping, joining. KQL is read-only and pipe-based, written in the order it runs. Azure Data Explorer accepts a subset of T-SQL and its explain command translates SQL to KQL, which helps when learning.
How does KQL compare with Splunk SPL? Both chain commands with pipes. where, summarize ... by and project play the roles of SPL's where/search, stats ... by and table/fields. Microsoft publishes a Splunk-to-KQL mapping for teams migrating rules.
Is KQL case-sensitive? Table names, column names, functions and == are. has, contains, =~ and in~ are not.
Does a query cost money to run? Interactive queries on data in the standard Analytics tier are generally included in what you pay to ingest and retain it, but data kept in cheaper tiers (Basic and Auxiliary logs, or long-term archive) can be billed per query or per search. Check the current Azure Monitor and Sentinel pricing pages for your region and plan.
Can I write a rule once for Sentinel and other SIEMs? Write it in Sigma and convert it with a pySigma Kusto backend, then review the output: field mappings for your tables decide whether the converted query matches anything.
More on this in Detection Engineering and Legacy Monitoring.
More guides
- Sigma Rules: A Practical Guide to Writing Detections That Don't Drown the SOCWhat Sigma rules are, how one is built field by field, how to convert it to your SIEM's query language, and how to keep it from becoming another noisy alert.
- YARA Rules: How to Write, Run and Tune File and Memory DetectionsWhat YARA rules are, how one is built from strings and a condition, how to run them across endpoints and files, and how to keep them from flooding the SOC.