Running Device Queries with KQL
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② 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.
- Source: The table where the data lives (e.g.,
DeviceInfo,DeviceProcessEvents). - Filter: The
whereoperator, which narrows down your results based on specific criteria. - Project: The
projectoperator, which selects only the columns you want to see. - Sort/Summarize: Commands like
order byorsummarizethat 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)orbetween(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
containswhen you can use==orin. Thecontainsoperator 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 usecontainsorhaswhen 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
takeorlimitoperator 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
- Visibility is Everything: KQL allows you to transform raw telemetry into meaningful insights, moving you from reactive troubleshooting to proactive management.
- Start with the Basics: Master the
where,project, andsummarizeoperators first. These three commands will handle 80% of your daily administrative tasks. - 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. - 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.
- Data Integrity: Be mindful of null values and case sensitivity. Using functions like
coalesce()andtolower()will make your queries more resilient to inconsistent data. - 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.
- 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.
- Choosing Device Join Types
- Choosing Device Join Types Quiz5q
- Joining Devices to Microsoft Entra ID
- Joining Devices to Microsoft Entra ID Quiz5q
- Registering Devices to Microsoft Entra ID
- Registering Devices to Microsoft Entra ID Quiz5q
- Planning Device Groups in Microsoft Entra ID
- Planning Device Groups in Microsoft Entra ID Quiz5q
- Implementing Dynamic Device Groups
- Implementing Dynamic Device Groups Quiz5q
- Configuring Enrollment Settings
- Configuring Enrollment Settings Quiz5q
- Configuring Automatic Enrollment for Windows
- Configuring Automatic Enrollment for Windows Quiz5q
- Configuring Bulk Enrollment for iOS and Android
- Configuring Bulk Enrollment for iOS and Android Quiz5q
- Configuring Android Enrollment Profiles
- Configuring Android Enrollment Profiles Quiz5q
- Configuring Android Enterprise Work Profiles
- Configuring Android Enterprise Work Profiles Quiz5q
- Managing Roles in Intune
- Managing Roles in Intune Quiz5q
- Implementing Compliance Policies
- Implementing Compliance Policies Quiz5q
- Implementing Conditional Access with Compliance
- Implementing Conditional Access with Compliance Quiz5q
- Configuring Windows Hello for Business
- Configuring Windows Hello for Business Quiz5q
- Implementing Windows LAPS
- Implementing Windows LAPS Quiz5q
- Managing Local Groups Membership
- Managing Local Groups Membership Quiz5q
- Choosing Between Autopilot and Provisioning Packages
- Choosing Between Autopilot and Provisioning Packages Quiz5q
- Choosing Windows Autopilot Deployment Modes
- Choosing Windows Autopilot Deployment Modes Quiz5q
- Applying Device Name Templates
- Applying Device Name Templates Quiz5q
- Implementing Windows Autopilot Deployment
- Implementing Windows Autopilot Deployment Quiz5q
- Creating Enrollment Status Pages
- Creating Enrollment Status Pages Quiz5q
- Implementing Provisioning Packages
- Implementing Provisioning Packages Quiz5q
- Planning Windows 11 Upgrades
- Planning Windows 11 Upgrades Quiz5q
- Implementing Windows 365 Cloud PC
- Implementing Windows 365 Cloud PC Quiz5q
- Configuring Autopilot Device Preparation
- Configuring Autopilot Device Preparation Quiz5q
- Creating Windows Device Configuration Profiles
- Creating Windows Device Configuration Profiles Quiz5q
- Importing ADMX Files
- Importing ADMX Files Quiz5q
- Creating Android Device Profiles
- Creating Android Device Profiles Quiz5q
- Creating iOS and iPadOS Device Profiles
- Creating iOS and iPadOS Device Profiles Quiz5q
- Creating macOS Device Profiles
- Creating macOS Device Profiles Quiz5q
- Targeting Profiles Using Filters
- Targeting Profiles Using Filters Quiz5q
- Creating Windows 11 Enterprise Multi-Session Profiles
- Creating Windows 11 Enterprise Multi-Session Profiles Quiz5q
- Configuring Endpoint Privilege Management
- Configuring Endpoint Privilege Management Quiz5q
- Using Enterprise App Catalog
- Using Enterprise App Catalog Quiz5q
- Implementing Advanced Analytics
- Implementing Advanced Analytics Quiz5q
- Configuring Remote Help
- Configuring Remote Help Quiz5q
- Implementing Microsoft Tunnel for MAM
- Implementing Microsoft Tunnel for MAM Quiz5q
- Understanding Microsoft Cloud PKI
- Understanding Microsoft Cloud PKI Quiz5q
- Syncing and Restarting Devices
- Syncing and Restarting Devices Quiz5q
- Retiring and Wiping Devices
- Retiring and Wiping Devices Quiz5q
- Performing Bulk Remote Actions
- Performing Bulk Remote Actions Quiz5q
- Rotating BitLocker Recovery Keys
- Rotating BitLocker Recovery Keys Quiz5q
- Running Device Queries with KQL
- Running Device Queries with KQL Quiz5q
- Updating Defender Antivirus Definitions
- Updating Defender Antivirus Definitions Quiz5q
- Preparing Applications for Deployment
- Preparing Applications for Deployment Quiz5q
- Deploying Apps Using Intune
- Deploying Apps Using Intune Quiz5q
- Deploying Microsoft 365 Apps
- Deploying Microsoft 365 Apps Quiz5q
- Configuring Policies for Office Apps
- Configuring Policies for Office Apps Quiz5q
- Using Office Deployment Tool with Autopilot
- Using Office Deployment Tool with Autopilot Quiz5q
- Managing Apps in Microsoft 365 Admin Center
- Managing Apps in Microsoft 365 Admin Center Quiz5q
- Deploying Apps from Platform App Stores
- Deploying Apps from Platform App Stores Quiz5q
- Managing Win32 App Dependencies
- Managing Win32 App Dependencies Quiz5q
- Planning App Protection Policies
- Planning App Protection Policies Quiz5q
- Implementing App Protection Policies
- Implementing App Protection Policies Quiz5q
- Implementing Conditional Access for Apps
- Implementing Conditional Access for Apps Quiz5q
- Planning App Configuration Policies
- Planning App Configuration Policies Quiz5q
- Implementing App Configuration Policies
- Implementing App Configuration Policies Quiz5q
- Configuring Selective Wipe for Apps
- Configuring Selective Wipe for Apps Quiz5q
- Creating Antivirus Policies
- Creating Antivirus Policies Quiz5q
- Creating Disk Encryption Policies
- Creating Disk Encryption Policies Quiz5q
- Creating Firewall Policies
- Creating Firewall Policies Quiz5q
- Configuring Attack Surface Reduction
- Configuring Attack Surface Reduction Quiz5q
- Implementing Security Baselines
- Implementing Security Baselines Quiz5q
- Integrating with Defender for Endpoint
- Integrating with Defender for Endpoint Quiz5q
- Onboarding Devices to Defender for Endpoint
- Onboarding Devices to Defender for Endpoint Quiz5q
- Configuring Endpoint Detection and Response
- Configuring Endpoint Detection and Response Quiz5q
- Planning Device Updates
- Planning Device Updates Quiz5q
- Creating Windows Update Rings
- Creating Windows Update Rings Quiz5q
- Managing iOS and macOS Updates
- Managing iOS and macOS Updates Quiz5q
- Managing Android Updates
- Managing Android Updates Quiz5q
- Configuring Delivery Optimization
- Configuring Delivery Optimization Quiz5q
- Monitoring Update Deployments
- Monitoring Update Deployments Quiz5q
- Creating Feature Update Policies
- Creating Feature Update Policies Quiz5q
- Managing Quality Update Expedites
- Managing Quality Update Expedites Quiz5q
- Using Windows Update for Business Reports
- Using Windows Update for Business Reports Quiz5q
Spend your points to unlock exam-style practice questions
Spend points to unlock MD-102 exam-style practice questions.
Practice for MD-102