# Hunting query

> Source: Courseiva IT Certification Glossary — https://courseiva.com/glossary/hunting-query

## Quick definition

In everyday IT security, a hunting query is like a custom search you write to find suspicious activity that automated alerts might miss. Instead of waiting for an alarm, you actively dig through logs, emails, and network data to spot potential attacks before they cause damage. Security analysts use these queries to track down advanced threats, like a detective following clues across multiple systems.

## Simple meaning

Imagine you are a security guard at a large office building. Normally, you rely on motion sensors and door alarms to tell you when something is wrong. But a really clever burglar might know how to avoid those sensors. So, sometimes you decide to walk around yourself, checking every hallway, every room, and every window, looking for anything out of place. That proactive patrol is exactly what a hunting query does in cybersecurity.

A hunting query is a special command you write in a language called Kusto Query Language (KQL). You run it inside tools like Microsoft 365 Defender or Azure Sentinel. Instead of waiting for an alert to pop up, you ask the system a specific question. For example, you might ask, "Show me all the times a user logged in from a country they have never visited before." Or, "Find all emails sent to people in accounting that contain a zip file attachment." The query sifts through millions of log entries, emails, and network events in seconds to find those matches.

This is different from a simple search because hunting queries are often very detailed and chained together. You might run one query, find a suspicious device, then run another query on that device to see what files it downloaded, and then run a third query to check if those files were opened on other computers. It is a step-by-step investigation that follows the trail of an attacker. The goal is to catch threats that are hiding in plain sight, like a hacker who uses a legitimate software tool to steal data or a phishing email that looks exactly like a real company message. By writing hunting queries, security analysts turn passive waiting into active searching, making the whole network much harder to breach.

## Technical definition

A hunting query is a Kusto Query Language (KQL) expression designed to search for specific patterns, anomalies, or indicators of compromise (IoCs) across large datasets in a Security Information and Event Management (SIEM) or Extended Detection and Response (XDR) platform. In the Microsoft ecosystem, these queries are executed in Microsoft 365 Defender (which covers endpoints, email, identity, and cloud apps) and Azure Sentinel (a cloud-native SIEM).

The core components of a hunting query include data sources (tables), filters, time ranges, joins, and aggregations. Common tables in Microsoft 365 Defender include DeviceEvents, DeviceLogonEvents, EmailEvents, IdentityLogonEvents, and AADSignInEvents (Azure Active Directory sign-ins). In Azure Sentinel, tables come from various connectors like SecurityEvent, CommonSecurityLog, and custom logs.

A hunting query typically starts by defining a time window using the ‘where Timestamp’ clause. Then it applies filters to narrow down the data, such as filtering for specific user accounts, IP addresses, process names, or event types. For example, a query looking for lateral movement might join DeviceLogonEvents (logins on different machines) with DeviceNetworkEvents (outbound connections) to find a user logging into a server and then immediately making a connection to an external IP.

Advanced hunting queries often use functions like summarize (to count occurrences), make_set (to create arrays of distinct values), and bin (to group events by time). The query can also incorporate threat intelligence by joining against external threat feeds or using built-in detection functions like detectEndgameMalware() or it_has_ipv4() to check for known malicious indicators.

In practice, security analysts build hunting queries iteratively. They start with a broad hypothesis ("Is there any unusual PowerShell usage?") and then refine the query based on results. They may use the ‘take’ operator to preview a small sample of results before running the full query across gigabytes of data. The results are often visualized in a timeline or exported as a CSV for further analysis. Microsoft also provides a library of pre-built hunting queries in the "Threat Analytics" section, which are updated with each new campaign or vulnerability disclosure.

The performance of a hunting query depends on the indexed columns and the size of the data. Queries that use time range filters and indexed columns (like Timestamp, DeviceId, or AccountUpn) run much faster. Analysts must also consider data retention policies, Microsoft 365 Defender typically retains data for 30 days, while Azure Sentinel can retain data for up to two years depending on the tier. Understanding these limits is critical for historical hunting.

Real-world implementation often involves multiple hunting queries combined into a hunting “playbook.” For example, a playbook for investigating a suspected data exfiltration might include queries for large file uploads, unusual outbound network connections, and changes to file permissions. Each query feeds into the next, building a complete picture of the attack. Sophisticated teams automate this process using Azure Sentinel’s Logic Apps or Microsoft 365 Defender’s automated investigation and response (AIR) capabilities, but the core of the investigation remains the hunting query itself.

## Real-life example

Think about a busy airport security team. They have cameras, metal detectors, and alarms that automatically alert them to weapons or suspicious bags. But a very skilled smuggler might not set off any alarms. They could hide something in a normal-looking suitcase, wear clothing that doesn’t alarm the scanner, and walk right through. The security team knows this, so they do something extra: they watch the behavior of passengers.

A security officer might look at a camera feed of the departure lounge and notice a person who keeps looking around nervously, changes seats every few minutes, and avoids eye contact. That officer is running a “hunting query” in their mind. They are not waiting for an alarm; they are actively searching for unusual behavior patterns. Then they might cross-reference that person’s ticket purchase history (paid with cash?), their checked bag (very heavy?), and their travel history (recently visited a high-risk country?). Each piece of information is like a new query that narrows down the investigation.

In cybersecurity, this is exactly what a security analyst does with hunting queries. They don’t wait for an antivirus alert or a firewall block. Instead, they look for patterns: a user logging in from two continents in 10 minutes, a computer sending a huge amount of data at 3 AM, or an employee accessing a server they have never touched before. Each hunting query is like the security officer’s mental question: “Show me all the people who bought a ticket with cash, traveled from Country X, and are now sitting near the gate.”

The analogy works because both cases require proactive thinking. The airport officer doesn’t catch every smuggler, but by hunting, they catch threats that automation misses. Similarly, a hunting query doesn’t guarantee finding every attack, but it dramatically increases the chance of detecting advanced, stealthy threats that evade automated rules.

## Why it matters

Hunting queries are essential because modern cyberattacks are designed to bypass traditional security tools. Attackers use legitimate tools like PowerShell, PsExec, and common software to blend in with normal activity. A typical antivirus or firewall cannot distinguish between a system administrator running a backup script and a hacker using the same script to copy data. Automated alerts are also limited: they only fire when a specific rule matches, and that rule is often known to attackers who can avoid it. Hunting queries close this gap by enabling human analysts to use their intuition and knowledge of the environment to detect the unknown.

In practical IT terms, hunting queries turn raw data into actionable intelligence. For instance, a company might have millions of log entries per day. Without hunting queries, that data is just noise. With them, an analyst can ask specific questions like “Show me all the times a domain admin’s credentials were used to log into a workstation that is not a server” or “Find any email that was sent to an external address with an attachment larger than 10 MB.” These are the exact scenarios that lead to detecting ransomware, phishing, or data exfiltration.

hunting queries are a core part of threat intelligence. When a new vulnerability is announced (like a zero-day in Exchange Server), security vendors release sample hunting queries to help customers check if they have been compromised. Organizations that have a mature hunting program can run these queries within hours, while others have to wait for a patch or an automated detection update. This speed can be the difference between containing a breach and suffering a full-scale incident.

Finally, hunting queries empower security teams to validate their security controls. By actively looking for signs of malware or misconfigurations, teams can identify gaps in their detection rules and firewalls. If you run a hunting query for brute-force attacks and find no results, but you know there has been a recent spike in failed logins, your query or data source might be broken. This feedback loop helps improve the overall security posture of the organization.

## Why it matters in exams

Hunting queries are most relevant for the Microsoft security-focused exams, especially the SC-200 (Microsoft Security Operations Analyst) and SC-900 (Microsoft Security, Compliance, and Identity Fundamentals) at a foundational level. The SC-200 exam specifically includes a domain called “Investigate threats using Microsoft 365 Defender” and “Investigate threats using Azure Sentinel,” both of which heavily emphasize writing and analyzing KQL hunting queries. In this exam, you can expect questions that ask you to identify the correct query syntax to find a specific event, interpret the output of a given query, or describe the purpose of a query component.

For the SC-900 exam, hunting queries appear mainly in the context of Microsoft 365 Defender’s capabilities. You need to know what advanced hunting is, that it uses KQL, and that it allows proactive search for threats. The exam may present a scenario where a security analyst wants to search for a suspicious pattern, and you must choose the correct tool (advanced hunting) from a list of options.

The exam objectives for SC-200 list “Detect threats using advanced hunting queries” as a specific skill. This means you are expected to understand KQL operators like `where`, `summarize`, `join`, `extend`, `project`, and `take`. You must also be able to read a query and understand what it is doing. Typical question types include multiple-choice where a query is shown and you must select the correct description of its result, or a drag-and-drop where you must arrange query clauses in the correct order.

Beyond SC-200 and SC-900, hunting queries also show up in Azure-related exams like AZ-500 (Microsoft Azure Security Technologies) and MS-500 (Microsoft 365 Security Administration). In these, the focus is more on understanding the hunting workflow and integrating it with other security tools. For example, you might be asked how to export hunting results to a third-party SIEM or how to set up automated investigation rules based on a hunting query.

For general IT certifications like CompTIA Security+, the term “hunting” appears in the context of threat hunting methodology, but not specifically KQL. The exam may ask you to differentiate between passive monitoring and active hunting. However, for those pursuing the Microsoft track, mastering hunting queries is not just helpful, it is required to pass.

## How it appears in exam questions

In the SC-200 exam, questions about hunting queries often fall into three categories: scenario-based, query interpretation, and configuration.

Scenario-based questions give you a real-world incident and ask you to select the correct hunting query to investigate it. For example, a question might say: “A user reports seeing unusual outbound traffic from their machine. You suspect a remote access trojan that communicates via HTTP to a command-and-control server. Which hunting query would you run?” Then four KQL snippets are provided as answer choices. You need to choose the one that correctly filters for outbound traffic, on the specific device, with a suspicious destination IP, and within the relevant time window.

Query interpretation questions show you a complete hunting query and ask you to explain its purpose or output. For instance: 
```
DeviceProcessEvents
| where Timestamp > ago(7d)
| where FileName == "cmd.exe" and ProcessCommandLine has "whoami"
| project Timestamp, DeviceName, AccountName, ProcessCommandLine
```
The answer might be: “This query finds all instances across all devices in the last 7 days where cmd.exe was used to run the ‘whoami’ command, which may indicate a user testing their privileges before trying to escalate.”

Configuration questions ask you to set up advanced hunting in Azure Sentinel or Microsoft 365 Defender. For example: “You want to run a query that searches for failed logon attempts from IP addresses outside your organization’s allowed country list. What should you configure first?” The answer might involve enabling the option to store raw event data or creating a watchlist of allowed IPs.

Another common pattern is the “multiple response” question where you must select two or three correct statements about advanced hunting. For example: “Which of the following are true about hunting queries in Microsoft 365 Defender? (Choose all that apply)” Options might include statements about data retention, the use of KQL, the ability to schedule queries, and the lack of support for custom detection rules. You must know that hunting queries can be saved and reused, but they are not scheduled by default (you need custom detections for that).

Finally, there are “troubleshooting” questions. A query returns unexpected results (too many or too few records). The question asks what to modify: adjust the time range, check the column names, or ensure the data source is connected. For example, if a query returns no results, the answer might be that the data retention period has expired for the required table.

## Example scenario

Imagine you are a security analyst at a mid-sized company that uses Microsoft 365. One morning, the HR manager calls you and says that an employee, Sarah, has been behaving oddly, she is asking coworkers for their login passwords, which is completely against company policy. You suspect someone may have compromised Sarah’s account or that Sarah herself might be doing something malicious.

You open Microsoft 365 Defender and go to the Advanced Hunting section. Instead of just checking the recent alerts, you decide to write a hunting query to dig deeper. First, you want to see if Sarah’s account has been used from unusual locations. You write:
```
AADSignInEventsBeta
| where AccountUpn == "sarah@company.com"
| where Timestamp > ago(7d)
| project Timestamp, IPAddress, City, Country, IsInteractive
```
The results show logins from the office city, but also one login from an IP address in a country she has never visited. That is a red flag.

Now you want to check if that suspicious IP address was used to access any other accounts or systems. You run a second query:
```
AADSignInEventsBeta
| where IPAddress == "185.220.101.44" // the suspicious IP
| project Timestamp, AccountUpn, ClientAppUsed
```
You find out that the same IP also tried to log into the CEO’s account, but failed because the CEO has multi-factor authentication (MFA). This suggests a targeted brute-force or credential-stuffing attack.

Next, you want to see if Sarah’s machine has any suspicious processes running. You query DeviceProcessEvents:
```
DeviceProcessEvents
| where DeviceName == "SARAH-PC"
| where Timestamp > ago(7d)
| where ProcessCommandLine contains "powershell" or ProcessCommandLine contains "wget"
| project Timestamp, FileName, ProcessCommandLine
```
The results show that an unknown script was downloaded using PowerShell from a URL that looks suspicious. Now you have a clear evidence chain: a compromised account, an attempted lateral move, and a malicious script. You escalate this to the incident response team. All of this was possible because you actively hunted with queries instead of waiting for an alert to tell you something was wrong.

## Common mistakes

- **Mistake:** Not using a time range filter in the query.
  - Why it is wrong: Without a time filter, the query may scan all historical data, which can be extremely slow and may return irrelevant results from years ago. It can also cause the query to time out or consume excessive resources.
  - Fix: Always add a `where Timestamp > ago(<number>d)` clause to limit the search to a relevant period, such as the last 7 days.
- **Mistake:** Confusing table names between Microsoft 365 Defender and Azure Sentinel.
  - Why it is wrong: Tables like DeviceLogonEvents exist in Microsoft 365 Defender but have different names or schemas in Azure Sentinel (e.g., SecurityEvent or SigninLogs). Using the wrong table causes the query to return zero results or errors.
  - Fix: Verify which platform you are querying and use the correct table schema. In Microsoft 365 Defender, use the defender-specific table names listed in the advanced hunting schema.
- **Mistake:** Forgetting to use `project` to limit columns in the output.
  - Why it is wrong: By default, KQL returns all columns from the table, which can be overwhelming and difficult to read. It also increases data transfer and may hit result size limits.
  - Fix: After filtering, always use `project` to select only the columns you need, such as Timestamp, DeviceName, and AccountUpn.
- **Mistake:** Using `contains` instead of `has` for exact string matching.
  - Why it is wrong: The `contains` operator is case-insensitive and will match partial strings, potentially returning many false positives. For example, `FileName contains "notepad"` would also match “notepad++.exe” or “notepadHelper.dll”.
  - Fix: Use `has` for whole-word matches or `matches regex` for precise pattern matching. Use `==` when you know the exact file name.
- **Mistake:** Ignoring data retention limits when hunting for old events.
  - Why it is wrong: A query searching for events older than 30 days in Microsoft 365 Defender will return no results because data is only retained for 30 days. Analysts may incorrectly conclude there are no threats, when the data simply does not exist.
  - Fix: Always check the retention period for the table you are querying. Use Azure Sentinel for longer-term hunting if needed.

## Exam trap

{"trap":"A question asks which tool to use to proactively search for threats across email, endpoints, and identities. Learners see options like “Azure Sentinel,” “Microsoft 365 Defender,” “Microsoft Defender for Cloud,” and “Microsoft Secure Score.” Many choose Azure Sentinel because it is a SIEM and seems like the obvious answer for searching logs.","why_learners_choose_it":"Azure Sentinel is a powerful SIEM that can also run hunting queries, but the question specifically says “across email, endpoints, and identities” which is the exact scope of Microsoft 365 Defender’s unified advanced hunting. Learners often associate all hunting with Azure Sentinel because it is marketed as a SIEM, while Microsoft 365 Defender’s hunting is an XDR feature.","how_to_avoid_it":"Read the question carefully: if it mentions multiple domains (email, endpoint, identity) and does not mention a third-party data source, it is referring to Microsoft 365 Defender’s built-in hunting. Also, know that Azure Sentinel is for collecting logs from various sources including third-party, while Microsoft 365 Defender specifically focuses on Microsoft 365 data. The correct answer is “Advanced hunting in Microsoft 365 Defender.”"}

## Commonly confused with

- **Hunting query vs KQL (Kusto Query Language):** KQL is the language you use to write hunting queries. Think of KQL as the grammar and vocabulary, while the hunting query is the actual sentence you write in that language. You cannot have a hunting query without using KQL, but KQL alone is just a language used for many other purposes like Azure Data Explorer analytics. (Example: If KQL is the English language, then a hunting query is a specific question like “Show me all the failed logins from Russia.”)
- **Hunting query vs Custom detection rule:** A custom detection rule is a saved hunting query that runs automatically on a schedule. While a hunting query is run manually by an analyst for one-time investigation, a custom detection rule runs every few minutes and creates incidents when it matches. Hunting queries are ad hoc; custom detections are automated. (Example: You write a query to check for suspicious logins manually during an incident, that’s hunting. You then save that same query as a rule to run every hour and alert you automatically, that’s a custom detection.)
- **Hunting query vs Threat intelligence indicator:** A threat intelligence indicator (IOC) is a specific piece of data like an IP address, URL, or file hash known to be malicious. A hunting query can use IOCs as filters (e.g., “where IPAddress in (list_of_bad_ips)”), but the query itself is the search mechanism, not the indicator. IOCs are the clues; the hunting query is the detective. (Example: If you have a list of known bad domains, that list is threat intelligence. A hunting query that checks your network logs against that list is the hunting query.)

## Step-by-step breakdown

1. **Formulate a hypothesis** — Start with a question or suspicion about a possible attack. For example, “Could an attacker be using PowerShell to download malware?” This hypothesis guides what data and filters you will use.
2. **Identify relevant data tables** — Based on your hypothesis, choose the correct tables. For PowerShell activity, use DeviceProcessEvents in Microsoft 365 Defender. For email phishing, use EmailEvents. Choosing the right table ensures you search in the right dataset.
3. **Write the initial query with filters** — Construct the KQL query using `where` clauses to filter by time range, device, user, process name, or other criteria. For example: `DeviceProcessEvents | where Timestamp > ago(7d) | where FileName == "powershell.exe"`.
4. **Run the query and analyze results** — Execute the query and review the results. Look for anomalies, such as PowerShell being launched by a non-admin user or at unusual hours. If the results are too broad, refine the filters.
5. **Refine and pivot** — Based on initial findings, modify the query to dig deeper. Use `join` to correlate with other tables, like joining DeviceProcessEvents with DeviceNetworkEvents to find the IP addresses the process connected to.
6. **Document and share findings** — If a threat is confirmed, document the query used and the results. Save the query for future use or convert it into a custom detection rule. Share the findings with the incident response team.

## Practical mini-lesson

To become proficient with hunting queries, start by exploring the built-in sample queries provided by Microsoft. In Microsoft 365 Defender, go to “Advanced Hunting” and look at the “Queries” tab; there are hundreds of pre-written queries covering various attack scenarios. Run them and study how they work. Change the time range from 7 days to 1 day to see how results shrink, or modify a filter to see how output changes.

A practical task is to write a query that detects “pass-the-hash” attacks. This attack uses stolen NTLM hashes to authenticate. In KQL, you would look for logon events with LogonType == 3 (network logon) and where the same account appears from multiple source workstations within a short time. A sample query:
```
DeviceLogonEvents
| where Timestamp > ago(1d)
| where LogonType == 3
| summarize LogonCount = dcount(DeviceName) by AccountUpn
| where LogonCount > 5
```
This query finds accounts that logged into more than 5 different devices via network logon in the last day, a possible indicator of lateral movement.

Another real-world scenario: detecting renamed copies of common tools. Attackers often rename “cmd.exe” to “svchost.exe” to hide. You can hunt for this by looking for processes with the original file hash but a different file name. Use the `hash` function:
```
DeviceProcessEvents
| where Timestamp > ago(7d)
| where SHA256 == "original_sha256_of_cmd.exe"
| where FileName != "cmd.exe"
```

What can go wrong? The most common issue is false positives. For example, a query that looks for any external PowerShell download might flag a legitimate system update. Always review the context before escalating. Also, be careful with `join` operations: if the join key has nulls or duplicates, you can get exponential results or lose data. Use `join kind=inner` carefully and test with a small time window first.

Professionals should also learn to use the “summarize” and “make_set” functions to compress results. For instance, instead of listing every single failed login, summarize by user to show who has the most failures. This makes analysis faster. Finally, always remember that hunting queries are just one part of the detection chain. They do not replace automated detection but complement it. A mature security operations center (SOC) uses hunting queries every day as part of routine threat hunting activities.

## Memory tip

Think of “HUNT” as an acronym: Hypothesis, Understand tables, Narrow filters, Test results. This mnemonics helps you structure your query process in exams.

## FAQ

**Do I need to know KQL to use hunting queries?**

Yes, hunting queries in Microsoft 365 Defender and Azure Sentinel are written in Kusto Query Language (KQL). You can use pre-built queries without knowing KQL, but to create custom searches or modify existing ones, you need a working knowledge of KQL.

**What is the difference between a hunting query and a simple search?**

A simple search looks for a specific keyword or value across all data, like a text search. A hunting query is structured, uses logical operators, and can join multiple data tables to find complex patterns that indicate a threat. It is more powerful and precise.

**Can hunting queries be scheduled to run automatically?**

Standard hunting queries are run manually. However, you can save a hunting query as a custom detection rule, which automatically runs on a schedule and creates alerts when the query returns results.

**How long does Microsoft 365 Defender retain data for hunting?**

Microsoft 365 Defender retains advanced hunting data for 30 days by default. For longer retention, you can stream the data to Azure Sentinel or export it to Azure Data Lake.

**What is the typical performance of a hunting query?**

Most hunting queries that filter by time and use indexed columns run within seconds to a few minutes. Large queries without time filters or with complex joins may take longer and are subject to resource limits.

**Is hunting query the same across all Microsoft security tools?**

The KQL language is the same, but the available tables vary. Microsoft 365 Defender has tables for endpoints, email, and identity. Azure Sentinel has tables from many connectors. You need to know which tables exist in the tool you are using.

## Summary

A hunting query is not just a technical term; it is a fundamental shift in how security analysts approach threats. Instead of passively waiting for automated alerts, a hunting query empowers the analyst to proactively search for hidden, sophisticated attacks that evade traditional defenses. In the Microsoft ecosystem, this is achieved through Kusto Query Language (KQL) within Microsoft 365 Defender and Azure Sentinel. The query searches across endpoint, email, identity, and cloud app data to find patterns like unusual logins, suspicious process execution, or data exfiltration.

For IT certification learners, particularly those targeting the SC-200 exam, understanding hunting queries is critical. You will be asked to write, interpret, and troubleshoot KQL queries. Common mistakes include forgetting time filters, using wrong table names, and misapplying string operators. Exams also test your ability to choose the right tool for proactive hunting, often Microsoft 365 Defender’s advanced hunting, not Azure Sentinel, for domain-specific investigations.

The takeaway is clear: hunting queries are the backbone of modern threat hunting. They require both technical skill (KQL syntax) and investigative thinking (forming hypotheses and refining queries). By mastering this concept, you not only pass your exam but also gain a practical skill that is highly valued in real-world cybersecurity roles. Always practice with sample queries, and remember that each query is a question you ask your data, the better the question, the better the answer.

---

Practice questions and the full interactive page: https://courseiva.com/glossary/hunting-query
