Where and Project Operators

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 8 read · keep scrolling

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

Mastering KQL: The Power of Where and Project Operators

Introduction: The Foundation of Data Analysis in Sentinel

When you work with Microsoft Sentinel, you are effectively acting as a detective. You are sifting through massive volumes of telemetry, logs, and security signals to uncover patterns, identify threats, and maintain the health of your environment. However, raw data is rarely useful in its natural state. It is often noisy, overwhelming, and cluttered with information that is irrelevant to the specific question you are trying to answer. This is where the Kusto Query Language (KQL) becomes your most essential tool.

KQL is designed for high-performance data exploration. At the heart of almost every query you will write are two fundamental operators: where and project. Think of these as the "filter" and the "lens" of your analysis. The where operator allows you to discard the noise, narrowing down your massive dataset to only the records that meet your specific criteria. The project operator allows you to focus on the specific attributes (columns) that matter, discarding everything else to make your output readable and actionable.

Understanding these two operators is not just about writing code; it is about learning how to think like an analyst. If you cannot effectively filter your data, you will be drowned in false positives. If you cannot shape your data, you will struggle to visualize it in dashboards or present it in reports. In this lesson, we will dive deep into how to use these operators effectively, how to combine them, and how to avoid common pitfalls that can slow down your queries or lead to incorrect conclusions.


Not read yet

The Where Operator: Mastering Data Filtering

The where operator is the primary mechanism for row-level filtering in KQL. When you append a where statement to your query, you are instructing the engine to iterate through the records in your table and return only those that evaluate to true for a given expression. If a record does not meet the criteria, it is excluded from the subsequent stages of your pipeline.

Basic Syntax and Usage

The syntax for the where operator is straightforward: Table | where Condition. You can chain multiple where operators together, or you can use logical operators like and or or to combine multiple conditions into a single statement.

Consider a scenario where you are investigating sign-in logs. You want to see only the failed attempts. Your query would look like this:

SigninLogs
| where ResultType != 0

In this example, SigninLogs is the table, and ResultType != 0 is the condition. In Azure Active Directory logs, a ResultType of 0 typically indicates a successful sign-in. By using the "not equal to" operator, we effectively filter out all successful logins, leaving us with only the failures.

Combining Multiple Conditions

Often, a single condition is not enough to narrow down your search. You might want to filter by both the outcome and the location of the user. You can combine these using the and operator:

SigninLogs
| where ResultType != 0 and IPAddress startswith "192.168."

By combining these, the KQL engine performs a logical intersection. A record must satisfy both conditions to be returned. If the sign-in failed but the IP address does not start with "192.168.", it will be excluded. This is the most efficient way to write your queries because it reduces the number of rows being processed as early as possible in the query pipeline.

Callout: The "Early Filtering" Principle Always apply your where filters as early as possible in your query. KQL is highly optimized, but the sooner you reduce the number of rows being processed, the less memory and CPU your query will consume. This is especially critical when dealing with tables containing millions of rows, such as SecurityEvent or SigninLogs.

Handling Nulls and Empty Values

One of the most common mistakes beginners make is failing to account for null or empty values. In KQL, a null value is distinct from an empty string. If you have a column that may contain null, a standard filter like where Column != "Value" might accidentally exclude rows where the column is null, because null is not equal to "Value," but it is also not technically a string.

To handle this, you can use the isnotempty() or isnotnull() functions:

SigninLogs
| where isnotempty(UserPrincipalName)
| where ResultType != 0

This ensures that your results are clean and that you aren't accidentally filtering out valid records just because they lack data in a specific field.


Not read yet

The Project Operator: Shaping Your Data Output

Once you have filtered your data using where, you are often left with a table that contains dozens of columns, many of which are irrelevant to your task. The project operator allows you to select, rename, and even create new columns on the fly. It is the tool you use to refine the "shape" of your data before it is displayed in a graph, table, or alert.

Basic Column Selection

The simplest use of project is to list the specific columns you want to see. This makes your output much cleaner and easier to read.

SigninLogs
| where ResultType != 0
| project TimeGenerated, UserPrincipalName, IPAddress, ResultDescription

By explicitly naming these four columns, you discard all the other metadata associated with the sign-in event. This is not just for readability; it also reduces the amount of data transmitted to your browser or reporting tool, which can improve performance in large-scale dashboards.

Renaming and Creating Columns

The project operator is powerful because it allows you to manipulate the data during the projection phase. You can rename columns to make them more descriptive, or you can create new columns based on calculations or transformations.

SigninLogs
| where ResultType != 0
| project Timestamp = TimeGenerated, User = UserPrincipalName, Location = IPAddress
| extend IsInternal = IPAddress startswith "192.168."

In this example, we renamed TimeGenerated to Timestamp, UserPrincipalName to User, and IPAddress to Location. We also used the extend operator (which works closely with project) to create a new boolean column called IsInternal that flags whether the sign-in came from a local network.

Project vs. Project-Away

Sometimes, you know exactly which columns you want to keep, but other times, you might know which columns you want to remove while keeping everything else. For these scenarios, KQL provides project-away.

SigninLogs
| project-away DeviceDetail, AppDisplayName, UserAgent

This is particularly useful when working with tables that have hundreds of columns. Instead of listing the 90 columns you want to keep, you can simply list the 10 you want to remove. It keeps your code concise and easier to maintain.

Callout: Project vs. Extend While project is used to define the final structure of your result set, extend is used to add new calculated columns to your existing table without removing the original columns. A common pattern is to use extend to perform calculations and then project at the very end to clean up the output.


Not read yet

Best Practices for Efficient Querying

Writing KQL is an art form. While the language is forgiving, there are industry standards that distinguish a "good" query from a "great" one. Following these practices will ensure your queries remain fast, readable, and maintainable.

1. Always Use Time Filters

In Microsoft Sentinel, data is partitioned by time. If you do not specify a time range, the query engine may have to scan vast amounts of historical data, which is slow and expensive. Always include a time filter at the beginning of your query using the TimeGenerated column.

SigninLogs
| where TimeGenerated > ago(24h)
| where ResultType != 0

2. Be Explicit with Column Names

Avoid using * (the wildcard) in your project statements unless you are performing an ad-hoc investigation. In production queries (like those used for alerts or dashboards), always list the columns you need. If the table schema changes (e.g., Microsoft adds a new column), using * might cause unexpected behavior in your downstream applications.

3. Comment Your Code

KQL supports comments using double slashes //. Use them to explain why you are filtering for certain conditions. This is invaluable when you return to a query six months later or when a colleague needs to audit your work.

// Filter for failed logins that originated from outside the known VPN range
SigninLogs
| where TimeGenerated > ago(7d)
| where ResultType != 0
| where not(IPAddress startswith "10.0.")

4. Leverage Case-Insensitivity Where Possible

By default, string comparisons in KQL are case-insensitive. However, if you are performing a search and you know the data is consistently formatted (e.g., all lowercase), you can use the == operator for a slight performance gain over case-insensitive operators like contains.


Not read yet

Comparison: Filtering and Shaping Operators

It is important to understand how different operators compare when you are trying to manipulate your data. Below is a quick reference guide to help you choose the right tool for the job.

Operator Purpose Best Used For
where Row-level filtering Reducing data volume based on specific criteria.
project Column selection/renaming Defining the final output structure.
project-away Column removal Removing noise while keeping most data.
extend Adding columns Calculating new values based on existing data.
take Row sampling Quick "peek" at the data structure.
limit Row limiting Capping results for performance or display.

Common Pitfalls and How to Avoid Them

Even experienced analysts fall into traps when writing KQL. Being aware of these common mistakes will save you hours of debugging time.

Trap 1: The "Order Matters" Mistake

New users often assume that the order of operators doesn't matter as long as they get the data they want. This is false. The order of operators determines the efficiency of the query. If you perform a complex transformation (like extend or parse) on a million rows, and then filter it down to 10 rows with where, you have wasted significant processing power. Always filter first, then transform.

Trap 2: Incorrect String Matching

KQL provides several ways to match strings: ==, contains, has, startswith, and matches regex.

  • has is highly optimized for looking for whole words.
  • contains is slower because it looks for substrings anywhere.
  • startswith is very fast because it only checks the beginning of the string. Using contains when you could have used has or startswith is a common performance bottleneck.

Trap 3: Ignoring Data Types

KQL is strongly typed. If you try to compare a string to an integer, the query will fail. For example, where ResultType == "0" will fail because ResultType is a numeric column. You must use where ResultType == 0. Always check the schema of your table if you are unsure about the data type of a column.


Not read yet

Step-by-Step: Constructing a Real-World Investigation Query

Let’s put everything together in a practical, step-by-step example. Suppose we want to investigate potential brute-force attacks on our user accounts.

Step 1: Define the scope. We only care about the last 7 days.

SigninLogs
| where TimeGenerated > ago(7d)

Step 2: Filter for failures. We want to see only sign-in failures.

SigninLogs
| where TimeGenerated > ago(7d)
| where ResultType != 0

Step 3: Group by User. We want to see which users are failing the most. We will use summarize here (a topic for another lesson, but essential for this flow).

SigninLogs
| where TimeGenerated > ago(7d)
| where ResultType != 0
| summarize FailureCount = count() by UserPrincipalName

Step 4: Refine the output. We only want to see users with more than 50 failures.

SigninLogs
| where TimeGenerated > ago(7d)
| where ResultType != 0
| summarize FailureCount = count() by UserPrincipalName
| where FailureCount > 50

Step 5: Present the data. Finally, we use project to ensure the report is clean.

SigninLogs
| where TimeGenerated > ago(7d)
| where ResultType != 0
| summarize FailureCount = count() by UserPrincipalName
| where FailureCount > 50
| project Account = UserPrincipalName, Attempts = FailureCount
| sort by Attempts desc

This query is clean, efficient, and provides an actionable list of accounts that might be under attack.


Not read yet

Advanced Nuances: Handling Dynamic Data

Modern logs often contain dynamic data, such as JSON blobs stored in a "Properties" or "Details" column. KQL handles these with the bag_pack or extract functions. While these are advanced topics, the project operator is often the final step in extracting these values into readable columns.

For instance, if you have a Properties column containing JSON, you might use:

SigninLogs
| extend DeviceName = tostring(parse_json(DeviceDetail).displayName)
| project TimeGenerated, UserPrincipalName, DeviceName

Here, we use extend to pull a specific value out of the JSON blob, and project to clean up the table so the user doesn't have to look at the raw JSON string.


Frequently Asked Questions (FAQ)

Q: Can I use where on a column I just created with extend? A: Yes! KQL queries are processed in a pipeline. Any column created by an extend or project operation is available for use by subsequent operators in the query.

Q: Is project case-sensitive for column names? A: Yes, column names in KQL are case-sensitive. If your table has a column named TimeGenerated, you cannot refer to it as timegenerated. Always check your schema explorer to ensure you are using the correct casing.

Q: What is the difference between take and limit? A: In KQL, take and limit are identical. They are aliases for the same operator. You can use whichever you prefer, though limit is often more intuitive to those coming from a SQL background.

Q: Does the order of columns in project matter? A: Yes. The columns will appear in your output table in the exact order you list them in the project operator. It is good practice to put the most important information (like TimeGenerated or User) in the leftmost columns.


Not read yet

Best Practices Checklist

  • Time-first: Always filter by TimeGenerated immediately.
  • Filter-first: Apply where before performing expensive operations like summarize or join.
  • Be explicit: Use project to name specific columns rather than using *.
  • Watch the types: Ensure you are comparing strings to strings and numbers to numbers.
  • Comment: Document your intent so others can follow your logic.
  • Clean up: Use project-away if you have a massive table and only want to drop a few columns.
  • Test: Run your query on a small time window before running it against a large one to ensure the logic is correct.

Key Takeaways

  1. The Pipeline Model: Remember that KQL is a pipeline. Data flows from the source table through various operators, and each operator transforms that data. The output of one operator becomes the input for the next.
  2. Filtering Efficiency: The where operator is your primary tool for reducing data volume. By filtering early, you improve query performance and reduce the risk of hitting resource limits in Sentinel.
  3. Data Shaping: The project operator is essential for creating clean, readable, and professional reports. Never show more data than is necessary for the task at hand.
  4. Strategic Use of extend: Use extend to perform calculations and data transformations, and use project to finalize the output structure. This separation of concerns makes your code much easier to debug.
  5. Performance Matters: Avoid using contains when has or startswith will suffice. Always be mindful of the data types you are comparing to prevent errors and ensure the engine can optimize your query.
  6. Maintainability: Treat your KQL queries as code. Use comments, consistent indentation, and explicit column naming to ensure that your work is maintainable and understandable by your team.
  7. Iterative Development: Don't try to write a complex query in one go. Build it step-by-step, starting with the table, adding filters, then summarizations, and finally the projection.

By mastering the where and project operators, you are building the foundation of a highly effective security operations workflow. These operators allow you to move from being overwhelmed by data to being in total control of it. As you continue your journey in Microsoft Sentinel, you will find that these two operators remain your most frequent companions, providing the clarity and focus needed to secure your environment effectively.

Not read yet

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