| Azure-Insights :👈 | 👉:Azure-Log-Analytics |
Kusto Query Language (KQL) Overview |
Kusto Query Language (KQL)
Kusto Query Language (KQL) is a powerful, read-only query language used to explore, analyze, and visualize large volumes of structured, semi-structured, and unstructured data in Azure services such as Log Analytics, Application Insights, and Azure Data Explorer.
π§ What is KQL?
Kusto Query Language (KQL) is a read-only, data exploration language used across Azure services like:
- Azure Monitor / Log Analytics
- Microsoft Sentinel
- Azure Data Explorer
- Microsoft Defender for Cloud
Origin of the name: Microsoft engineers named the project after famous French oceanographer Jacques Cousteau, symbolizing the ability to explore an ocean of data.
Kusto is a good name, but now it is only a nickname, Kustoβs official name is Azure Data Explorer or ADE. The short way to write ADE is ADX.
Kusto (Azure Data Explorer) does not convert KQL to SQL internally. Instead, its distributed query engine compiles KQL directly into native machine code using Just-In-Time (JIT) compilation and executes it across a cluster of compute nodes. (In fact, if you send a T-SQL query to Kusto, it actually translates the T-SQL into KQL under the hood.)
Where Kusto Is Executed
Kusto runs inside Azure Data Explorer (ADX) clusters, which also power backend analytics for services like Azure Monitor, Log Analytics, Microsoft Sentinel, and Microsoft Fabric.
- Compute Clusters. A Kusto cluster consists of distributed compute nodes (ranging from 2 to hundreds of Azure Virtual Machines).
- Decoupled Storage. Persistent data lives in Azure Blob Storage completely separate from the compute nodes. This allows compute power and storage capacity to scale independently.
- Hot Cache Tier. Frequently accessed data is cached directly in the RAM and local NVMe SSDs of the compute nodes so queries rarely have to wait on remote Blob Storage.
Core Architecture & Node Roles
Within a Kusto cluster, different node roles divide the work of managing metadata, routing queries, and crunching data:
- Admin Node. Manages cluster metadata, tracks schemas, and coordinates data ingestion and background maintenance.
- Gateway Node. Acts as the front door that authenticates incoming client requests and routes them into the cluster.
- Query Head Node. Receives the KQL query, parses it, builds the distributed execution plan, and merges final results from worker nodes.
- Data Nodes. Hold shards of cached data in memory/SSD and execute the heavy filtering, scanning, and aggregation in parallel.
How KQL Executes Internally (Step-by-Step)
Rather than translating to another high-level query language like SQL, Kusto compiles queries straight down to optimized execution plans and binary instructions:
- Parsing & AST Generation. The Query Head parses the KQL text into an Abstract Syntax Tree (AST).
- Relational Operator (RelOp) Tree. The AST is converted into a tree of relational operators (RelOp). The optimizer applies rules like predicate pushdown (pushing where filters as close to the raw data scan as possible) and partition pruning.
- Distributed Plan Creation. The Query Head splits the optimized tree into a distributed execution plan, deciding which fragments run locally on Data Nodes (e.g., partial aggregations) and which run on the Query Head (e.g., final sorting).
- JIT Compilation to Native Binary. Before scanning data, Kusto uses Just-In-Time (JIT) compilation to generate native binary machine code tailored specifically to the query's expressions and data types, avoiding slow interpreter overhead.
- Columnar Extent Scanning. Data in Kusto is stored in immutable, compressed, columnar shards called extents. Each extent includes inverted term indexes (for fast full-text search) and min/max metadata. Data Nodes scan only the relevant columns and extents in parallel, streaming results back to the Query Head
Itβs designed for fast, interactive analysis of large datasets β especially telemetry, logs, metrics, and time-series data β without modifying the underlying data.
β Why Use KQL
- Quickly identify trends and anomalies in large datasets.
- Supports monitoring, diagnostics, and troubleshooting in Azure.
- Enables custom dashboards and alerting rules.
- Ideal for multi-tenant SaaS telemetry and modular infrastructure analysis.
βοΈ Key Features
- Query data in Kusto is fast, way faster than the transitional RDBMS, such as SQL Server, MySQL, etc. Especially when the data size grows to billions of rows and continually grows in billion sizes.
- Optimized for fast data exploration and ad-hoc queries.
- Supports filtering, aggregation, joins, and advanced data transformations.
- Integrates with dashboards, workbooks, and alerts for real-time monitoring.
- Provides time-series analysis and pattern detection.
π Common KQL Operations
- Filtering: `where` clause to narrow down data.
- Projection: `project` to select specific columns.
- Aggregation: `summarize` to group and calculate metrics.
- Joining Data: `join` to combine tables.
- Sorting: `order by` to arrange results.
- Time Series Analysis: `make-series` and `bin()` for temporal aggregation.
π§© Example Query
Logs
| where TimeGenerated > ago(1h)
| where SeverityLevel == "Error"
| summarize ErrorCount = count() by Computer
| order by ErrorCount desc
π Core Concepts
| Concept | Description |
|---|---|
| Read-only | You can query and transform data, but not insert/update/delete. |
| Data-flow model | Queries are built as a sequence of operations connected by a pipe (|) β each step transforms the table before passing it on. |
| Schema hierarchy | Data is organized into databases β tables β columns (similar to SQL). |
| Case-sensitive | Table names, column names, and operators are case-sensitive. |
| Optimized for telemetry | Rich support for text search, parsing, time-series, aggregation, and anomaly detection. |
π Basic Syntax Structure
TableName
| where Timestamp > ago(1h)
| project ColumnA, ColumnB
| summarize Count = count() by ColumnA
| order by Count desc
How it works:
- Start with a table (TableName)
- Filter rows (
where) - Select columns (
project) - Aggregate data (
summarize) - Sort results (
order by)
π Common Operators
| Operator | Purpose | Example |
|---|---|---|
| where | Filter rows | where Level == "Error" |
| project | Select columns | project TimeGenerated, Message |
| summarize | Aggregate | summarize avg(DurationMs) by UserId |
| extend | Add calculated columns | extend LoadTimeSec = DurationMs / 1000 |
| join | Combine tables | join kind=inner |
| order by | Sort results | order by Count desc |
| parse | Extract values from text | parse Message with "User:" UserId " logged in" |
β‘ Example in Azure Monitor
Scenario: Find the top 5 IP addresses with the most failed logins in the last 24 hours.
SigninLogs
| where ResultType != 0
| where TimeGenerated > ago(24h)
| summarize Failures = count() by IPAddress
| top 5 by Failures desc
π― Best Practices for Writing KQL
- Filter early β Use
whereas soon as possible to reduce dataset size. - Project only needed columns β Avoid pulling unnecessary data.
- Use
summarizewisely β Aggregate before joins to reduce cost. - Parameterize queries in Workbooks for reusability.
- Test in small time windows before running large queries.
π Why Youβll Love It for Your Work
- Tag data with
TenantIdto filter dashboards per tenant. - Build modular KQL snippets for reuse in Workbooks, Alerts, and APIs.
- Integrate KQL queries into Angular dashboards via the Azure Monitor REST API for live telemetry.
KQL Cheat Sheet - Azure Monitor, Sentinel, Application Insights
π KQL Cheat Sheet
20+ ready-to-use query patterns for Azure Monitor, Microsoft Sentinel, and Application Insights.
1οΈβ£ Azure Monitor & Log Analytics Queries
-
Heartbeat | summarize Count = count() by ComputerList all monitored computers with heartbeat count.
-
Perf | where ObjectName == "Processor" and CounterName == "% Processor Time" | summarize AvgCPU = avg(CounterValue) by bin(TimeGenerated, 5m), ComputerAverage CPU usage per computer in 5-min bins.
-
AzureActivity | where ActivityStatus == "Failed" | project TimeGenerated, Caller, OperationName, ActivityStatusShow failed Azure operations.
-
SecurityEvent | where EventID == 4625 | summarize FailedLogins = count() by Account, bin(TimeGenerated, 1h)Failed login attempts per account per hour.
-
InsightsMetrics | where Name == "Requests" | summarize TotalRequests = sum(Val) by bin(TimeGenerated, 1h), ResourceTotal requests per resource per hour.
2οΈβ£ Microsoft Sentinel Queries
-
SigninLogs | where ResultType != 0 | summarize Failures = count() by UserPrincipalName, IPAddressFailed sign-ins by user and IP.
-
SecurityAlert | summarize Alerts = count() by AlertName, SeverityCount of alerts by name and severity.
-
SecurityIncident | where Status == "Active" | project IncidentNumber, Title, Severity, OwnerList active incidents with details.
-
OfficeActivity | where Operation == "FileAccessed" | summarize AccessCount = count() by UserId, Site_UrlFile access count by user and site.
-
DeviceNetworkEvents | where RemoteUrl contains "malicious.com" | project Timestamp, DeviceName, RemoteUrlDetect connections to malicious domains.
3οΈβ£ Application Insights Queries
-
requests | summarize AvgDuration = avg(duration) by bin(timestamp, 1h)Average request duration per hour.
-
requests | where success == "False" | summarize Failures = count() by nameFailed requests by operation name.
-
dependencies | summarize AvgDuration = avg(duration) by targetAverage dependency call duration by target.
-
traces | where message contains "Exception" | project timestamp, message, severityLevelList exception traces with severity.
-
pageViews | summarize Views = count() by namePage view count by page name.
4οΈβ£ Cross-Service / Advanced Patterns
-
union requests, dependencies | summarize TotalCalls = count() by bin(timestamp, 1h)Combine requests and dependencies for total calls per hour.
-
SigninLogs | join kind=inner (SecurityAlert) on $left.UserPrincipalName == $right.CompromisedEntity | project TimeGenerated, UserPrincipalName, AlertNameCorrelate sign-ins with security alerts.
-
Perf | where CounterName == "% Processor Time" | summarize AvgCPU = avg(CounterValue) by Computer | order by AvgCPU descTop CPU-consuming machines.
-
SecurityEvent | where EventID in (4720, 4722, 4723) | summarize Count = count() by EventID, AccountTrack account creation, enable, and password change events.
-
requests | extend DurationSec = todouble(duration)/1000 | summarize P95 = percentile(DurationSec, 95) by bin(timestamp, 1h)95th percentile request duration per hour.
-
Heartbeat | summarize LastSeen = max(TimeGenerated) by Computer | where LastSeen < ago(1h)Machines not reporting heartbeat in the last hour.
π‘ Tips for Using KQL Efficiently
- Filter early with
whereto reduce dataset size. - Use
projectto select only needed columns. - Aggregate with
summarizebefore joins for performance. - Parameterize queries in Workbooks for reusability.
- Test with small time windows before scaling up.
| Azure-Insights :👈 | 👉:Azure-Log-Analytics |