Azure Data Explorer and KQL Interview Questions and Answers Part 4 - Time Series and Analytics

Azure Data Explorer Interview Q&A · Part 4 of 10

In this post we are going to cover time series and analytics in KQL. These are 7 real Azure Data Explorer and KQL interview questions for data engineers, asked the way they come up on a real project, and the last one is a scenario: operations wants an alert when a sensor's readings drop far below its normal pattern.

This is where KQL goes beyond counting rows: filling the empty hours in a chart, finding anomalies, running totals, sessions, fast estimates over huge tables, and turning messy text into typed columns. Interviewers ask about it because these are the questions real dashboards and alerts depend on, and each one has a detail that trips people up.

Part 4 of the Real Time Azure Data Explorer and KQL Interview Questions and Answers series on TechBrothersIT.

The short answer

Say this first

make-series gives every time bin a value, with a default for empty bins, and series_decompose_anomalies flags points far from the seasonal baseline. Window functions such as prev and row_cumsum need a sorted row set. percentiles and dcount are fast estimates with documented error, and parse and parse_json turn messy text into typed columns.

Let's create some sample data

Every query in this post runs on the Kusto emulator, Microsoft's Azure Data Explorer engine in a local container, in a database called shop. The data is small and invented: requests.csv, 18 web requests, and sensor.csv, hourly readings for two sensors over four days, loaded with .ingest into, plus DailySales, Clicks, Logs and Events loaded with .ingest inline. Both are for exploration and prototyping, not production. kql is a small helper that sends a query to the emulator and prints the result as a text table. What only Azure can show, such as the scheduled alert, is shown as code.

requests.csv
Timestamp,Level,Service,CustomerId,DurationMs,Message
2026-10-20T08:05:00Z,Info,checkout,C001,120,order placed
2026-10-20T08:12:00Z,Error,payments,C002,3050,db-timeout while charging card
2026-10-20T08:20:00Z,Info,catalog,C003,45,search ok
2026-10-20T08:41:00Z,Warning,checkout,C001,900,slow response from payments.api
2026-10-20T08:55:00Z,Error,checkout,C004,1500,Error: payment declined
2026-10-20T09:02:00Z,Info,catalog,C002,50,search ok
2026-10-20T09:10:00Z,Error,payments,C002,3010,db-timeout while charging card
2026-10-20T09:15:00Z,Info,checkout,C005,130,order placed
2026-10-20T09:31:00Z,Error,payments,C001,2900,ERROR connecting to db.primary
2026-10-20T09:47:00Z,Info,catalog,C003,40,search ok
2026-10-20T11:03:00Z,Info,checkout,C003,110,order placed
2026-10-20T11:09:00Z,Error,checkout,C002,1700,user error: invalid coupon
2026-10-20T11:20:00Z,Warning,catalog,C005,700,cache miss
2026-10-20T11:44:00Z,Error,payments,C004,3100,err code 42 from gateway
2026-10-20T11:58:00Z,Info,payments,C005,200,refund issued
2026-10-20T12:06:00Z,Error,payments,C002,2950,db-timeout while charging card
2026-10-20T12:30:00Z,Info,checkout,C001,125,order placed
2026-10-20T12:52:00Z,Info,catalog,C004,48,search ok
sensor.csv
S1,2026-10-17T00:00:00Z,19.70
S1,2026-10-17T01:00:00Z,21.59
S1,2026-10-17T02:00:00Z,22.20
S1,2026-10-17T03:00:00Z,23.84
S1,2026-10-17T04:00:00Z,24.03
S1,2026-10-17T05:00:00Z,25.13
S1,2026-10-17T06:00:00Z,24.70
S1,2026-10-17T07:00:00Z,25.13
S1,2026-10-17T08:00:00Z,24.03
S1,2026-10-17T09:00:00Z,23.84
S1,2026-10-17T10:00:00Z,22.20
S1,2026-10-17T11:00:00Z,21.59
S1,2026-10-17T12:00:00Z,19.70
S1,2026-10-17T13:00:00Z,19.01
S1,2026-10-17T14:00:00Z,17.20
S1,2026-10-17T15:00:00Z,16.76
S1,2026-10-17T16:00:00Z,15.37
S1,2026-10-17T17:00:00Z,15.47
S1,2026-10-17T18:00:00Z,14.70
S1,2026-10-17T19:00:00Z,15.47
S1,2026-10-17T20:00:00Z,15.37
S1,2026-10-17T21:00:00Z,16.76
S1,2026-10-17T22:00:00Z,17.20
S1,2026-10-17T23:00:00Z,19.01
S1,2026-10-18T00:00:00Z,19.70
S1,2026-10-18T01:00:00Z,21.59
S1,2026-10-18T02:00:00Z,22.20
S1,2026-10-18T03:00:00Z,23.84
S1,2026-10-18T04:00:00Z,24.03
S1,2026-10-18T05:00:00Z,25.13
S1,2026-10-18T06:00:00Z,24.70
S1,2026-10-18T07:00:00Z,25.13
S1,2026-10-18T08:00:00Z,24.03
S1,2026-10-18T09:00:00Z,23.84
S1,2026-10-18T10:00:00Z,22.20
S1,2026-10-18T11:00:00Z,21.59
S1,2026-10-18T12:00:00Z,19.70
S1,2026-10-18T13:00:00Z,19.01
S1,2026-10-18T14:00:00Z,17.20
S1,2026-10-18T15:00:00Z,16.76
S1,2026-10-18T16:00:00Z,15.37
S1,2026-10-18T17:00:00Z,15.47
S1,2026-10-18T18:00:00Z,14.70
S1,2026-10-18T19:00:00Z,15.47
S1,2026-10-18T20:00:00Z,15.37
S1,2026-10-18T21:00:00Z,16.76
S1,2026-10-18T22:00:00Z,17.20
S1,2026-10-18T23:00:00Z,19.01
S1,2026-10-19T00:00:00Z,19.70
S1,2026-10-19T01:00:00Z,21.59
S1,2026-10-19T02:00:00Z,22.20
S1,2026-10-19T03:00:00Z,23.84
S1,2026-10-19T04:00:00Z,24.03
S1,2026-10-19T05:00:00Z,25.13
S1,2026-10-19T09:00:00Z,23.84
S1,2026-10-19T10:00:00Z,22.20
S1,2026-10-19T11:00:00Z,21.59
S1,2026-10-19T12:00:00Z,19.70
S1,2026-10-19T13:00:00Z,19.01
S1,2026-10-19T14:00:00Z,17.20
S1,2026-10-19T15:00:00Z,16.76
S1,2026-10-19T16:00:00Z,15.37
S1,2026-10-19T17:00:00Z,15.47
S1,2026-10-19T18:00:00Z,14.70
S1,2026-10-19T19:00:00Z,15.47
S1,2026-10-19T20:00:00Z,15.37
S1,2026-10-19T21:00:00Z,16.76
S1,2026-10-19T22:00:00Z,17.20
S1,2026-10-19T23:00:00Z,19.01
S1,2026-10-20T00:00:00Z,19.70
S1,2026-10-20T01:00:00Z,21.59
S1,2026-10-20T02:00:00Z,22.20
S1,2026-10-20T03:00:00Z,23.84
S1,2026-10-20T04:00:00Z,24.03
S1,2026-10-20T05:00:00Z,25.13
S1,2026-10-20T06:00:00Z,24.70
S1,2026-10-20T07:00:00Z,25.13
S1,2026-10-20T08:00:00Z,24.03
S1,2026-10-20T09:00:00Z,23.84
S1,2026-10-20T10:00:00Z,22.20
S1,2026-10-20T11:00:00Z,21.59
S1,2026-10-20T12:00:00Z,2.00
S1,2026-10-20T13:00:00Z,19.01
S1,2026-10-20T14:00:00Z,17.20
S1,2026-10-20T15:00:00Z,16.76
S1,2026-10-20T16:00:00Z,15.37
S1,2026-10-20T17:00:00Z,15.47
S1,2026-10-20T18:00:00Z,14.70
S1,2026-10-20T19:00:00Z,15.47
S1,2026-10-20T20:00:00Z,15.37
S1,2026-10-20T21:00:00Z,16.76
S1,2026-10-20T22:00:00Z,17.20
S1,2026-10-20T23:00:00Z,19.01
S2,2026-10-17T00:00:00Z,29.70
S2,2026-10-17T01:00:00Z,31.59
S2,2026-10-17T02:00:00Z,32.20
S2,2026-10-17T03:00:00Z,33.84
S2,2026-10-17T04:00:00Z,34.03
S2,2026-10-17T05:00:00Z,35.13
S2,2026-10-17T06:00:00Z,34.70
S2,2026-10-17T07:00:00Z,35.13
S2,2026-10-17T08:00:00Z,34.03
S2,2026-10-17T09:00:00Z,33.84
S2,2026-10-17T10:00:00Z,32.20
S2,2026-10-17T11:00:00Z,31.59
S2,2026-10-17T12:00:00Z,29.70
S2,2026-10-17T13:00:00Z,29.01
S2,2026-10-17T14:00:00Z,27.20
S2,2026-10-17T15:00:00Z,26.76
S2,2026-10-17T16:00:00Z,25.37
S2,2026-10-17T17:00:00Z,25.47
S2,2026-10-17T18:00:00Z,24.70
S2,2026-10-17T19:00:00Z,25.47
S2,2026-10-17T20:00:00Z,25.37
S2,2026-10-17T21:00:00Z,26.76
S2,2026-10-17T22:00:00Z,27.20
S2,2026-10-17T23:00:00Z,29.01
S2,2026-10-18T00:00:00Z,29.70
S2,2026-10-18T01:00:00Z,31.59
S2,2026-10-18T02:00:00Z,32.20
S2,2026-10-18T03:00:00Z,33.84
S2,2026-10-18T04:00:00Z,34.03
S2,2026-10-18T05:00:00Z,35.13
S2,2026-10-18T06:00:00Z,34.70
S2,2026-10-18T07:00:00Z,35.13
S2,2026-10-18T08:00:00Z,34.03
S2,2026-10-18T09:00:00Z,33.84
S2,2026-10-18T10:00:00Z,32.20
S2,2026-10-18T11:00:00Z,31.59
S2,2026-10-18T12:00:00Z,29.70
S2,2026-10-18T13:00:00Z,29.01
S2,2026-10-18T14:00:00Z,27.20
S2,2026-10-18T15:00:00Z,26.76
S2,2026-10-18T16:00:00Z,25.37
S2,2026-10-18T17:00:00Z,25.47
S2,2026-10-18T18:00:00Z,24.70
S2,2026-10-18T19:00:00Z,25.47
S2,2026-10-18T20:00:00Z,25.37
S2,2026-10-18T21:00:00Z,26.76
S2,2026-10-18T22:00:00Z,27.20
S2,2026-10-18T23:00:00Z,29.01
S2,2026-10-19T00:00:00Z,29.70
S2,2026-10-19T01:00:00Z,31.59
S2,2026-10-19T02:00:00Z,32.20
S2,2026-10-19T03:00:00Z,33.84
S2,2026-10-19T04:00:00Z,34.03
S2,2026-10-19T05:00:00Z,35.13
S2,2026-10-19T06:00:00Z,34.70
S2,2026-10-19T07:00:00Z,35.13
S2,2026-10-19T08:00:00Z,34.03
S2,2026-10-19T09:00:00Z,33.84
S2,2026-10-19T10:00:00Z,32.20
S2,2026-10-19T11:00:00Z,31.59
S2,2026-10-19T12:00:00Z,29.70
S2,2026-10-19T13:00:00Z,29.01
S2,2026-10-19T14:00:00Z,27.20
S2,2026-10-19T15:00:00Z,26.76
S2,2026-10-19T16:00:00Z,25.37
S2,2026-10-19T17:00:00Z,25.47
S2,2026-10-19T18:00:00Z,24.70
S2,2026-10-19T19:00:00Z,25.47
S2,2026-10-19T20:00:00Z,25.37
S2,2026-10-19T21:00:00Z,26.76
S2,2026-10-19T22:00:00Z,27.20
S2,2026-10-19T23:00:00Z,29.01
S2,2026-10-20T00:00:00Z,29.70
S2,2026-10-20T01:00:00Z,31.59
S2,2026-10-20T02:00:00Z,60.00
S2,2026-10-20T03:00:00Z,33.84
S2,2026-10-20T04:00:00Z,34.03
S2,2026-10-20T05:00:00Z,35.13
S2,2026-10-20T06:00:00Z,34.70
S2,2026-10-20T07:00:00Z,35.13
S2,2026-10-20T08:00:00Z,34.03
S2,2026-10-20T09:00:00Z,33.84
S2,2026-10-20T10:00:00Z,32.20
S2,2026-10-20T11:00:00Z,31.59
S2,2026-10-20T12:00:00Z,29.70
S2,2026-10-20T13:00:00Z,29.01
S2,2026-10-20T14:00:00Z,27.20
S2,2026-10-20T15:00:00Z,26.76
S2,2026-10-20T16:00:00Z,25.37
S2,2026-10-20T17:00:00Z,25.47
S2,2026-10-20T18:00:00Z,24.70
S2,2026-10-20T19:00:00Z,25.47
S2,2026-10-20T20:00:00Z,25.37
S2,2026-10-20T21:00:00Z,26.76
S2,2026-10-20T22:00:00Z,27.20
S2,2026-10-20T23:00:00Z,29.01
setup.kql
.create table Requests (Timestamp:datetime, Level:string, Service:string, CustomerId:string, DurationMs:long, Message:string)

.ingest into table Requests (@"/kustodata/requests.csv") with (format="csv", ignoreFirstRecord=true)

.create table Sensor (SensorId:string, Timestamp:datetime, Value:real)

.ingest into table Sensor (@"/kustodata/sensor.csv") with (format="csv")

.create table DailySales (Store:string, Day:datetime, Revenue:real)

.ingest inline into table DailySales <|
north,2026-10-19,1200
north,2026-10-20,1500
north,2026-10-21,900
north,2026-10-22,2000
south,2026-10-19,800
south,2026-10-20,950
south,2026-10-21,700

.create table Clicks (UserId:string, Ts:datetime, Page:string)

.ingest inline into table Clicks <|
u1,2026-10-20T08:00:00Z,home
u1,2026-10-20T08:10:00Z,product
u1,2026-10-20T08:25:00Z,cart
u1,2026-10-20T08:50:00Z,product
u1,2026-10-20T09:05:00Z,checkout
u1,2026-10-20T10:30:00Z,home
u2,2026-10-20T08:02:00Z,home
u2,2026-10-20T08:40:00Z,product
u2,2026-10-20T08:45:00Z,cart

.create table Logs (Id:int, Line:string)

.ingest inline into table Logs <|
1,2026-10-20 08:12:00 ERROR payments order=1001 took 3050ms
2,2026-10-20 08:20:00 INFO catalog order=1002 took 45ms
3,garbage line

.create table Events (Id:int, Payload:string)

.ingest inline into table Events <|
1,"{""device"":""d1"",""temp"":21.5,""loc"":{""city"":""Oslo""}}"
2,"{""device"":""d2"",""temp"":""bad"",""loc"":{""city"":""Bergen""}}"
3,not json

Question 1: A dashboard has gaps for hours with no data. How does make-series fill them?

make-series returns one array per series, with a value for every bin from start to end, and empty bins get the default. Plain summarize by bin skips empty bins.

First, the gap. Our requests table has nothing between 10:00 and 11:00. We run q1a.kql:

q1a.kql
let start = datetime(2026-10-20 08:00);
let end = datetime(2026-10-20 13:00);
Requests
| where Timestamp >= start and Timestamp < end
| summarize Requests = count() by Hour = bin(Timestamp, 1h)
| order by Hour asc
Terminal
$ kql -f q1a.kql
> let start = datetime(2026-10-20 08:00);
Hour                  Requests
--------------------  --------
2026-10-20T08:00:00Z  5
2026-10-20T09:00:00Z  5
2026-10-20T11:00:00Z  5
2026-10-20T12:00:00Z  3
Result table4 rows
HourRequests
2026-10-20T08:00:00Z5
2026-10-20T09:00:00Z5
2026-10-20T11:00:00Z5
2026-10-20T12:00:00Z3

There is no 10:00 row, so a chart draws a line straight across it.

Now make-series: the aggregation, a default for empty bins, the time column, and from, to and step. We run q1b.kql:

q1b.kql
let start = datetime(2026-10-20 08:00);
let end = datetime(2026-10-20 13:00);
Requests
| make-series Requests = count() default=0
    on Timestamp from start to end step 1h
Terminal
$ kql -f q1b.kql
> let start = datetime(2026-10-20 08:00);
Requests     Timestamp
-----------  ------------------------------------------------------------
[5,5,0,5,3]  ["2026-10-20T08:00:00.0000000Z","2026-10-20T09:00:00.0000...

The default is 0, and to is exclusive, so 08:00 to 13:00 gives five bins: [5,5,0,5,3]. To show it as a table, or join it with other data, we mv-expand the arrays back into rows with q1c.kql:

q1c.kql
let start = datetime(2026-10-20 08:00);
let end = datetime(2026-10-20 13:00);
Requests
| make-series Requests = count() default=0
    on Timestamp from start to end step 1h
| mv-expand Timestamp to typeof(datetime), Requests to typeof(long)
| project Hour = Timestamp, Requests
| order by Hour asc
Terminal
$ kql -f q1c.kql
> let start = datetime(2026-10-20 08:00);
Hour                  Requests
--------------------  --------
2026-10-20T08:00:00Z  5
2026-10-20T09:00:00Z  5
2026-10-20T10:00:00Z  0
2026-10-20T11:00:00Z  5
2026-10-20T12:00:00Z  3
Result table5 rows
HourRequests
2026-10-20T08:00:00Z5
2026-10-20T09:00:00Z5
2026-10-20T10:00:00Z0
2026-10-20T11:00:00Z5
2026-10-20T12:00:00Z3

Every hour is there now, and 10:00 shows 0 requests. In the web UI, render timechart draws it.

The trap is averages: a zero for an empty hour is a fake value. So we use default=double(null), then series_fill_linear. We run q1d.kql for catalog:

q1d.kql
let start = datetime(2026-10-20 08:00);
let end = datetime(2026-10-20 13:00);
Requests
| where Service == "catalog"
| make-series AvgMs = avg(DurationMs) default=double(null)
    on Timestamp from start to end step 1h
| extend Filled = series_fill_linear(AvgMs)
| mv-expand Timestamp to typeof(datetime), AvgMs to typeof(real),
    Filled to typeof(real)
| project Hour = Timestamp, AvgMs, Filled
| order by Hour asc
Terminal
$ kql -f q1d.kql
> let start = datetime(2026-10-20 08:00);
Hour                  AvgMs  Filled
--------------------  -----  ------
2026-10-20T08:00:00Z  45     45
2026-10-20T09:00:00Z  45     45
2026-10-20T10:00:00Z  null   372.5
2026-10-20T11:00:00Z  700    700
2026-10-20T12:00:00Z  48     48
Result table5 rows
HourAvgMsFilled
2026-10-20T08:00:00Z4545
2026-10-20T09:00:00Z4545
2026-10-20T10:00:00ZNULL372.5
2026-10-20T11:00:00Z700700
2026-10-20T12:00:00Z4848

The empty hour becomes 372.5, halfway between 45 and 700.

Tip

Always set from and to. Without them, each series starts at its own first bin with data, and the series don't line up.

Question 2: Someone asks how to find anomalies in a metric. How does series_decompose_anomalies work?

Build a series with make-series, then call series_decompose_anomalies. It returns a flag, a score and a baseline for every point.

Here is how it works, in order:

  • make-series: one array per sensor
  • decompose: seasonal, trend and residual
  • outlier test: on the residual
  • flag, score, baseline: per point

And the defaults:

ParameterDefaultMeaning
Threshold1.5k value: mild or stronger anomalies
Seasonality-1detect automatically (0 = no seasonality)
Trendavgor linefit, or none
AD methodctukeyTukey's fence, 10th to 90th percentile range

Let's try it on our two sensors, hourly for four days. Sensor one has a three-hour gap, so series_fill_linear replaces those nulls before the decomposition. Then we decompose and keep the flagged points. We run q2.kql:

q2.kql
let start = datetime(2026-10-17);
let end = datetime(2026-10-21);
Sensor
| make-series Value = avg(Value) default=double(null)
    on Timestamp from start to end step 1h by SensorId
| extend Value = series_fill_linear(Value)
| extend (Flag, Score, Baseline) = series_decompose_anomalies(Value)
| mv-expand Timestamp to typeof(datetime), Value to typeof(real),
    Flag to typeof(int), Score to typeof(real),
    Baseline to typeof(real)
| where Flag != 0
| project SensorId, Timestamp, Value, Flag,
    Score = round(Score, 2), Baseline = round(Baseline, 2)
| order by SensorId asc, Timestamp asc
Terminal
$ kql -f q2.kql
> let start = datetime(2026-10-17);
SensorId  Timestamp             Value  Flag  Score  Baseline
--------  --------------------  -----  ----  -----  --------
S1        2026-10-20T12:00:00Z  2      -1    -5.38  19.51
S2        2026-10-20T02:00:00Z  60     1     5.39   32.49
Result table2 rows
SensorIdTimestampValueFlagScoreBaseline
S12026-10-20T12:00:00Z2-1-5.3819.51
S22026-10-20T02:00:00Z6015.3932.49

S1 drops to 2 at noon on October 20, against a baseline of 19.51. S2 spikes to 60 at 02:00, against 32.49.

A flag of -1 means below the expected value, 1 above, and 0 normal. The score says how far out a point is, so we can rank them: -5.38 and 5.39 here.

For a real project:

  • Several full cycles: of history
  • Fill gaps: before decomposing
  • Tune the threshold: on past incidents
Pitfall

The default threshold, 1.5, finds mild or stronger anomalies. That is noisy for paging people.

Question 3: A teammate needs a running total and the previous row's value. How do you use serialize, prev and row_cumsum?

Window functions like prev(), next(), row_number() and row_cumsum() need a serialized row set, meaning rows in a fixed order. We get one with order by, top or serialize.

Let's call prev on a plain table first:

Terminal (expected error)
$ kql 'DailySales | extend Prev = prev(Revenue)'
Error: Semantic error: SEM0442: Function 'prev' cannot be invoked in current context. Details: the row
  set must be serialized.

The engine refuses: Function 'prev' cannot be invoked in current context. Details: the row set must be serialized.

Here is which operators give a serialized row set:

OperatorOutput serialized?
sort / order by, top, serializeyes: window functions work
range, getschemayes
summarize, joinno: sort again first
make-series, mv-expand, distinctno: sort again first

So after a summarize, we sort again. Now the daily revenue for two stores. We order by store and day, flag each store's first row, take the previous day's revenue, and pass the flag as row_cumsum's restart argument. We run q3.kql:

q3.kql
DailySales
| order by Store asc, Day asc
| extend First = Store != prev(Store)
| extend Prev = iff(First, real(null), prev(Revenue))
| extend Change = Revenue - Prev
| extend Running = row_cumsum(Revenue, First)
| project Store, Day = format_datetime(Day, "yyyy-MM-dd"),
    Revenue, Prev, Change, Running
| order by Store asc, Day asc
Terminal
$ kql -f q3.kql
> DailySales
Store  Day         Revenue  Prev  Change  Running
-----  ----------  -------  ----  ------  -------
north  2026-10-19  1200     null  null    1200
north  2026-10-20  1500     1200  300     2700
north  2026-10-21  900      1500  -600    3600
north  2026-10-22  2000     900   1100    5600
south  2026-10-19  800      null  null    800
south  2026-10-20  950      800   150     1750
south  2026-10-21  700      950   -250    2450
Result table7 rows
StoreDayRevenuePrevChangeRunning
north2026-10-191200NULLNULL1200
north2026-10-20150012003002700
north2026-10-219001500-6003600
north2026-10-22200090011005600
south2026-10-19800NULLNULL800
south2026-10-209508001501750
south2026-10-21700950-2502450

North's running total ends at 5600. South starts again at 800, and its first row has no previous value, null.

Pitfall

serialize alone on unsorted data. It freezes an order that isn't guaranteed, so running totals can change between runs. Sort by a unique key first.

Question 4: Someone asks how to compute percentiles and distinct counts at scale. How accurate are they?

Both are estimates, so they stay cheap on huge tables. percentiles() uses T-Digest: the error is on the rank, worst at the median, and capped at 1%. dcount() uses a HyperLogLog variant.

The dcount accuracy level decides the error, and it's exact for small sets:

dcount accuracy01 (default)234
error (one sigma)1.6%0.8%0.4%0.28%0.2%
exact up to1,000 values8,000 values

Let's test it on 100,000 rows with 50,000 distinct keys. We run q4.kql:

q4.kql
range x from 1 to 100000 step 1
| extend k = x % 50000
| summarize P50 = percentile(x, 50), P99 = percentile(x, 99),
    D0 = dcount(k, 0), D1 = dcount(k), D2 = dcount(k, 2),
    D4 = dcount(k, 4), Exact = count_distinct(k)
Terminal
$ kql -f q4.kql
> range x from 1 to 100000 step 1
P50    P99    D0     D1     D2     D4     Exact
-----  -----  -----  -----  -----  -----  -----
49792  98999  50958  50173  50082  50144  50000
Result table1 row
P50P99D0D1D2D4Exact
49792989995095850173500825014450000

Level 0 says 50958, almost two percent high. The default says 50173, under half a percent. The P50 is 49792: close, not exact. count_distinct gives the exact 50000, but it's in preview and limited to 100 million unique values.

Percentiles are nearest rank, not interpolated. We run q4b.kql on the numbers 1 to 10:

q4b.kql
range x from 1 to 10 step 1
| summarize P50 = percentile(x, 50), Avg = avg(x)
Terminal
$ kql -f q4b.kql
> range x from 1 to 10 step 1
P50  Avg
---  ---
5    5.5

The median is 5, not 5.5.

In a real project:

  • Label them as estimates.
  • For an exact business count, summarize by the key, then count.
Pitfall

Never sum daily dcounts or average percentiles. For roll-ups, keep the hll() or tdigest() states and merge them.

Question 5: Product wants user sessions from click events. How do you build sessions in KQL?

Sort the clicks by user and time, then use row_window_session. It gives each click its session start. Then summarize by user and session start.

We pass three things:

  • MaxDistanceFromFirst: 1h, the longest a session can last from its first click
  • MaxDistanceBetweenNeighbors: 30m, the biggest gap between clicks
  • Restart: a new user

Let's count clicks, the last click and checkouts per session. We run q5.kql:

q5.kql
Clicks
| where Ts between (datetime(2026-10-20) .. 1d)
| sort by UserId asc, Ts asc
| extend Session = row_window_session(Ts, 1h, 30m,
    UserId != prev(UserId))
| summarize Clicks = count(), Last = max(Ts),
    Checkouts = countif(Page == "checkout") by UserId, Session
| project UserId, Start = format_datetime(Session, "HH:mm"),
    End = format_datetime(Last, "HH:mm"), Clicks, Checkouts
| order by UserId asc, Start asc
Terminal
$ kql -f q5.kql
> Clicks
UserId  Start  End    Clicks  Checkouts
------  -----  -----  ------  ---------
u1      08:00  08:50  4       0
u1      09:05  09:05  1       1
u1      10:30  10:30  1       0
u2      08:02  08:02  1       0
u2      08:40  08:45  2       0
Result table5 rows
UserIdStartEndClicksCheckouts
u108:0008:5040
u109:0509:0511
u110:3010:3010
u208:0208:0210
u208:4008:4520

u1 gets three sessions. The first runs from 08:00 to 08:50. The click at 09:05 starts a new one: the gap was only fifteen minutes, but it's more than an hour after the first click. 10:30 is new after a long gap. u2's 38-minute gap splits the visit too. Only the 09:05 session reached checkout.

For custom rules, like ending on logout, use the scan operator, or number sessions with row_cumsum over a new-session flag.

Real project

Agree on the gap with product first. It's a business rule, not a technical one.

Question 6: A teammate needs to parse messy log lines and JSON. How do parse, extract and parse_json work?

parse for lines with a fixed shape, extract for one regex group, and parse_json for JSON into a dynamic value. No match means null, not an error.

Here is the comparison:

FunctionUse it forNo match
parse / parse-wherea fixed line shape, many columnsnulls / row dropped
extract()one regex group, optional typenull
parse_json()JSON text into dynamickeeps the string

With parse, we describe the line as text and typed columns, and it fills them in one pass. Our lines have a date, time, level, service, order number and duration. We also pull the order number with extract. We run q6a.kql:

q6a.kql
Logs
| parse Line with Date:string " " Time:string " " Level:string
    " " Service:string " order=" OrderId:long " took " Ms:long "ms"
| extend Order = extract(@"order=(\d+)", 1, Line, typeof(long))
| project Id, Level, Service, OrderId, Ms, Order
| order by Id asc
Terminal
$ kql -f q6a.kql
> Logs
Id  Level  Service   OrderId  Ms    Order
--  -----  --------  -------  ----  -----
1   ERROR  payments  1001     3050  1001
2   INFO   catalog   1002     45    1002
3                    null     null  null
Result table3 rows
IdLevelServiceOrderIdMsOrder
1ERRORpayments100130501001
2INFOcatalog1002451002
3NULLNULLNULL

Lines 1 and 2 parse: ERROR payments 1001 3050 and INFO catalog 1002 45. Line 3 is garbage: it stays, with empty columns, so we can still count bad lines; parse-where would drop it instead. If you'd write several extracts on the same line, one parse is cheaper.

For JSON, parse_json turns the string into a dynamic value, then we read paths and cast. We run q6b.kql:

q6b.kql
Events
| extend d = parse_json(Payload)
| project Id, Device = tostring(d.device), Temp = todouble(d.temp),
    City = tostring(d.loc.city), Kind = gettype(d)
| order by Id asc
Terminal
$ kql -f q6b.kql
> Events
Id  Device  Temp  City    Kind
--  ------  ----  ------  ----------
1   d1      21.5  Oslo    dictionary
2   d2      null  Bergen  dictionary
3           null          string
Result table3 rows
IdDeviceTempCityKind
1d121.5Oslodictionary
2d2NULLBergendictionary
3NULLstring

The bad temperature on d2 becomes null, and the text that isn't JSON doesn't fail: gettype shows it stayed a string.

At scale

Don't parse JSON in every dashboard query. Parse it once at ingestion with an update policy. That is part 6 of this series.

Scenario 7: Operations wants an alert when a sensor's readings drop far below its normal pattern. How do you build the detection?

I build a stored function that returns only the sensors to alert on, and a scheduler runs it.

Here is the flow:

  • Sensors: hourly readings
  • Sensor table: Azure Data Explorer
  • SensorDrops(): stored function
  • Scheduled alert: every few minutes
  • On-call: operations

Inside the function: make-series per sensor over three days, fill the gaps, decompose, and keep only negative flags from the last two hours. It takes now and the threshold as parameters. Here, now is pinned to 13:00 on October 20 so the output is repeatable, and the threshold is 3.0, stricter than the default, to page only for strong drops. We run fn7.kql, then q7.kql:

fn7.kql
.create-or-alter function with (folder="Alerts",
    docstring="Sensors far below their normal pattern")
    SensorDrops(now_:datetime, k:real) {
    Sensor
    | where Timestamp between ((now_ - 3d) .. now_)
    | make-series Value = avg(Value) default=double(null)
        on Timestamp from now_ - 3d to now_ step 1h by SensorId
    | extend Value = series_fill_linear(Value)
    | extend (Flag, Score, Expected) =
        series_decompose_anomalies(Value, k)
    | mv-expand Timestamp to typeof(datetime), Value to typeof(real),
        Flag to typeof(int), Score to typeof(real),
        Expected to typeof(real)
    | where Flag == -1 and Timestamp >= now_ - 2h
    | project SensorId, Timestamp, Value,
        Expected = round(Expected, 1), Score = round(Score, 2)
}
q7.kql
SensorDrops(datetime(2026-10-20 13:00), 3.0)
| project SensorId,
    Hour = format_datetime(Timestamp, "yyyy-MM-dd HH:mm"),
    Value, Expected, Score
| order by SensorId asc, Hour asc
Terminal
$ kql -q -f fn7.kql
> .create-or-alter function with (folder="Alerts",
ok: .create-or-alter function with (folder="Alerts",
$ kql -f q7.kql
> SensorDrops(datetime(2026-10-20 13:00), 3.0)
SensorId  Hour              Value  Expected  Score
--------  ----------------  -----  --------  -----
S1        2026-10-20 12:00  2      19.4      -4.65
Result table1 row
SensorIdHourValueExpectedScore
S12026-10-20 12:00219.4-4.65

It returns one row: S1 at 12:00, reading 2, against an expected value of 19.4. Sensor two's spike isn't there: it's above normal, and it's outside the last two hours.

In Azure, a parameterless wrapper passes now, rounded down to the hour:

alert_function.kql (Azure, not run)
// a parameterless wrapper for the scheduler
.create-or-alter function SensorDropsNow() {
    SensorDrops(bin(now(), 1h), 3.0)    // complete hours only
}

Then a scheduler runs it:

  • Azure Monitor log alert: on a schedule
  • Logic App: runs it, posts to the on-call channel
  • Activator: only if the data is in a Fabric Eventhouse
Two traps

A sensor that stops sending isn't a low reading, so add a separate no-data check. And alert once per sensor per incident, or operations will mute you.

Key points to remember

  • make-series: a value for every bin; use default=double(null) plus a fill function for averages
  • series_decompose_anomalies: seasonal, trend, residual; defaults 1.5, autodetect, avg, ctukey
  • Window functions need a sorted row set; row_cumsum restarts per group
  • percentiles (T-Digest, 1% cap) and dcount (0.8% default) are estimates
  • Sessions with row_window_session; parse lines with parse, JSON with parse_json

The full script

Here is a Python script that writes every file and runs every query in order on the Kusto emulator; start the emulator container first, as the comments at the top of the script show.

Show the full script that writes the files and runs every step
Full script - writes the files and runs every step on the Kusto emulator (start the emulator container first, see the comments at the top), run it with Python
# ========================================================================
# Azure Data Explorer Interview Q&A #4 - Time series and analytics
# TechBrothersIT. Names and sample data are invented for teaching.
# Every step below was run on the Kusto emulator (Kustainer, the Azure Data Explorer engine in a Linux container,
# build 2026.11.02); the outputs in the video and the blog post are the real outputs.
# To run it yourself (Docker on Linux, macOS or Windows with WSL), in an EMPTY folder:
#   1. Start the emulator with this folder mounted at /kustodata (the steps ingest files from there):
#      docker run -d --name kustainer -e ACCEPT_EULA=Y -m 4G -p 8080:8080 -v "$PWD":/kustodata \
#          mcr.microsoft.com/azuredataexplorer/kustainer-linux:latest
#      Wait until `docker logs kustainer` says the database "is answering queries".
#   2. python KQL_Interview_QA_04_Code.py   (Python 3.10 or later; kql.py itself needs no packages: it uses the REST API)
# "kql" in the commands is a small helper written by Step 0 (kql.py): it sends a query or a management command
# to http://localhost:8080 and prints the result as a text table (no sign-in: the emulator has no authentication).
# The emulator is for development and testing only; an Azure Data Explorer cluster needs Microsoft Entra ID sign-in
# (use the Kusto SDK or the web UI there).
# Steps that restart the emulator say so in a comment: run "docker restart kustainer" at that point.
# ========================================================================

import os, subprocess, sys, time

def write(path, text):
    if text is None:
        if os.path.exists(path): os.remove(path)
        return
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        f.write(text.strip("\n") + "\n")

def run(cmd, expect_error=False, allow_error=False, env=None):
    print("\n$ " + cmd, flush=True)
    rc = subprocess.run(cmd, shell=True, env=dict(os.environ, **(env or {}))).returncode
    if rc != 0 and not (expect_error or allow_error):
        raise SystemExit("stopped: this command was expected to succeed")

# Environment used by every step (the database the steps use)
os.environ.update({'KQL_DB': 'shop'})

# Step 0: the kql helper, the database and the starting files
write("kql.py", '"""kql: run KQL queries and management commands on the local Kusto emulator (Kustainer), print the results as text tables.\n  kql \'StormEvents | take 3\'              run one query or one management command (starts with \'.\')\n  kql -f script.kql                      run every statement in the file (statements are separated by blank lines;\n                                         // comment lines are skipped); each result is printed under its first line\n  options: -d DB (default $KQL_DB or NetDefaultDB)  --max N rows to print (default 30)  --cell N max chars per cell (default 60)\n           -q  for management commands: print one line ("ok: <command>") instead of the result table\n           --stats  after a query, print the rows / extents the query scanned (from the engine\'s own query statistics)\n           --props \'{"Options": {...}}\'  client request properties (e.g. truncationmaxrecords)\n           -e  keep going after an error (the error is printed and the exit code is 1 at the end)\n           --json  print the last statement\'s first result as JSON {"cols": [...], "rows": [...]} (used by the video generator)\nEmpty cells: a null value in a non-string column prints as "null"; an empty or null string prints as nothing.\nA query that fails after returning some rows (for example a result over the truncation limit) prints the rows it got, then\n"Error (partial result): <engine message>", and exits 1.\nThe engine answers at http://localhost:8080 (no authentication: the emulator has none)."""\nimport json, os, re, sys, urllib.request, urllib.error\n\nURL = os.environ.get(\'KQL_URL\', \'http://localhost:8080\')\n\n\ndef post(path, db, csl, props=None):\n    body = {\'db\': db, \'csl\': csl, \'properties\': json.dumps(props or {\'Options\': {}})}\n    req = urllib.request.Request(URL + path, data=json.dumps(body).encode(), method=\'POST\',\n                                 headers={\'Content-Type\': \'application/json; charset=utf-8\', \'Accept\': \'application/json\',\n                                          \'x-ms-app\': \'kql-cli\', \'x-ms-client-request-id\': \'kql-cli\'})\n    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))\n    try:\n        with opener.open(req, timeout=600) as r: return json.loads(r.read().decode(\'utf-8\'))\n    except urllib.error.HTTPError as e:\n        txt = e.read().decode(\'utf-8\', \'replace\')\n        try:\n            er = json.loads(txt)[\'error\']\n            msg = er.get(\'@message\') or er.get(\'message\')\n        except Exception:\n            msg = txt.strip().split(\'\\n\')[0]\n        msg = re.sub(r\'^Request is invalid and cannot be processed: \', \'\', msg)\n        msg = re.sub(r\'\\s*\\(Activity stack:.*\', \'\', msg, flags=re.S)\n        raise KqlError(msg.strip())\n\n\nclass KqlError(Exception): pass\n\n\ndef cell(v, width, typ=\'\'):\n    if v is None: s = \'\' if typ in (\'string\', \'\') else \'null\'\n    elif isinstance(v, bool): s = \'true\' if v else \'false\'\n    elif isinstance(v, (dict, list)): s = json.dumps(v, separators=(\',\', \':\'), ensure_ascii=False)\n    elif isinstance(v, float):\n        s = repr(v)\n        if s.endswith(\'.0\'): s = s[:-2]\n    else: s = str(v)\n    s = s.replace(\'\\r\', \' \').replace(\'\\n\', \' \')\n    if len(s) > width: s = s[:width - 3] + \'...\'\n    return s\n\n\ndef table(cols, rows, mx, width, types=None):\n    rows = rows if isinstance(rows, list) else []\n    types = types or [\'\'] * len(cols)\n    shown = [[cell(v, width, types[i]) for i, v in enumerate(r)] for r in rows[:mx]]\n    w = [max([len(c)] + [len(r[i]) for r in shown]) for i, c in enumerate(cols)]\n    out = [\'  \'.join(c.ljust(w[i]) for i, c in enumerate(cols)).rstrip(),\n           \'  \'.join(\'-\' * w[i] for i in range(len(cols)))]\n    for r in shown:\n        out.append(\'  \'.join(v.ljust(w[i]) for i, v in enumerate(r)).rstrip())\n    n = len(rows)\n    if n > mx: out.append(\'... %d more rows (%d rows in total)\' % (n - mx, n))\n    elif n == 0: out.append(\'(no rows)\')\n    return \'\\n\'.join(out)\n\n\nLAST = {}\n\n\ndef one_api_msg(errs):\n    msgs = []\n    for e in errs or []:\n        er = e.get(\'error\', e) if isinstance(e, dict) else {}\n        m = er.get(\'@message\') or er.get(\'message\') or str(e)\n        m = re.sub(r\'\\s*\\(Activity stack:.*\', \'\', m, flags=re.S).strip()\n        if m not in msgs: msgs.append(m)\n    return \' | \'.join(msgs) or \'unknown error\'\n\n\ndef run_query(db, csl, a):\n    frames = post(\'/v2/rest/query\', db, csl, a.props)\n    outs, stats, partial = [], None, None\n    for f in frames:\n        if f.get(\'FrameType\') == \'DataSetCompletion\' and f.get(\'HasErrors\') and partial is None:\n            partial = one_api_msg(f.get(\'OneApiErrors\'))\n        if f.get(\'FrameType\') != \'DataTable\': continue\n        if f.get(\'TableKind\') == \'PrimaryResult\':\n            rows = [r for r in f[\'Rows\'] if isinstance(r, list)]\n            for r in f[\'Rows\']:\n                if isinstance(r, dict) and r.get(\'OneApiErrors\'): partial = one_api_msg(r[\'OneApiErrors\'])\n            cols = [c[\'ColumnName\'] for c in f[\'Columns\']]\n            if \'cols\' not in LAST: LAST.update(cols=cols, rows=rows)\n            outs.append(table(cols, rows, a.max, a.cell, [str(c.get(\'ColumnType\', \'\')).lower() for c in f[\'Columns\']]))\n        if f.get(\'TableKind\') == \'QueryCompletionInformation\':\n            cols = [c[\'ColumnName\'] for c in f[\'Columns\']]\n            for r in f[\'Rows\']:\n                d = dict(zip(cols, r))\n                if d.get(\'EventTypeName\') == \'QueryResourceConsumption\':\n                    try: stats = json.loads(d[\'Payload\'])\n                    except Exception: pass\n                if d.get(\'Level\') in (2, 3) and d.get(\'EventTypeName\') not in (\'QueryResourceConsumption\',):\n                    txt = d.get(\'Payload\') or \'\'\n                    try: txt = json.loads(txt).get(\'Text\', txt)\n                    except Exception: pass\n                    outs.append(\'%s: %s\' % (\'Warning\' if d.get(\'Level\') == 3 else \'Error\', txt))\n    if a.stats and stats:\n        sh = (stats.get(\'resource_usage\') or {}).get(\'cache\', {}).get(\'shards\', {})\n        ix = stats.get(\'input_dataset_statistics\') or {}\n        ex, rw = ix.get(\'extents\') or {}, ix.get(\'rows\') or {}\n        outs.append(\'scanned: %s of %s extents, %s of %s rows\' % (ex.get(\'scanned\'), ex.get(\'total\'), rw.get(\'scanned\'), rw.get(\'total\')))\n    if partial:\n        outs.append(\'Error (partial result): \' + partial)\n        raise PartialError(\'\\n\\n\'.join(outs))\n    return \'\\n\\n\'.join(outs)\n\n\nclass PartialError(Exception): pass\n\n\ndef run_mgmt(db, csl, a):\n    d = post(\'/v1/rest/mgmt\', db, csl, a.props)\n    if a.q and not a.json: return \'ok: \' + first_line(csl)\n    t = (d.get(\'Tables\') or [{}])[0]\n    LAST.update(cols=[c[\'ColumnName\'] for c in t.get(\'Columns\', [])], rows=t.get(\'Rows\', []))\n    return table([c[\'ColumnName\'] for c in t.get(\'Columns\', [])], t.get(\'Rows\', []), a.max, a.cell,\n                 [str(c.get(\'DataType\', c.get(\'ColumnType\', \'\'))).lower().replace(\'system.\', \'\') for c in t.get(\'Columns\', [])])\n\n\ndef first_line(s):\n    l = s.strip().split(\'\\n\')[0].strip()\n    return l if len(l) <= 90 else l[:87] + \'...\'\n\n\ndef statements(text):\n    blocks, cur = [], []\n    for l in text.split(\'\\n\'):\n        if not l.strip():\n            if cur: blocks.append(\'\\n\'.join(cur)); cur = []\n            continue\n        if l.strip().startswith(\'//\') and not cur: continue\n        cur.append(l)\n    if cur: blocks.append(\'\\n\'.join(cur))\n    return blocks\n\n\ndef main():\n    import argparse\n    p = argparse.ArgumentParser(add_help=False)\n    p.add_argument(\'-d\', default=os.environ.get(\'KQL_DB\', \'NetDefaultDB\'))\n    p.add_argument(\'-f\'); p.add_argument(\'-q\', action=\'store_true\'); p.add_argument(\'-e\', action=\'store_true\')\n    p.add_argument(\'--stats\', action=\'store_true\'); p.add_argument(\'--max\', type=int, default=30)\n    p.add_argument(\'--cell\', type=int, default=60); p.add_argument(\'--props\'); p.add_argument(\'-h\', \'--help\', action=\'store_true\')\n    p.add_argument(\'--json\', action=\'store_true\')\n    p.add_argument(\'text\', nargs=\'?\')\n    a = p.parse_args()\n    if a.help or (not a.f and not a.text): print(__doc__); return 0\n    a.props = json.loads(a.props) if a.props else None\n    stmts = statements(open(a.f).read()) if a.f else [a.text]\n    rc, first = 0, True\n    if a.json:\n        for s in stmts:\n            LAST.clear()\n            try:\n                run_mgmt(a.d, s, a) if s.lstrip().startswith(\'.\') else run_query(a.d, s, a)\n            except (KqlError, PartialError) as e:\n                print(\'Error: \' + str(e)); return 1\n        print(json.dumps(dict(cols=LAST.get(\'cols\', []), rows=LAST.get(\'rows\', [])), ensure_ascii=False))\n        return 0\n    for s in stmts:\n        if a.f:\n            if not first: print()\n            print(\'> \' + first_line(s))\n        first = False\n        try:\n            out = run_mgmt(a.d, s, a) if s.lstrip().startswith(\'.\') else run_query(a.d, s, a)\n            if out: print(out)\n        except PartialError as e:\n            print(str(e)); rc = 1\n            if not a.e: return 1\n        except KqlError as e:\n            print(\'Error: \' + str(e)); rc = 1\n            if not a.e: return 1\n    return rc\n\n\nif __name__ == \'__main__\':\n    sys.exit(main())\n')
KQL = '"%s" "%s"' % (sys.executable, os.path.abspath("kql.py"))   # commands below run it as: python kql.py ...
run(KQL + ' -d NetDefaultDB -q \'.create database shop persist (@"/kustodata/dbs/shop/md", @"/kustodata/dbs/shop/data")\'')
write('requests.csv', """\
Timestamp,Level,Service,CustomerId,DurationMs,Message
2026-10-20T08:05:00Z,Info,checkout,C001,120,order placed
2026-10-20T08:12:00Z,Error,payments,C002,3050,db-timeout while charging card
2026-10-20T08:20:00Z,Info,catalog,C003,45,search ok
2026-10-20T08:41:00Z,Warning,checkout,C001,900,slow response from payments.api
2026-10-20T08:55:00Z,Error,checkout,C004,1500,Error: payment declined
2026-10-20T09:02:00Z,Info,catalog,C002,50,search ok
2026-10-20T09:10:00Z,Error,payments,C002,3010,db-timeout while charging card
2026-10-20T09:15:00Z,Info,checkout,C005,130,order placed
2026-10-20T09:31:00Z,Error,payments,C001,2900,ERROR connecting to db.primary
2026-10-20T09:47:00Z,Info,catalog,C003,40,search ok
2026-10-20T11:03:00Z,Info,checkout,C003,110,order placed
2026-10-20T11:09:00Z,Error,checkout,C002,1700,user error: invalid coupon
2026-10-20T11:20:00Z,Warning,catalog,C005,700,cache miss
2026-10-20T11:44:00Z,Error,payments,C004,3100,err code 42 from gateway
2026-10-20T11:58:00Z,Info,payments,C005,200,refund issued
2026-10-20T12:06:00Z,Error,payments,C002,2950,db-timeout while charging card
2026-10-20T12:30:00Z,Info,checkout,C001,125,order placed
2026-10-20T12:52:00Z,Info,catalog,C004,48,search ok
""")
write('sensor.csv', """\
S1,2026-10-17T00:00:00Z,19.70
S1,2026-10-17T01:00:00Z,21.59
S1,2026-10-17T02:00:00Z,22.20
S1,2026-10-17T03:00:00Z,23.84
S1,2026-10-17T04:00:00Z,24.03
S1,2026-10-17T05:00:00Z,25.13
S1,2026-10-17T06:00:00Z,24.70
S1,2026-10-17T07:00:00Z,25.13
S1,2026-10-17T08:00:00Z,24.03
S1,2026-10-17T09:00:00Z,23.84
S1,2026-10-17T10:00:00Z,22.20
S1,2026-10-17T11:00:00Z,21.59
S1,2026-10-17T12:00:00Z,19.70
S1,2026-10-17T13:00:00Z,19.01
S1,2026-10-17T14:00:00Z,17.20
S1,2026-10-17T15:00:00Z,16.76
S1,2026-10-17T16:00:00Z,15.37
S1,2026-10-17T17:00:00Z,15.47
S1,2026-10-17T18:00:00Z,14.70
S1,2026-10-17T19:00:00Z,15.47
S1,2026-10-17T20:00:00Z,15.37
S1,2026-10-17T21:00:00Z,16.76
S1,2026-10-17T22:00:00Z,17.20
S1,2026-10-17T23:00:00Z,19.01
S1,2026-10-18T00:00:00Z,19.70
S1,2026-10-18T01:00:00Z,21.59
S1,2026-10-18T02:00:00Z,22.20
S1,2026-10-18T03:00:00Z,23.84
S1,2026-10-18T04:00:00Z,24.03
S1,2026-10-18T05:00:00Z,25.13
S1,2026-10-18T06:00:00Z,24.70
S1,2026-10-18T07:00:00Z,25.13
S1,2026-10-18T08:00:00Z,24.03
S1,2026-10-18T09:00:00Z,23.84
S1,2026-10-18T10:00:00Z,22.20
S1,2026-10-18T11:00:00Z,21.59
S1,2026-10-18T12:00:00Z,19.70
S1,2026-10-18T13:00:00Z,19.01
S1,2026-10-18T14:00:00Z,17.20
S1,2026-10-18T15:00:00Z,16.76
S1,2026-10-18T16:00:00Z,15.37
S1,2026-10-18T17:00:00Z,15.47
S1,2026-10-18T18:00:00Z,14.70
S1,2026-10-18T19:00:00Z,15.47
S1,2026-10-18T20:00:00Z,15.37
S1,2026-10-18T21:00:00Z,16.76
S1,2026-10-18T22:00:00Z,17.20
S1,2026-10-18T23:00:00Z,19.01
S1,2026-10-19T00:00:00Z,19.70
S1,2026-10-19T01:00:00Z,21.59
S1,2026-10-19T02:00:00Z,22.20
S1,2026-10-19T03:00:00Z,23.84
S1,2026-10-19T04:00:00Z,24.03
S1,2026-10-19T05:00:00Z,25.13
S1,2026-10-19T09:00:00Z,23.84
S1,2026-10-19T10:00:00Z,22.20
S1,2026-10-19T11:00:00Z,21.59
S1,2026-10-19T12:00:00Z,19.70
S1,2026-10-19T13:00:00Z,19.01
S1,2026-10-19T14:00:00Z,17.20
S1,2026-10-19T15:00:00Z,16.76
S1,2026-10-19T16:00:00Z,15.37
S1,2026-10-19T17:00:00Z,15.47
S1,2026-10-19T18:00:00Z,14.70
S1,2026-10-19T19:00:00Z,15.47
S1,2026-10-19T20:00:00Z,15.37
S1,2026-10-19T21:00:00Z,16.76
S1,2026-10-19T22:00:00Z,17.20
S1,2026-10-19T23:00:00Z,19.01
S1,2026-10-20T00:00:00Z,19.70
S1,2026-10-20T01:00:00Z,21.59
S1,2026-10-20T02:00:00Z,22.20
S1,2026-10-20T03:00:00Z,23.84
S1,2026-10-20T04:00:00Z,24.03
S1,2026-10-20T05:00:00Z,25.13
S1,2026-10-20T06:00:00Z,24.70
S1,2026-10-20T07:00:00Z,25.13
S1,2026-10-20T08:00:00Z,24.03
S1,2026-10-20T09:00:00Z,23.84
S1,2026-10-20T10:00:00Z,22.20
S1,2026-10-20T11:00:00Z,21.59
S1,2026-10-20T12:00:00Z,2.00
S1,2026-10-20T13:00:00Z,19.01
S1,2026-10-20T14:00:00Z,17.20
S1,2026-10-20T15:00:00Z,16.76
S1,2026-10-20T16:00:00Z,15.37
S1,2026-10-20T17:00:00Z,15.47
S1,2026-10-20T18:00:00Z,14.70
S1,2026-10-20T19:00:00Z,15.47
S1,2026-10-20T20:00:00Z,15.37
S1,2026-10-20T21:00:00Z,16.76
S1,2026-10-20T22:00:00Z,17.20
S1,2026-10-20T23:00:00Z,19.01
S2,2026-10-17T00:00:00Z,29.70
S2,2026-10-17T01:00:00Z,31.59
S2,2026-10-17T02:00:00Z,32.20
S2,2026-10-17T03:00:00Z,33.84
S2,2026-10-17T04:00:00Z,34.03
S2,2026-10-17T05:00:00Z,35.13
S2,2026-10-17T06:00:00Z,34.70
S2,2026-10-17T07:00:00Z,35.13
S2,2026-10-17T08:00:00Z,34.03
S2,2026-10-17T09:00:00Z,33.84
S2,2026-10-17T10:00:00Z,32.20
S2,2026-10-17T11:00:00Z,31.59
S2,2026-10-17T12:00:00Z,29.70
S2,2026-10-17T13:00:00Z,29.01
S2,2026-10-17T14:00:00Z,27.20
S2,2026-10-17T15:00:00Z,26.76
S2,2026-10-17T16:00:00Z,25.37
S2,2026-10-17T17:00:00Z,25.47
S2,2026-10-17T18:00:00Z,24.70
S2,2026-10-17T19:00:00Z,25.47
S2,2026-10-17T20:00:00Z,25.37
S2,2026-10-17T21:00:00Z,26.76
S2,2026-10-17T22:00:00Z,27.20
S2,2026-10-17T23:00:00Z,29.01
S2,2026-10-18T00:00:00Z,29.70
S2,2026-10-18T01:00:00Z,31.59
S2,2026-10-18T02:00:00Z,32.20
S2,2026-10-18T03:00:00Z,33.84
S2,2026-10-18T04:00:00Z,34.03
S2,2026-10-18T05:00:00Z,35.13
S2,2026-10-18T06:00:00Z,34.70
S2,2026-10-18T07:00:00Z,35.13
S2,2026-10-18T08:00:00Z,34.03
S2,2026-10-18T09:00:00Z,33.84
S2,2026-10-18T10:00:00Z,32.20
S2,2026-10-18T11:00:00Z,31.59
S2,2026-10-18T12:00:00Z,29.70
S2,2026-10-18T13:00:00Z,29.01
S2,2026-10-18T14:00:00Z,27.20
S2,2026-10-18T15:00:00Z,26.76
S2,2026-10-18T16:00:00Z,25.37
S2,2026-10-18T17:00:00Z,25.47
S2,2026-10-18T18:00:00Z,24.70
S2,2026-10-18T19:00:00Z,25.47
S2,2026-10-18T20:00:00Z,25.37
S2,2026-10-18T21:00:00Z,26.76
S2,2026-10-18T22:00:00Z,27.20
S2,2026-10-18T23:00:00Z,29.01
S2,2026-10-19T00:00:00Z,29.70
S2,2026-10-19T01:00:00Z,31.59
S2,2026-10-19T02:00:00Z,32.20
S2,2026-10-19T03:00:00Z,33.84
S2,2026-10-19T04:00:00Z,34.03
S2,2026-10-19T05:00:00Z,35.13
S2,2026-10-19T06:00:00Z,34.70
S2,2026-10-19T07:00:00Z,35.13
S2,2026-10-19T08:00:00Z,34.03
S2,2026-10-19T09:00:00Z,33.84
S2,2026-10-19T10:00:00Z,32.20
S2,2026-10-19T11:00:00Z,31.59
S2,2026-10-19T12:00:00Z,29.70
S2,2026-10-19T13:00:00Z,29.01
S2,2026-10-19T14:00:00Z,27.20
S2,2026-10-19T15:00:00Z,26.76
S2,2026-10-19T16:00:00Z,25.37
S2,2026-10-19T17:00:00Z,25.47
S2,2026-10-19T18:00:00Z,24.70
S2,2026-10-19T19:00:00Z,25.47
S2,2026-10-19T20:00:00Z,25.37
S2,2026-10-19T21:00:00Z,26.76
S2,2026-10-19T22:00:00Z,27.20
S2,2026-10-19T23:00:00Z,29.01
S2,2026-10-20T00:00:00Z,29.70
S2,2026-10-20T01:00:00Z,31.59
S2,2026-10-20T02:00:00Z,60.00
S2,2026-10-20T03:00:00Z,33.84
S2,2026-10-20T04:00:00Z,34.03
S2,2026-10-20T05:00:00Z,35.13
S2,2026-10-20T06:00:00Z,34.70
S2,2026-10-20T07:00:00Z,35.13
S2,2026-10-20T08:00:00Z,34.03
S2,2026-10-20T09:00:00Z,33.84
S2,2026-10-20T10:00:00Z,32.20
S2,2026-10-20T11:00:00Z,31.59
S2,2026-10-20T12:00:00Z,29.70
S2,2026-10-20T13:00:00Z,29.01
S2,2026-10-20T14:00:00Z,27.20
S2,2026-10-20T15:00:00Z,26.76
S2,2026-10-20T16:00:00Z,25.37
S2,2026-10-20T17:00:00Z,25.47
S2,2026-10-20T18:00:00Z,24.70
S2,2026-10-20T19:00:00Z,25.47
S2,2026-10-20T20:00:00Z,25.37
S2,2026-10-20T21:00:00Z,26.76
S2,2026-10-20T22:00:00Z,27.20
S2,2026-10-20T23:00:00Z,29.01
""")
write('setup.kql', """\
.create table Requests (Timestamp:datetime, Level:string, Service:string, CustomerId:string, DurationMs:long, Message:string)

.ingest into table Requests (@"/kustodata/requests.csv") with (format="csv", ignoreFirstRecord=true)

.create table Sensor (SensorId:string, Timestamp:datetime, Value:real)

.ingest into table Sensor (@"/kustodata/sensor.csv") with (format="csv")

.create table DailySales (Store:string, Day:datetime, Revenue:real)

.ingest inline into table DailySales <|
north,2026-10-19,1200
north,2026-10-20,1500
north,2026-10-21,900
north,2026-10-22,2000
south,2026-10-19,800
south,2026-10-20,950
south,2026-10-21,700

.create table Clicks (UserId:string, Ts:datetime, Page:string)

.ingest inline into table Clicks <|
u1,2026-10-20T08:00:00Z,home
u1,2026-10-20T08:10:00Z,product
u1,2026-10-20T08:25:00Z,cart
u1,2026-10-20T08:50:00Z,product
u1,2026-10-20T09:05:00Z,checkout
u1,2026-10-20T10:30:00Z,home
u2,2026-10-20T08:02:00Z,home
u2,2026-10-20T08:40:00Z,product
u2,2026-10-20T08:45:00Z,cart

.create table Logs (Id:int, Line:string)

.ingest inline into table Logs <|
1,2026-10-20 08:12:00 ERROR payments order=1001 took 3050ms
2,2026-10-20 08:20:00 INFO catalog order=1002 took 45ms
3,garbage line

.create table Events (Id:int, Payload:string)

.ingest inline into table Events <|
1,"{""device"":""d1"",""temp"":21.5,""loc"":{""city"":""Oslo""}}"
2,"{""device"":""d2"",""temp"":""bad"",""loc"":{""city"":""Bergen""}}"
3,not json
""")
run(KQL + ' -q -f setup.kql')

# Step 1: summarize by bin: the empty 10:00 hour has no row
write('q1a.kql', """\
let start = datetime(2026-10-20 08:00);
let end = datetime(2026-10-20 13:00);
Requests
| where Timestamp >= start and Timestamp < end
| summarize Requests = count() by Hour = bin(Timestamp, 1h)
| order by Hour asc
""")
run(KQL + ' -f q1a.kql')

# Step 2: make-series: one array, a 0 for the empty hour
write('q1b.kql', """\
let start = datetime(2026-10-20 08:00);
let end = datetime(2026-10-20 13:00);
Requests
| make-series Requests = count() default=0
    on Timestamp from start to end step 1h
""")
run(KQL + ' -f q1b.kql')

# Step 3: mv-expand the series back to rows
write('q1c.kql', """\
let start = datetime(2026-10-20 08:00);
let end = datetime(2026-10-20 13:00);
Requests
| make-series Requests = count() default=0
    on Timestamp from start to end step 1h
| mv-expand Timestamp to typeof(datetime), Requests to typeof(long)
| project Hour = Timestamp, Requests
| order by Hour asc
""")
run(KQL + ' -f q1c.kql')

# Step 4: avg with default=double(null), then series_fill_linear
write('q1d.kql', """\
let start = datetime(2026-10-20 08:00);
let end = datetime(2026-10-20 13:00);
Requests
| where Service == "catalog"
| make-series AvgMs = avg(DurationMs) default=double(null)
    on Timestamp from start to end step 1h
| extend Filled = series_fill_linear(AvgMs)
| mv-expand Timestamp to typeof(datetime), AvgMs to typeof(real),
    Filled to typeof(real)
| project Hour = Timestamp, AvgMs, Filled
| order by Hour asc
""")
run(KQL + ' -f q1d.kql')

# Step 5: series_decompose_anomalies on two sensors
write('q2.kql', """\
let start = datetime(2026-10-17);
let end = datetime(2026-10-21);
Sensor
| make-series Value = avg(Value) default=double(null)
    on Timestamp from start to end step 1h by SensorId
| extend Value = series_fill_linear(Value)
| extend (Flag, Score, Baseline) = series_decompose_anomalies(Value)
| mv-expand Timestamp to typeof(datetime), Value to typeof(real),
    Flag to typeof(int), Score to typeof(real),
    Baseline to typeof(real)
| where Flag != 0
| project SensorId, Timestamp, Value, Flag,
    Score = round(Score, 2), Baseline = round(Baseline, 2)
| order by SensorId asc, Timestamp asc
""")
run(KQL + ' -f q2.kql')

# Step 6: prev() on an unsorted table: the row set must be serialized
run(KQL + " 'DailySales | extend Prev = prev(Revenue)'", expect_error=True)   # EXPECTED TO FAIL: the video shows this error

# Step 7: order by, then prev and row_cumsum with a restart per store
write('q3.kql', """\
DailySales
| order by Store asc, Day asc
| extend First = Store != prev(Store)
| extend Prev = iff(First, real(null), prev(Revenue))
| extend Change = Revenue - Prev
| extend Running = row_cumsum(Revenue, First)
| project Store, Day = format_datetime(Day, "yyyy-MM-dd"),
    Revenue, Prev, Change, Running
| order by Store asc, Day asc
""")
run(KQL + ' -f q3.kql')

# Step 8: percentiles and dcount accuracy levels on 100,000 rows
write('q4.kql', """\
range x from 1 to 100000 step 1
| extend k = x % 50000
| summarize P50 = percentile(x, 50), P99 = percentile(x, 99),
    D0 = dcount(k, 0), D1 = dcount(k), D2 = dcount(k, 2),
    D4 = dcount(k, 4), Exact = count_distinct(k)
""")
run(KQL + ' -f q4.kql')

# Step 9: percentile is nearest rank
write('q4b.kql', """\
range x from 1 to 10 step 1
| summarize P50 = percentile(x, 50), Avg = avg(x)
""")
run(KQL + ' -f q4b.kql')

# Step 10: sessions with row_window_session
write('q5.kql', """\
Clicks
| where Ts between (datetime(2026-10-20) .. 1d)
| sort by UserId asc, Ts asc
| extend Session = row_window_session(Ts, 1h, 30m,
    UserId != prev(UserId))
| summarize Clicks = count(), Last = max(Ts),
    Checkouts = countif(Page == "checkout") by UserId, Session
| project UserId, Start = format_datetime(Session, "HH:mm"),
    End = format_datetime(Last, "HH:mm"), Clicks, Checkouts
| order by UserId asc, Start asc
""")
run(KQL + ' -f q5.kql')

# Step 11: parse and extract on log lines
write('q6a.kql', 'Logs\n| parse Line with Date:string " " Time:string " " Level:string\n    " " Service:string " order=" OrderId:long " took " Ms:long "ms"\n| extend Order = extract(@"order=(\\d+)", 1, Line, typeof(long))\n| project Id, Level, Service, OrderId, Ms, Order\n| order by Id asc\n')
run(KQL + ' -f q6a.kql')

# Step 12: parse_json on payloads
write('q6b.kql', """\
Events
| extend d = parse_json(Payload)
| project Id, Device = tostring(d.device), Temp = todouble(d.temp),
    City = tostring(d.loc.city), Kind = gettype(d)
| order by Id asc
""")
run(KQL + ' -f q6b.kql')

# Step 13: the SensorDrops function, called with now pinned
write('fn7.kql', """\
.create-or-alter function with (folder="Alerts",
    docstring="Sensors far below their normal pattern")
    SensorDrops(now_:datetime, k:real) {
    Sensor
    | where Timestamp between ((now_ - 3d) .. now_)
    | make-series Value = avg(Value) default=double(null)
        on Timestamp from now_ - 3d to now_ step 1h by SensorId
    | extend Value = series_fill_linear(Value)
    | extend (Flag, Score, Expected) =
        series_decompose_anomalies(Value, k)
    | mv-expand Timestamp to typeof(datetime), Value to typeof(real),
        Flag to typeof(int), Score to typeof(real),
        Expected to typeof(real)
    | where Flag == -1 and Timestamp >= now_ - 2h
    | project SensorId, Timestamp, Value,
        Expected = round(Expected, 1), Score = round(Score, 2)
}
""")
write('q7.kql', """\
SensorDrops(datetime(2026-10-20 13:00), 3.0)
| project SensorId,
    Hour = format_datetime(Timestamp, "yyyy-MM-dd HH:mm"),
    Value, Expected, Score
| order by SensorId asc, Hour asc
""")
run(KQL + ' -q -f fn7.kql')
run(KQL + ' -f q7.kql')
Next in this series

Part 5: Ingestion

The sample data on this page is invented for teaching. Every terminal output is the real output of the command above it, run on the Kusto emulator (Kustainer, the Azure Data Explorer engine in a Linux container, build 2026.11.02). Features the emulator cannot show truthfully are shown as code. Part of the Real Time Azure Data Explorer and KQL Interview Questions and Answers series on TechBrothersIT. Features, limits and their status (GA or preview) are current as of November 2026; check the official Azure Data Explorer and Kusto documentation (learn.microsoft.com/azure/data-explorer and learn.microsoft.com/kusto) for anything you quote in an interview.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.