Kusto Query Language (KQL) is the language you use to search, filter and summarize security data in Microsoft Sentinel. This KQL tutorial for Microsoft Sentinel takes you from your first query to a working detection: you will read sign-in and Windows logs, spot a password spray, chain two queries together with a join and turn the result into an analytics rule. Every query here is written for defenders and uses real Sentinel table and column names.
You do not need a paid workspace to follow along. Microsoft provides free practice environments, which we cover first. If you would rather learn with an instructor and hands-on labs, our Microsoft Sentinel training covers KQL, analytics rules, hunting and SC-200 preparation in live classes.
Key takeaways
- KQL queries read top to bottom: a table name, then operators joined by the pipe character, each one reshaping the rows it receives.
- Filter on time first, prefer
hasovercontains, and finish exploratory queries withtakeorcount. - The default
joinkind isinnerunique, which removes duplicate keys on the left side; setkind=innerwhen you need every match. - Sentinel tables use
TimeGenerated; Defender XDR tables in advanced hunting useTimestamp. - Microsoft Sentinel now runs in the Microsoft Defender portal, and support in the Azure portal ends after March 31, 2027.
What is KQL and why does Microsoft Sentinel use it?
KQL is a read-only query language built for large volumes of log and telemetry data. A query never changes the data it reads, which makes it safe to experiment with. Microsoft uses the same language across Microsoft Sentinel, Microsoft Defender XDR advanced hunting, Azure Monitor Log Analytics and Azure Data Explorer, so the skill carries over between products.
In Sentinel you use KQL in three main places: hunting queries that look for threats your rules missed, analytics rules that raise alerts and incidents, and workbooks that chart activity over time. Microsoft’s own overview describes KQL as easy to read and notes that a small set of introductory operators covers most everyday queries, which is good news for beginners.
Where you run KQL in Sentinel today
Microsoft has moved Sentinel into the unified security operations experience in the Microsoft Defender portal. The Logs page you may remember from the Azure portal corresponds to Advanced hunting (under Investigation and response) in the Defender portal, where one query editor covers Sentinel tables, Defender XDR tables and the Sentinel data lake. Microsoft states that after March 31, 2027, Sentinel will no longer be supported in the Azure portal, so new learners should practise in the Defender portal.
Free places to practise KQL
| Environment | What you get | Limits |
|---|---|---|
| Azure Data Explorer help cluster | The Samples database with tables such as StormEvents; no Azure subscription required | Weather and sample data, not security logs |
| Log Analytics demo environment | A demo workspace with Azure Monitor tables, no subscription required | You cannot save queries or create alerts |
| Microsoft Sentinel trial | Your own workspace with free ingestion for a trial period on eligible workspaces | Check Microsoft’s current billing page for the trial terms |
Start with the help cluster to learn the operators, then move to a Sentinel trial workspace when you want to query real sign-in and security events.
How a KQL query is built
Every query starts with a data source, usually a table, followed by operators separated by the pipe character |. The output of each step becomes the input of the next, so the order of operators matters. Here is the shape of almost every hunting query you will write:
SigninLogs
| where TimeGenerated > ago(1d)
| where ResultType != "0"
| project TimeGenerated, UserPrincipalName, IPAddress, AppDisplayName, ResultType
| take 20 Read it line by line. SigninLogs holds Microsoft Entra ID sign-ins. The first where keeps the last 24 hours, the second keeps failed sign-ins (in this table ResultType is a string, and "0" means success). project chooses the columns to show, and take returns a sample of 20 rows. Note that take and limit are the same operator, and neither promises which rows you get unless you sort first.
The operators you will use most
| Operator | What it does | Example |
|---|---|---|
where | Filters rows | where EventID == 4625 |
project | Selects, renames or orders columns | project TimeGenerated, Account |
extend | Adds a calculated column | extend Hour = hourofday(TimeGenerated) |
summarize | Aggregates rows into groups | summarize count() by IPAddress |
sort by / order by | Sorts rows, descending by default | sort by Attempts desc |
top | Sorts and keeps the first N rows | top 10 by Failures |
join | Combines two tables on a key | join kind=inner (T2) on UserPrincipalName |
union | Stacks rows from several tables | union SigninLogs, AADNonInteractiveUserSignInLogs |
let | Names a value or a subquery for reuse | let threshold = 10; |
has vs contains: the first performance lesson
has matches whole terms, while contains matches any substring. KQL indexes terms (runs of letters and digits of three or more characters), so has can use the index and is faster. The trade-off is precision: a value like KustoExplorerQueryRun does not match has "Explorer" because “Explorer” is not a separate term, but it does match contains "Explorer". Both operators ignore case; add the _cs suffix when you need a case-sensitive match.
Hands-on: hunt for a password spray in sign-in logs
In a password spray, an attacker tries one or two common passwords against many accounts to avoid lockouts. In sign-in data this often appears as one IP address failing against many different users. Error code 50126 in Microsoft Entra ID means an invalid username or password, so it is a good place to start:
SigninLogs
| where TimeGenerated > ago(1h)
| where ResultType == "50126"
| summarize FailedUsers = dcount(UserPrincipalName), Attempts = count() by IPAddress
| where FailedUsers >= 10
| sort by FailedUsers desc The summarize line groups failures by source IP, counts the attempts and estimates how many distinct users were targeted. Keep in mind that dcount() returns an estimate: it trades a little accuracy for speed, which is fine for hunting but worth mentioning in an incident report. The threshold of 10 is a starting point; tune it to your environment after looking at normal traffic.
See the pattern over time
A chart often tells you more than a table. This query counts failed sign-ins per hour across a week and draws a time chart:
SigninLogs
| where TimeGenerated > ago(7d)
| summarize Failures = countif(ResultType != "0") by bin(TimeGenerated, 1h)
| render timechart bin() rounds each timestamp down to the hour so rows fall into hourly buckets. Spikes outside business hours, or a sudden jump from a quiet baseline, are worth a closer look.
Correlate events with let and join
A spray only matters if it works. The next query looks for accounts that failed several times from an IP address and then signed in successfully from that same address within the hour:
let failures = SigninLogs
| where TimeGenerated > ago(1h)
| where ResultType == "50126"
| summarize FailedCount = count() by UserPrincipalName, IPAddress
| where FailedCount >= 5;
let successes = SigninLogs
| where TimeGenerated > ago(1h)
| where ResultType == "0"
| project SuccessTime = TimeGenerated, UserPrincipalName, IPAddress, AppDisplayName;
failures
| join kind=inner (successes) on UserPrincipalName, IPAddress
| project UserPrincipalName, IPAddress, FailedCount, SuccessTime, AppDisplayName Two details trip up beginners. First, every let statement must end with a semicolon. Second, if you leave out kind=, KQL uses innerunique, which keeps only one row per key from the left table. That is rarely what you want in an investigation, so state kind=inner explicitly. Microsoft’s best practices also suggest putting the smaller table on the left side of a join.
A hit here is a lead, not proof of compromise: users mistype passwords too. Check the IP reputation, the location, whether the user passed MFA and what they did after signing in.
Query Windows security events
If you collect Windows Security events into Sentinel, they land in the SecurityEvent table. Event ID 4625 records a failed logon, and 4624 a successful one. This query lists the accounts with the most failures in the last day:
SecurityEvent
| where TimeGenerated > ago(1d)
| where EventID == 4625
| summarize Failures = count() by Account, Computer, IpAddress
| top 10 by Failures Add LogonType to the by clause to separate network logons (type 3) from Remote Desktop logons (type 10). That one change often explains whether failures come from a misconfigured service or from someone trying RDP.
Hunt process activity with Defender XDR tables
When Microsoft Defender for Endpoint data is available in advanced hunting, the DeviceProcessEvents table shows process launches. In the Defender portal these tables use a Timestamp column rather than TimeGenerated, and Defender XDR data is kept for 30 days in advanced hunting by default. This query looks for PowerShell started with an encoded command, a technique that attackers use to hide script content and that defenders routinely review:
DeviceProcessEvents
| where Timestamp > ago(7d)
| where FileName =~ "powershell.exe"
| where ProcessCommandLine has "EncodedCommand"
| project Timestamp, DeviceName, AccountName, InitiatingProcessFileName, ProcessCommandLine
| sort by Timestamp desc The =~ operator is a case-insensitive equals. Treat the results as a hunting list: administrators and management tools also use encoded commands, so review the parent process in InitiatingProcessFileName before you escalate.
Use watchlists to add business context
Watchlists let you upload lists such as VIP users, admin accounts or known partner IP ranges and use them in queries with the _GetWatchlist() function. Matching on the SearchKey column gives the best performance:
let vip = _GetWatchlist('VIPUsers') | project SearchKey;
SigninLogs
| where TimeGenerated > ago(1d)
| where UserPrincipalName in (vip)
| where ResultType != "0"
| project TimeGenerated, UserPrincipalName, IPAddress, ResultType Replace VIPUsers with your own watchlist alias. You can list the aliases in a workspace with _GetWatchlistAlias.
Turn a hunting query into a detection
Once a query reliably finds something worth investigating, promote it to a rule so it runs on a schedule. Sentinel gives you several options:
- Scheduled analytics rules run on a frequency and look back over a period you choose, each between 5 minutes and 14 days, and the frequency cannot be longer than the lookback. A rule can produce up to 150 alerts per run.
- Near-real-time (NRT) rules run every minute for urgent detections, with tighter limits on the number of rules and alerts.
- Custom detection rules in the Defender portal work across Sentinel and Defender XDR data, and Microsoft now recommends them for new rules. The service applies the lookback window for you, and the query must return a time column plus the identifier columns the rule needs.
Whichever type you choose, map entities such as accounts, hosts and IP addresses so incidents link related alerts, and test the query against a week of data to estimate how noisy it will be. Microsoft’s scheduled rule documentation also blocks broad patterns such as search * and union * in rule queries.
KQL best practices for faster, cleaner queries
- Put the time filter immediately after the table name.
- Prefer
hasovercontains, and case-sensitive==over=~when you know the exact value. - Filter early and project only the columns you need before a
joinorsummarize. - Use
materialize()for aletsubquery that you reference more than once. - Finish exploratory queries with
takeorcountso you do not pull millions of rows. - Comment your queries with
//so teammates know why each filter exists.
KQL is a core skill for analysts, and it shows up in many interviews for SOC roles. For broader preparation, see our SOC analyst interview questions, and if your environment also uses Okta or Entra ID for sign-in, our Okta vs Azure AD comparison explains how the two identity platforms differ. You can browse every live program on the Tutorials Mania courses page.
Learn Microsoft Sentinel with live, instructor-led training
Our Microsoft Sentinel course covers data connectors, KQL, analytics rules, incident investigation, threat hunting, workbooks and automation playbooks in live online classes. It is mapped to the SC-200 Microsoft Security Operations Analyst exam, with hands-on labs and certification guidance.
Frequently asked questions
Is KQL hard to learn?
No. KQL reads in a natural top to bottom order, and a handful of operators (where, project, extend, summarize, sort and join) cover most daily work. The harder part is knowing your data: which table holds which events and what normal activity looks like.
Is KQL similar to SQL?
The ideas are similar, but the syntax flows differently: KQL starts with the table and pipes data through operators. Microsoft publishes a SQL to KQL cheat sheet, and Azure Data Explorer can translate a SQL query into KQL when you add a line containing -- and a line containing explain above it.
Can I practise KQL for free?
Yes. The Azure Data Explorer help cluster and the Log Analytics demo environment both work without an Azure subscription. For security data, a Microsoft Sentinel trial workspace lets you connect free sources such as Azure Activity logs and Office 365 audit logs.
Is KQL on the SC-200 exam?
Yes. The SC-200 Microsoft Security Operations Analyst study guide lists identifying threats with KQL under threat hunting, along with creating KQL jobs in the Sentinel data lake. Check the current study guide before you book, because Microsoft updates the skills outline regularly.
What is the difference between TimeGenerated and Timestamp?
Sentinel and Azure Monitor tables use TimeGenerated. Defender XDR tables in advanced hunting use Timestamp. When Defender data is streamed into Sentinel the two values can differ, and Microsoft advises relying on Timestamp for the time the event actually happened.
Sources
- Kusto Query Language in Microsoft Sentinel, Microsoft Learn
- Microsoft Sentinel in the Microsoft Defender portal, Microsoft Learn
- Best practices for KQL queries, Microsoft Learn
- join operator and string operators, Microsoft Learn
- SigninLogs table reference, Microsoft Learn
- Microsoft Entra authentication and authorization error codes, Microsoft Learn
- DeviceProcessEvents table, Microsoft Learn
- Scheduled analytics rules in Microsoft Sentinel, Microsoft Learn
- Create and manage custom detection rules, Microsoft Learn
- Build queries or rules with watchlists, Microsoft Learn
- Study guide for Exam SC-200, Microsoft Learn