KQL (Kusto Query Language) Formatter

For SOC analysts and platform engineers handed a detection flattened onto one line by an alert rule, a workbook or a chat message. Each pipeline step gets its own line, and tenant names, IP addresses and account IDs in the query stay in this tab.

Input

Settings

History

Load from URL

What gets formatted

KQL is the query language behind Azure Data Explorer, Azure Monitor Log Analytics and Application Insights, Microsoft Sentinel, Defender XDR advanced hunting and Real-Time Intelligence in Microsoft Fabric. A query is a pipeline: a table, then tabular operators joined by |.

PasteKit uses a built-in KQL tokenizer and printer. It starts each tabular operator (where, extend, summarize, project, join, order by, render and the rest) on its own indented line beginning with the pipe, and normalises the spacing around operators, commas and = in assignments. Long summarize and project lists break to one item per line. let statements stay as separate statements ending in ;, and the subquery inside a join is indented so you can see where it begins and ends.

String literals (including verbatim @"..." and obfuscated h"..." strings), datetime() and timespan literals such as 7d, and // comments are left exactly as written. Management commands such as .show tables are printed as they are.

Blank lines, width and shortcuts

Blank lines between statements are preserved on purpose. Log Analytics and Kusto Explorer treat a blank line as the boundary between queries, so removing one would merge two queries and adding one would split a query in half. If you see a query run only partway in the portal, look for a stray blank line above the |.

KQL has no special options here. The toolbar’s indent and line width control how subqueries are indented and when a list wraps. Press Ctrl/Cmd+Enter to format and Ctrl/Cmd+Shift+C to copy the query for the Azure portal or Kusto Explorer. Ctrl/Cmd+K lists other commands. Minify does not apply to KQL.

If a query cannot be tokenised, the problem is shown with its line and column instead of formatted output. The formatter has no connection to your workspace, so unknown tables, columns and functions only surface when the query runs.

Language traps worth checking in the output

One step per line makes a few expensive or surprising choices easy to spot:

  • join without kind= defaults to innerunique, which keeps one arbitrary row per key from the left side before matching. In a detection that silently drops events, so write kind=inner unless you want that behaviour.
  • has versus contains. has matches whole terms using the term index, while contains scans for substrings and is much slower. Only terms of three characters or more are indexed, so has "ab" scans as well.
  • has is term-based, so "KustoExplorerQueryRun" has "Explorer" is false.
  • == is case-sensitive; =~ is the case-insensitive comparison.
  • take returns arbitrary rows. Use top or order by when order matters.
  • Filter on the time column first so the engine can skip data.
  • Put the smaller table on the left of a join, which Microsoft recommends for performance.

Detections as code

Version control is where formatted KQL pays off most. Sentinel content in Git, Defender custom detections and Azure Data Explorer functions deployed by pipeline all produce readable diffs when every operator sits on its own line. A changed threshold shows up as one changed line rather than a rewritten 400-character string, and a reviewer can check the filter without reconstructing the query in their head.

The SQL formatter covers T-SQL, which Azure Data Explorer also accepts for simple queries, and the log parser helps when the raw events are what you need to read.

Examples

Sentinel: password spray from one IP

The summarize list breaks one aggregation per line with the by clause beneath it, so the aggregation and the threshold filter after it read as separate decisions.

Input
SigninLogs | where TimeGenerated > ago(1d) | where ResultType in ("50126","50053") | summarize FailedAttempts=count(), TargetAccounts=dcount(UserPrincipalName), Accounts=make_set(UserPrincipalName,25) by IPAddress, bin(TimeGenerated,1h) | where TargetAccounts >= 10 | order by TargetAccounts desc
Output
SigninLogs
  | where TimeGenerated > ago(1d)
  | where ResultType in ("50126", "50053")
  | summarize
    FailedAttempts = count(),
    TargetAccounts = dcount(UserPrincipalName),
    Accounts = make_set(UserPrincipalName, 25)
    by IPAddress, bin(TimeGenerated, 1h)
  | where TargetAccounts >= 10
  | order by TargetAccounts desc
Open this example in the tool

Application Insights: slowest endpoints

A typical performance query. Assignments and comparisons get consistent spacing and render stays as the final pipeline step.

Input
requests | where timestamp > ago(24h) | summarize p95=percentile(duration,95), failures=countif(success==false), total=count() by name, bin(timestamp,1h) | extend failureRate=round(100.0 * failures / total,2) | where total>50 | order by p95 desc | render timechart
Output
requests
  | where timestamp > ago(24h)
  | summarize
    p95 = percentile(duration, 95),
    failures = countif(success == false),
    total = count()
    by name, bin(timestamp, 1h)
  | extend failureRate = round(100.0 * failures / total, 2)
  | where total > 50
  | order by p95 desc
  | render timechart
Open this example in the tool

Defender: encoded PowerShell followed by network traffic

The let statement ends in a semicolon on its own block, the join keeps kind=inner beside the operator, and the subquery is indented between its parentheses.

Input
let encoded=DeviceProcessEvents | where Timestamp>ago(7d) | where FileName=~"powershell.exe" and ProcessCommandLine has_any ("-enc","-EncodedCommand","FromBase64String") | project DeviceId, DeviceName, ProcTime=Timestamp, ProcessCommandLine, InitiatingProcessFileName; encoded | join kind=inner (DeviceNetworkEvents | where Timestamp>ago(7d) | where RemoteIPType=="Public" | project DeviceId, NetTime=Timestamp, RemoteIP, RemoteUrl) on DeviceId | where NetTime between (ProcTime .. (ProcTime+5m)) | summarize Urls=make_set(RemoteUrl,20), Connections=count() by DeviceName, ProcessCommandLine
Output
let encoded = DeviceProcessEvents
  | where Timestamp > ago(7d)
  | where FileName =~ "powershell.exe"
    and ProcessCommandLine has_any (
      "-enc",
      "-EncodedCommand",
      "FromBase64String"
    )
  | project
    DeviceId,
    DeviceName,
    ProcTime = Timestamp,
    ProcessCommandLine,
    InitiatingProcessFileName;
encoded
  | join kind=inner (
    DeviceNetworkEvents
      | where Timestamp > ago(7d)
      | where RemoteIPType == "Public"
      | project DeviceId, NetTime = Timestamp, RemoteIP, RemoteUrl
  ) on DeviceId
  | where NetTime between (ProcTime .. (ProcTime + 5m))
  | summarize
    Urls = make_set(RemoteUrl, 20),
    Connections = count()
    by DeviceName, ProcessCommandLine
Open this example in the tool

Entra audit: who added a role member

Each extended column takes a line. Array indexes and dotted paths into dynamic columns stay glued together, including the nested parse_json call.

Input
AuditLogs | where TimeGenerated > ago(7d) and OperationName == "Add member to role" | extend Actor=tostring(InitiatedBy.user.userPrincipalName), Target=tostring(TargetResources[0].userPrincipalName), Role=tostring(parse_json(tostring(TargetResources[0].modifiedProperties))[1].newValue) | project TimeGenerated, Actor, Target, Role, Result | sort by TimeGenerated desc
Output
AuditLogs
  | where TimeGenerated > ago(7d) and OperationName == "Add member to role"
  | extend
    Actor = tostring(InitiatedBy.user.userPrincipalName),
    Target = tostring(TargetResources[0].userPrincipalName),
    Role = tostring(
      parse_json(tostring(TargetResources[0].modifiedProperties))[1].newValue
    )
  | project TimeGenerated, Actor, Target, Role, Result
  | sort by TimeGenerated desc
Open this example in the tool

Common errors and how to fix them

ErrorCauseFix
This string is never closed before the end of the lineA string started with " or ’ and was not closed on the same line, often because a Windows path or JSON fragment contains a quote.Close the quote. For backslashes use a verbatim string, @“C:\temp”, and for text that spans lines use a ``` block.
This '(' is never closedA function call, a join subquery or a between (a … b) range is missing its closing parenthesis.The position points at the opening bracket with no partner. Join subqueries are the usual place to lose one.
Expected ')' to close the '(' opened earlier, but found ']'Brackets of different kinds cross over, which tends to happen when editing an index such as TargetResources[0] inside a nested call.Check the brackets between the reported position and the opening one, then close the inner one first.
Formats fine, but Log Analytics reports a syntax error right after a let statementThe let statement is missing its terminating semicolon. The formatter only tokenises, so this reaches the service.Add ; after each let, then run the query again.
Semantic error: 'where' operator: Failed to resolve scalar expression named 'Type'Reported by the Kusto service, not by this page. The column does not exist at that point in the pipeline, often because an earlier project removed or renamed it.Read the formatted pipeline upwards from the failing line and find the last step that still produces the column. Defender advanced hunting uses Timestamp where Sentinel tables use TimeGenerated, a common cause when a query moves between the two.

Frequently asked questions

Does this work for Microsoft Sentinel and Defender queries?

Yes. Sentinel analytics rules, hunting queries and Defender XDR advanced hunting all use KQL, so they format the same way.

Does the formatter validate table and column names?

No. It has no connection to your cluster or workspace, so schema errors are only caught when the query runs.

Why does my KQL query only run partway in Log Analytics?

A blank line inside the query splits it in two, and the editor runs only the block your cursor is in. Remove blank lines between pipeline steps; this formatter keeps whatever blank lines you had.

Why does a KQL join return fewer rows than I expected?

The default join kind, innerunique, removes duplicate keys from the left side before matching. Use kind=inner when every left-side row matters.

Will it change string contents or comments?

No. Strings, verbatim strings and // comments are kept exactly as written.

What is the difference between KQL and SQL?

KQL is a read-only pipeline language: data flows left to right through operators joined by |. SQL describes the result in one declarative statement.

Related tools