Union and Join Operators
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 8 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Building Multi-Table Statements in KQL: Mastering Union and Join
Introduction: Why Multi-Table Logic Matters in Security Operations
In the world of Microsoft Sentinel, data is rarely stored in a single, convenient location. Security telemetry comes from a vast array of sources—firewalls, identity providers, cloud infrastructure, and endpoint detection systems—each landing in its own dedicated table within your Log Analytics workspace. As a security analyst or detection engineer, your job is to correlate these disparate data points to uncover complex attack patterns. If you only look at one table at a time, you are only seeing a tiny fraction of the story.
This is where the power of multi-table operators comes into play. By using union and join, you can bridge the gaps between these tables, creating a unified view of your environment. Whether you are trying to track a lateral movement attempt that jumps from an Office 365 login to a local workstation process execution, or you are simply trying to aggregate logs from multiple regional workspaces, these operators are the primary tools in your arsenal. Mastering them is not just about writing more complex queries; it is about significantly reducing your mean time to detect (MTTD) by ensuring no piece of evidence is left behind.
In this lesson, we will peel back the layers of how union and join function within Kusto Query Language (KQL). We will move beyond the basic definitions and explore how to handle schema mismatches, optimize performance for large datasets, and avoid the common pitfalls that lead to slow or inaccurate detection logic.
Not read yet
The Union Operator: Combining Data Streams
The union operator is conceptually simple: it takes two or more tabular expressions and returns a single table containing all the rows from each of the inputs. Think of it as stacking tables on top of each other. If you have a SigninLogs table and an AADNonInteractiveUserSignInLogs table, and you want to analyze all sign-in activity in one go, union is your primary tool.
Basic Syntax and Usage
The most straightforward way to use union is to list the tables you want to combine. KQL will attempt to align columns that share the same name and data type, filling in empty values (nulls) for columns that exist in one table but not the other.
union SigninLogs, AADNonInteractiveUserSignInLogs
| summarize count() by ResultType
In the example above, KQL takes every row from both tables and creates a unified result set. If SigninLogs has a column called IPAddress and AADNonInteractiveUserSignInLogs also has IPAddress, these will be merged into a single column in the output. If one table has a column called AppDisplayName and the other does not, the resulting table will contain that column, but the rows originating from the table lacking the column will show empty values.
Handling Schema Mismatches
One of the most common challenges with union is dealing with different schemas. If you are unioning tables that have very different column structures, you might end up with a result set that is sparse and difficult to read. You can use the kind parameter to control how the union behaves.
union kind=inner: Only includes columns that are common to all input tables. This is useful when you only care about specific fields that you know exist across all your data sources.union kind=outer: This is the default behavior. It includes all columns from all tables, filling in nulls where data is missing.
Callout: Union vs. Join It is common for beginners to confuse these two. Remember the "Stack vs. Side-by-Side" rule.
Unionstacks tables vertically, increasing the number of rows.Joinplaces tables side-by-side horizontally, increasing the number of columns. Useunionwhen you have similar data in different places. Usejoinwhen you have different data that shares a common key.
Advanced Union Techniques: Wildcards and Queries
You are not limited to just table names. You can use wildcards to select multiple tables at once, which is incredibly powerful when dealing with workspace-level logging or partitioned data.
union SecurityEvent, Syslog
| where TimeGenerated > ago(1h)
| where EventID == 4624
You can even use union on the results of sub-queries. This allows you to perform some preliminary filtering or transformation on individual tables before combining them, which can significantly improve performance by reducing the amount of data processed in the final merge.
let successfulLogins = SigninLogs | where ResultType == 0 | project TimeGenerated, UserPrincipalName;
let failedLogins = SigninLogs | where ResultType != 0 | project TimeGenerated, UserPrincipalName;
union successfulLogins, failedLogins
| summarize count() by UserPrincipalName
Not read yet
The Join Operator: Correlating Related Data
While union is for stacking, join is for correlating. A join combines rows from two tables based on a matching value in a specific column—the "join key." This is the cornerstone of behavioral analysis, such as linking a specific process ID to a user account or matching a network connection to a specific host.
Understanding Join Flavors
KQL supports several types of joins, each serving a specific logic in your investigations. Understanding these is critical because choosing the wrong one can lead to missing data or "fan-out" issues where your results multiply unexpectedly.
inner(default): Returns only rows that have a match in both tables. If a row in the left table doesn't have a corresponding match in the right table, it is discarded.leftouter: Returns all rows from the left table, and the matching rows from the right table. If there is no match, the right-side columns will contain nulls. This is the most common choice for security investigations because you usually want to keep the primary event (e.g., a process execution) even if you can't find a corresponding metadata event.rightouter: The opposite ofleftouter. It keeps all rows from the right table and matches them with the left.fullouter: Returns all rows when there is a match in either the left or right table.leftanti: Returns rows from the left table that have NO match in the right table. This is incredibly useful for finding "missing" events, such as seeing a login that never had a corresponding logoff.
Practical Join Example: Correlating Processes with Users
Let’s look at a common scenario: you have a process execution event, but you need to know the identity of the user associated with that process. You might have one table for SecurityEvent (processes) and another for IdentityInfo (user metadata).
SecurityEvent
| where EventID == 4688
| join kind=leftouter (
IdentityInfo
| project AccountUPN, GroupMembership
) on $left.Account == $right.AccountUPN
In this query, we take the process execution events and "decorate" them with information from the IdentityInfo table. By using leftouter, we ensure that even if we don't have metadata for a specific user, we still see the process execution event. If we had used an inner join, any process execution where the user wasn't in our IdentityInfo list would have been dropped from the results entirely, potentially hiding an important alert.
Warning: The "Join Fan-Out" Trap Be extremely careful with joins where the join key is not unique in the right-hand table. If you join on
Computerand the right-hand table has 100 rows for that same computer, your result set will explode in size, as each row from the left table will be duplicated for every match found on the right. Always verify that your join key is unique on at least one side, or usesummarizeto condense the right-hand table before joining.
Step-by-Step: Joining Data for Threat Hunting
When performing a manual investigation, follow these steps to ensure your join is efficient and accurate:
- Filter First: Always filter your tables as much as possible before performing the join. If you are looking for events from the last hour, apply the
where TimeGenerated > ago(1h)filter to both sides of the join. - Project Only Necessary Columns: Joins are memory-intensive. Do not join entire tables. Use the
projectoperator to select only the columns you absolutely need for the correlation. - Choose the Right Key: Ensure the join key is consistent. If one table stores a username as
domain\userand the other as[email protected], you will need to useextendto normalize the strings before attempting the join. - Execute and Validate: Run the query and check the row count. If the row count is significantly higher than your input tables, you have likely encountered a "fan-out" and need to rethink your join key or aggregation strategy.
Not read yet
Comparison Table: Union vs. Join
| Feature | Union | Join |
|---|---|---|
| Primary Goal | Combining data of the same type | Correlating data of different types |
| Result Structure | Adds more rows (vertical) | Adds more columns (horizontal) |
| Key Requirement | No key required | Requires a common join key |
| Common Use Case | Aggregating logs from multiple sources | Linking events to entities (users/hosts) |
| Performance Impact | Generally low overhead | Potentially high, depends on memory |
Best Practices and Industry Standards
1. Optimize for Memory
KQL runs in a distributed environment, but individual queries are constrained by memory limits. When joining, the right-hand side of the join is loaded into memory. If you are joining two massive tables, the query will fail or time out. Always prioritize the smaller table on the right side of the join. If both tables are massive, consider using lookup (if you are doing a simple enrichment) or pre-aggregating the data.
2. Use lookup for Simple Enrichment
If you are only trying to add a few fields from a small reference table (like a list of known malicious IPs) to a large telemetry table, use the lookup operator instead of join. lookup is optimized for this exact use case and is generally faster and more memory-efficient than a standard join.
// Using lookup for enrichment
let MaliciousIPs = datatable(IPAddress:string, ThreatIntel:string)
["1.2.3.4", "Known Botnet", "5.6.7.8", "Known C2"];
SigninLogs
| lookup MaliciousIPs on IPAddress
| where isnotempty(ThreatIntel)
3. Normalize Data Before Joining
Data quality is the greatest enemy of successful correlation. Security logs often contain variations of the same information. Before joining on a username, ensure both sides are converted to lowercase using tolower(). Before joining on an IP address, ensure you aren't trying to match a string to an integer.
4. Leverage the let Statement
Complex queries become unreadable and difficult to debug if you nest too many joins. Use let statements to define your data chunks clearly. This makes your code modular and allows you to test each piece of the logic independently before putting it all together.
Not read yet
Common Pitfalls and How to Avoid Them
The "Missing Data" Pitfall
The most common mistake is using an inner join when a leftouter join was required. An inner join acts as a filter. If you join your SecurityEvent table with a UserWatchlist table and use an inner join, your query will only return events for users who are currently on the watchlist. If you wanted to see all events and flag the ones involving watchlist users, you must use a leftouter join.
The "Time Window" Mismatch
When joining two tables based on time-related events, analysts often forget that the events might not happen at the exact same millisecond. If you are trying to correlate a "Process Start" with a "Network Connection," they will have different TimeGenerated timestamps. If you try to join on TimeGenerated, you will get zero results. Instead, join on a shared identifier like ProcessId or CorrelationId, and use where clauses to ensure the events occur within a reasonable time window of each other.
Querying Too Much Data
A common "newbie" error is to run union * or join without any time filters. In a large environment, this will scan petabytes of data, causing your query to time out or, worse, impacting the performance of the entire Sentinel workspace. Always, always apply a TimeGenerated filter as the very first step in your query.
Tip: Use the
summarizeOperator Before Joining If you have a table with millions of rows, trying to join it directly will likely fail. Usesummarizeto collapse the data into a smaller set of unique keys before joining. For example, if you are joining process logs with user info, summarize the process logs to get a unique list of users first, then join that list with the user metadata.
Not read yet
Advanced Scenarios: Multi-Table Logic in Action
Scenario 1: Cross-Workspace Hunting
In many organizations, security data is spread across multiple Log Analytics workspaces. You can use the union operator to query across these boundaries.
union workspace("SecurityWorkspace1").SecurityEvent, workspace("SecurityWorkspace2").SecurityEvent
| where EventID == 4625
| summarize count() by Account, bin(TimeGenerated, 1h)
This query effectively creates a single, global view of failed logins across your entire enterprise, regardless of where the data is physically stored.
Scenario 2: Detecting Lateral Movement
Lateral movement often involves a sequence of events: a login, followed by a process execution, followed by a network connection. To detect this, you might need to join multiple tables in a chain.
let Logins = SigninLogs | where ResultType == 0 | project TimeGenerated, UserPrincipalName, IPAddress;
let Processes = SecurityEvent | where EventID == 4688 | project TimeGenerated, Account, ProcessName;
Logins
| join kind=inner (Processes) on $left.UserPrincipalName == $right.Account
| where Processes.TimeGenerated > Logins.TimeGenerated
| where Processes.TimeGenerated < Logins.TimeGenerated + 1h
This query links a successful login to a process execution that happened within the following hour. By chaining these operators, you build a "story" of the attack.
Not read yet
Quick Reference: Join Types at a Glance
| Join Type | Logic | When to use |
|---|---|---|
inner |
Intersection of both sets | When you only want matches. |
leftouter |
Everything on the left + matches on the right | When you want to preserve the primary event. |
leftanti |
Everything on the left that has NO match on the right | When looking for anomalies or missing logs. |
fullouter |
Union of all rows with matches merged | Rarely used, but helpful for complete data reconciliation. |
Frequently Asked Questions (FAQ)
Q: Why is my join query taking so long to run? A: Most likely, you are joining too much data. Check if you have applied filters to both sides of the join. If you are joining on a column with low cardinality (few unique values), the join operation is much more expensive. Ensure you are projecting only the columns you need.
Q: Can I join more than two tables?
A: Yes, you can chain joins. However, each join adds complexity and memory usage. If you need to join four or five tables, consider using let statements to perform them in stages, or check if you can use union to combine some of your data sources before performing a single join.
Q: What happens if the join key column has null values?
A: Null values do not match other null values in KQL. If you have nulls in your join key, those rows will be dropped in an inner join. If you need to include them, you must handle them explicitly, perhaps by using coalesce() to provide a default value before the join.
Q: Is lookup always better than join?
A: lookup is faster and easier for simple enrichment (adding columns from a small table to a large one). join is more flexible and supports more complex logic (like leftanti or fullouter). Use lookup when you can, and join when you must.
Not read yet
Key Takeaways
- Union is for Stacking: Use
unionwhen you want to combine logs from multiple tables that share a similar purpose or schema. It is your primary tool for global visibility. - Join is for Correlating: Use
joinwhen you need to connect two different types of data, such as connecting a process execution to a user identity. - Filter First, Join Later: Always filter your data as much as possible before performing a
join. This reduces the memory footprint and speeds up the query significantly. - Mind the "Fan-Out": Be aware that joining on non-unique keys can result in a massive, unintended increase in row count. Always check your data cardinality before joining.
- Prefer
leftouterfor Security: When performing investigations,leftouteris safer thaninnerbecause it ensures you don't accidentally discard the primary evidence just because a metadata match was missing. - Use
lookupfor Enrichment: For simple data decoration—like adding threat intel tags to IP addresses—lookupis a more performant alternative tojoin. - Normalize Your Keys: Always ensure your join keys are consistent (e.g., matching casing, removing leading/trailing spaces) to avoid failed correlations.
By mastering these two operators, you transition from being a passive consumer of logs to an active hunter of threats. The ability to stitch together information from across your environment is what separates high-performing security operations teams from the rest. Continue practicing these queries in your lab environment, and you will soon find that complex multi-table logic becomes second nature.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
- Investigate Security Incidents
- Investigate Security Incidents Quiz5q
- Manage Incidents in Defender Portal
- Manage Incidents in Defender Portal Quiz5q
- Investigate Alerts and Alert Queues
- Investigate Alerts and Alert Queues Quiz5q
- Automated Investigation and Response
- Automated Investigation and Response Quiz5q
Spend your points to unlock exam-style practice questions
Spend points to unlock SC-200 exam-style practice questions.
Practice for SC-200