Running Device Queries with KQL

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 9 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Lesson: Running Device Queries with KQL

Introduction: The Power of Data-Driven Device Management

In modern IT environments, managing devices is no longer just about pushing software updates or resetting passwords. It is about visibility. When you have hundreds or thousands of devices distributed across offices, homes, and remote locations, the ability to "ask" your fleet questions and receive immediate, actionable answers is a superpower. This is where Kusto Query Language (KQL) comes into play. KQL is the engine behind many advanced endpoint management platforms, allowing administrators to sift through vast amounts of telemetry data to find exactly what they need in seconds.

Why does this matter? Imagine a scenario where a new security vulnerability is announced. Instead of manually checking every device or waiting for a slow inventory report to generate, you can write a simple KQL query to identify every machine currently running the affected software version. You can pinpoint the exact hardware specifications, the user logged in, and the last time the device checked in. KQL transforms device management from a reactive, manual process into a proactive, data-driven operation. By mastering this language, you stop guessing about the state of your infrastructure and start knowing.


Not read yet

Understanding the Fundamentals of KQL

KQL is a read-only query language, meaning you cannot accidentally delete or modify your device data while running a query. It is designed to be highly efficient, processing massive datasets by filtering, sorting, and aggregating information using a syntax that reads somewhat like a sentence. If you have ever used SQL, you will find some similarities, but KQL is specifically optimized for log and telemetry data, which makes it significantly faster for the types of tasks we perform in device management.

At its core, a KQL query flows from left to right, using a pipe operator (|) to pass data from one command to the next. You start by identifying the table containing the information you need, and then you "pipe" that data through various operators to refine your results.

The Basic Structure of a Query

Every query follows a logical progression. You start with the source (the table), filter the data to narrow your scope, project the specific columns you care about, and finally, sort or summarize the results to make them readable.

  1. Source: The table where the data lives (e.g., DeviceInfo, DeviceProcessEvents).
  2. Filter: The where operator, which narrows down your results based on specific criteria.
  3. Project: The project operator, which selects only the columns you want to see.
  4. Sort/Summarize: Commands like order by or summarize that organize the final output.

Callout: KQL vs. SQL While SQL is designed for relational databases where data is highly structured into rows and columns, KQL is built for time-series and log data. In SQL, you might spend a lot of time joining multiple tables together. In KQL, the data is often pre-indexed and optimized for "search" behavior. You will find that KQL is much more forgiving with syntax and allows for "exploratory" querying, where you can start broad and drill down without needing to know the entire schema ahead of time.


Not read yet

Essential Operators for Device Queries

To be effective at device management, you need to master a handful of core operators. These are the building blocks of every query you will write.

1. The where Operator

The where operator is your primary tool for filtering. It acts as a gatekeeper, letting only the records that meet your specific conditions pass through to the next stage of your query.

Example: Finding all devices running Windows 10.

DeviceInfo
| where OSPlatform == "Windows10"

2. The project Operator

When you query a table, it might contain hundreds of columns, most of which you don't need. The project operator keeps your output clean by showing only the data points relevant to your current task.

Example: Showing only the device name and the last logged-on user.

DeviceInfo
| project DeviceName, LoggedOnUsers

3. The summarize Operator

This is arguably the most powerful operator for reporting. It allows you to perform calculations, such as counting how many devices are in a specific state or finding the average version number of a software package.

Example: Counting how many devices are in each health state.

DeviceHealthStatus
| summarize DeviceCount = count() by HealthStatus

4. The extend Operator

Sometimes, the data you need isn't stored in a single column. The extend operator allows you to create new, temporary columns based on calculations or transformations of existing data.

Example: Creating a "FullDisplayName" by combining the first and last name columns.

UserTable
| extend FullName = strcat(FirstName, " ", LastName)

Not read yet

Practical Scenarios: Running Queries in the Real World

Let's look at how these concepts apply to daily administrative tasks. We will move from basic inventory checks to more complex security investigations.

Scenario 1: Identifying Outdated OS Versions

Keeping track of operating system versions is a fundamental security practice. You want to ensure that all devices are on a supported build.

DeviceInfo
| where OSVersion !contains "22H2"
| project DeviceName, OSVersion, LastSeen
| sort by LastSeen desc

Breakdown of this query:

  • DeviceInfo: We are looking at the master device inventory table.
  • where OSVersion !contains "22H2": We filter out any device that already has the latest build, leaving us only with the "laggards."
  • project: We limit the output to the name, version, and the last time it checked in.
  • sort by: We put the most recently seen devices at the top so we can prioritize machines that are actually active.

Scenario 2: Investigating a Specific User's Activity

If a user reports that their device is behaving strangely, you need to see what processes have been running on their specific machine.

DeviceProcessEvents
| where DeviceName == "LAPTOP-XYZ-123"
| where Timestamp > ago(24h)
| project Timestamp, FileName, ProcessCommandLine, InitiatingProcessFileName
| sort by Timestamp desc

Breakdown of this query:

  • DeviceProcessEvents: This table tracks every process execution on your managed fleet.
  • where DeviceName == ...: We isolate the search to one specific hardware asset.
  • where Timestamp > ago(24h): This is a crucial filter. Querying raw telemetry can be slow, so we limit our search to the last 24 hours to keep performance high.
  • project: We pull the command line arguments, which are often where malicious activity hides.

Tip: Using Time Ranges Always include a time range filter (like ago(24h) or between(datetime(2023-01-01) .. datetime(2023-01-31))) in your queries. Without it, KQL will attempt to scan the entire historical database, which can lead to slow performance and potential query timeouts.


Not read yet

Deep Dive: Advanced KQL Techniques

Once you are comfortable with the basics, you can start using advanced techniques to perform complex analytics.

Joining Data Tables

Sometimes, the information you need is spread across two different tables. For instance, you might have device information in one table and security alerts in another. You can use the join operator to combine them.

DeviceInventory
| join kind=inner (DeviceAlerts) on DeviceId
| project DeviceName, AlertTitle, Severity
  • join: Connects two tables based on a common field (in this case, DeviceId).
  • kind=inner: Ensures that only devices that have both an inventory record and an alert appear in the output.

Handling Null Values

In real-world data, fields are often empty. If you try to perform a calculation on a null value, the query might fail or return unexpected results. Use the isnotnull() or coalesce() functions to handle these edge cases.

DeviceInfo
| extend CleanOS = coalesce(OSVersion, "Unknown")
| summarize count() by CleanOS

This query ensures that if the OS version is missing, it is labeled as "Unknown" rather than just disappearing from your summary.


Not read yet

Best Practices for KQL Querying

Writing queries is an art as much as a science. Follow these best practices to ensure your queries are reliable, fast, and easy to maintain.

1. The "Filter Early, Filter Often" Rule

The most common mistake beginners make is pulling back too much data before filtering it. Always place your where clauses as close to the beginning of the query as possible. By reducing the dataset early, you save memory and processing power, resulting in a faster response.

2. Comment Your Code

KQL supports comments using the // syntax. If you are writing a query that you plan to save and reuse (or share with your team), add a brief comment explaining what the query does.

// Identify devices that have not checked in for more than 30 days
DeviceInfo
| where LastSeen < ago(30d)
| project DeviceName, LastSeen

3. Use project to Clean Up Output

Never output the entire row of a table unless absolutely necessary. Raw telemetry tables can have dozens of columns, and displaying them all makes it impossible to find the information you actually need. Always use project or project-away to curate the output.

4. Avoid * in Queries

While select * is common in SQL, using * in KQL is generally discouraged for production queries. It is unpredictable; if the underlying schema changes and a new column is added, your report might suddenly become cluttered with unnecessary data. Explicitly naming your columns is a safer practice.

Warning: The Performance Pitfall Avoid using contains when you can use == or in. The contains operator performs a full-text search, which is computationally expensive. If you know the exact value (e.g., where OSVersion == "Windows 11"), always use an equality operator. Only use contains or has when you are performing partial string matching.


Not read yet

Comparison: KQL Operators

Operator Purpose Best Used For
where Filtering Narrowing results based on specific criteria.
project Selection Choosing which columns to display.
extend Calculation Creating new data fields on the fly.
summarize Aggregation Counting, averaging, or grouping data.
join Integration Combining data from two distinct tables.
sort by Ordering Organizing results for readability.

Common Pitfalls and Troubleshooting

Even experienced administrators run into issues when writing queries. Here are the most common problems and how to fix them.

Pitfall 1: Timezone Confusion

When you use ago(1d), KQL uses UTC time by default. If your organization operates in a specific timezone, you might find that your query results don't seem to match the "local" time you expect.

  • Fix: Be aware that all system logs are stored in UTC. When interpreting your results, always account for the offset from your local time.

Pitfall 2: Case Sensitivity

By default, some string comparisons in KQL are case-sensitive, while others are not. For example, == is case-sensitive, but has is not.

  • Fix: If you are searching for a device name and aren't sure if it's "Laptop-01" or "laptop-01", use the case-insensitive version of the operator or convert the string to lowercase first using tolower().
DeviceInfo
| where tolower(DeviceName) == "laptop-01"

Pitfall 3: The "Too Much Data" Error

If you run a query that returns millions of rows, the system might block it to prevent a service disruption.

  • Fix: Use the take or limit operator to test your query on a small sample size before running it against the entire dataset.
DeviceInfo
| take 100

Not read yet

Building a Library of "Standard Queries"

As you manage your devices, you will find yourself running the same types of queries repeatedly. It is a best practice to build a personal library of these queries. You can store them in a simple text file or a shared documentation site. Having a "cheat sheet" saves you time and ensures consistency in how you report on device health.

Example: The "Daily Health Check" Query

This query provides a high-level overview of your environment.

// A quick view of device health and OS distribution
DeviceInfo
| summarize DeviceCount = count() by OSPlatform, HealthStatus
| sort by DeviceCount desc

Example: The "Software Inventory" Query

This helps you identify how many devices have a specific application installed.

// Find devices with a specific application
DeviceInstalledApplications
| where AppName contains "Chrome"
| summarize AppCount = count() by DeviceName

Not read yet

FAQ: Frequently Asked Questions

Q: Can I modify device data using KQL? A: No, KQL is strictly a query language for reading and analyzing data. You cannot use it to change settings or delete files on a device.

Q: Does KQL work on all devices? A: KQL works on any device that is reporting telemetry to your management platform (such as Microsoft Defender for Endpoint or Azure Monitor). If a device is offline, it will not report data until it reconnects.

Q: How do I share my queries with my team? A: Most platforms that use KQL allow you to save queries as "Saved Queries" or "Workbooks." This allows team members to run the same analysis without needing to know the underlying query logic.

Q: Is KQL difficult to learn? A: If you have basic computer literacy and an understanding of logical operators (AND, OR, NOT), you will find KQL very intuitive. The syntax is designed to be readable.


Key Takeaways

  1. Visibility is Everything: KQL allows you to transform raw telemetry into meaningful insights, moving you from reactive troubleshooting to proactive management.
  2. Start with the Basics: Master the where, project, and summarize operators first. These three commands will handle 80% of your daily administrative tasks.
  3. Optimize for Performance: Always filter your data early and use time ranges (e.g., ago()) to prevent queries from timing out or consuming unnecessary resources.
  4. Adopt a Standardized Workflow: Create a library of reusable queries for common tasks like identifying outdated OS versions, checking software inventory, and reviewing recent process activity.
  5. Data Integrity: Be mindful of null values and case sensitivity. Using functions like coalesce() and tolower() will make your queries more resilient to inconsistent data.
  6. Continuous Learning: The best way to learn KQL is by doing. Start with simple queries and gradually incorporate joins, subqueries, and advanced aggregations as your needs evolve.
  7. Documentation Matters: Always comment your code. A well-documented query is much easier to debug and share with colleagues, making your entire IT team more efficient.

By applying these principles, you will gain a deep understanding of your device fleet. You will no longer be wondering what is happening on your network; you will be able to prove it with data. KQL is a foundational skill for the modern IT professional, and mastering it will distinguish you as a capable and efficient administrator. Start small, experiment often, and build your library of queries to streamline your daily workflow.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.