Join our Newsletter — 33% off our NHI Course
Home› Guides› osquery SQL Cheat Sheet: Tables and Queries for…
Template Endpoint Security

osquery SQL Cheat Sheet: Tables and Queries for Host Investigation

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 27 November 2026 12 min read
On this page

During an investigation the slow part of using osquery is rarely the SQL itself but remembering which table holds the answer, which operating systems it exists on, and which columns it needs in the WHERE clause before it returns anything. This cheat sheet is a ready reference of osquery tables and read-only queries organised by investigation question: what is running and listening, what will start again after reboot, who has logged in and which keys grant access, and whether a file is what it claims to be. It also covers scheduling queries in packs and keeping them cheap. It is for threat hunters, DFIR analysts and endpoint engineers who already have osquery deployed; for what osquery is, deployment and how it fits beside EDR, see the osquery guide.

This is an independent guide from NHI Mgmt Group, based on the osquery project's public documentation and its table specifications as of November 2026 (latest listed release 5.24.0). It is not sponsored or reviewed by the osquery project. Product features change, so confirm table names and columns against the osquery schema for your installed version.

Key takeaways

  • Check the platform first. Tables such as launchd (macOS), systemd_units (Linux) and scheduled_tasks (Windows) exist on one OS only; crontab, authorized_keys and shell_history are Linux and macOS only.
  • Some tables need input. hash and file require a path or directory constraint, and joins through users are how per-user tables such as authorized_keys return every user's rows.
  • Join on pid and uid. Most investigation queries are a join of processes with a socket, file or user table on pid or uid.
  • Point-in-time tables miss short-lived activity. For processes that start and exit between queries, enable the evented tables (process_events, bpf_process_events, es_process_events, file_events) after testing their overhead.
  • Profile before you schedule. Joins across processes and socket tables are among the more expensive queries; the watchdog restarts a worker that exceeds its limits, so test with the project's profiling tool and set sensible intervals.

How to use this template

  1. Start interactively: run queries in osqueryi on one host, or as a live query from your fleet manager, before scheduling anything. osquery uses SQLite syntax.
  2. Confirm the schema: run .tables and .schema <table> in osqueryi, or check the schema page for your version. Column names change between releases.
  3. Select columns, not *: name the columns you need; it keeps output readable and reduces cost.
  4. Record evidence: when a query answers an incident question, save the query text, host, time and output to your case record; see the Digital Forensics (DFIR) Guide.
  5. Promote what works: move proven hunting queries into a pack with a tested interval (see Scheduling queries and packs).

All queries below are read-only. Replace values in square brackets, such as [path] or [sha256], with your own.

Key tables by platform

QuestionTablePlatformsNotes
What is running?processesLinux, macOS, Windowson_disk = 0 means the binary path no longer exists
What is listening?listening_portsLinux, macOS, WindowsJoin to processes on pid
What is connected out?process_open_socketsLinux, macOS, Windowsremote_address, remote_port, state
What starts at boot or login?startup_itemsLinux, macOS, WindowsBroad view; check the OS-specific tables too
macOS persistencelaunchdmacOSLaunchAgents and LaunchDaemons with program, program_arguments, run_at_load
Linux persistencesystemd_units, crontabLinux; crontab also macOSfragment_path shows the unit file
Windows persistenceservices, scheduled_tasks, autoexec, registry, wmi_cli_event_consumersWindowsautoexec aggregates several autostart sources
Who can log in with a key?authorized_keysLinux, macOSJoin through users on uid
Which private keys sit on disk?user_ssh_keysLinux, macOS, Windowsencrypted = 0 flags unprotected keys
Who is and was logged in?logged_in_users, lastAll; last Linux and macOShost shows the remote source
What did users type?shell_historyLinux, macOStime can be 0 where the shell does not record it
Is this file what it claims?hash, file, authenticodeAll; authenticode Windowshash and file require path or directory

Query basics and joins

Treat each table as a view of current host state. Three patterns cover most investigations.

  • Constrain required columns: SELECT path, sha256 FROM hash WHERE path = '[path]'; returns one row; without the constraint the table returns nothing.
  • Join on keys: pid links processes to sockets; uid links users to keys and history; path links files to hashes.
  • Use LIKE for paths: % is the SQL wildcard, and for the file table WHERE path LIKE '/etc/%' lists one directory level. String comparisons are case sensitive unless the column is declared otherwise (Windows service names and hashes are case-insensitive in the schema).

1 Sample only, based on the public documentation cited. Assess it independently against the current official documentation, test outside production and back up first.

Sample 1
-- Per-user tables: iterate every local user
SELECT u.username, ak.key_file, ak.algorithm, ak.comment
FROM users u
JOIN authorized_keys ak USING (uid);

Processes and listening ports

Sample 1
-- Processes whose binary is no longer on disk
SELECT pid, name, path, cmdline, parent, start_time
FROM processes
WHERE on_disk = 0;

-- Listening sockets with the owning process
SELECT DISTINCT p.pid, p.name, p.path, lp.address, lp.port, lp.protocol
FROM listening_ports lp
JOIN processes p USING (pid)
WHERE lp.port != 0;

-- Established outbound connections by process
SELECT p.name, p.path, s.remote_address, s.remote_port, s.state
FROM process_open_sockets s
JOIN processes p USING (pid)
WHERE s.remote_port != 0 AND s.remote_address NOT IN ('127.0.0.1', '::1');

-- Parent and child pairs, to spot unusual parents (for example an office app spawning a shell)
SELECT c.pid, c.name AS child, c.cmdline, p.name AS parent
FROM processes c
JOIN processes p ON c.parent = p.pid;

The protocol column is numeric (6 is TCP, 17 is UDP).

Persistence locations

PlatformQueryATT&CK technique
macOSSELECT label, program, program_arguments, run_at_load, path FROM launchd WHERE run_at_load = '1';T1543.001 Launch Agent; T1543.004 Launch Daemon
LinuxSELECT id, fragment_path, active_state, unit_file_state FROM systemd_units WHERE id LIKE '%.service' AND fragment_path NOT LIKE '/usr/lib/%';T1543.002 Systemd Service
Linux, macOSSELECT minute, hour, command, path FROM crontab;T1053.003 Cron
WindowsSELECT name, action, path, enabled, hidden, next_run_time FROM scheduled_tasks WHERE enabled = 1;T1053.005 Scheduled Task
WindowsSELECT name, display_name, path, start_type, user_account FROM services WHERE start_type = 'AUTO_START';T1543.003 Windows Service
WindowsSELECT name, path, source FROM autoexec;T1547.001 Registry Run Keys / Startup Folder
WindowsSELECT name, command_line_template, executable_path FROM wmi_cli_event_consumers;T1546.003 WMI Event Subscription
AllSELECT name, path, type, source, status, username FROM startup_items;TA0003 Persistence (broad view)

Read results against a known-good baseline from a clean build of the same image; most rows are legitimate. The path filter on systemd_units is an example: adjust it to where your distribution installs vendor units. For Windows hunting depth see How to Hunt for Persistence on Windows, and for Linux see the Linux Persistence Forensics Guide.

Users, logins and keys

Sample 1
-- Interactive logins now, with remote source
SELECT user, type, tty, host, time, pid FROM logged_in_users;

-- Login history (Linux, macOS)
SELECT username, tty, host, time, type FROM last ORDER BY time DESC LIMIT 50;

-- Accounts with a login shell (Linux, macOS)
SELECT uid, username, shell, directory FROM users
WHERE shell NOT LIKE '%nologin' AND shell NOT LIKE '%false';

-- Unencrypted private keys in home directories
SELECT u.username, k.path, k.key_type
FROM users u JOIN user_ssh_keys k USING (uid)
WHERE k.encrypted = 0;

-- Recent shell commands for one user (Linux, macOS)
SELECT u.username, h.time, h.command
FROM users u JOIN shell_history h USING (uid)
WHERE u.username = '[username]';

SSH keys are machine credentials: an unexpected entry in authorized_keys maps to ATT&CK T1098.004 SSH Authorized Keys, and an unencrypted private key found by user_ssh_keys is a credential to rotate, not just a finding. See How to find unused GitHub deploy keys and SSH keys and the SSH Key Management Guide. Shell history may contain secrets typed on the command line; restrict who can run that query and treat output as sensitive.

File and hash checks

Sample 1
-- Hash one file
SELECT path, md5, sha256 FROM hash WHERE path = '[path]';

-- Hash every file in a directory
SELECT path, sha256 FROM hash WHERE directory = '[directory]';

-- Hash the binaries of running processes
SELECT p.pid, p.name, p.path, h.sha256
FROM processes p JOIN hash h ON h.path = p.path
WHERE p.on_disk = 1;

-- Search a directory tree for a known bad hash (expensive: scope tightly)
SELECT f.path, h.sha256 FROM file f JOIN hash h USING (path)
WHERE f.directory = '[directory]' AND h.sha256 = '[sha256]';

-- Recently modified files in one directory
SELECT path, size, uid, mode, mtime FROM file
WHERE directory = '/etc' AND mtime > (strftime('%s','now') - 86400);

-- Windows: signature status of a binary
SELECT path, result, subject_name, issuer_name FROM authenticode WHERE path = '[path]';

For continuous change tracking use file integrity monitoring instead of repeated scans: configure file_paths categories and query file_events (inotify on Linux, FSEvents on macOS) or ntfs_journal_events on Windows. In file_paths, % matches one level and %% matches recursively. FIM is off by default and needs --disable_events=false plus the matching flag, such as --enable_file_events=true.

Scheduling queries and packs

SettingWhat it doesGuidance
intervalSeconds of daemon run time between executions, maximum 604,800 (one week)Suspended laptops pause the clock, so daily queries may run less often than expected
Differential (default)Logs only added and removed rows compared with the last run, cached in RocksDBBest for persistence and listening port changes
"snapshot": trueLogs the full result set every runUse for inventories you want complete in each log
"removed": falseSuppresses removed rows in differential outputReduces noise where only additions matter
Pack platformLimits a pack or query to an OSStops Windows-only queries erroring on Linux
Pack discoveryRuns the pack only where discovery queries return rowsRefreshed every 60 minutes by default (pack_refresh_interval)
Pack shardRuns on a percentage of hostsPilot new queries on a small shard first

The project ships example packs in its repository, but they are a starting point: review intervals and remove queries you will not act on.

Performance and the evented tables

  • Profile first: the project's tools/analysis/profile.py reports utilisation, CPU time, memory and file descriptors per query; its own example rates the processes and listening ports join as the most expensive query in the sample set and suggests running it less often.
  • Respect the watchdog: osqueryd restarts a worker that breaches memory or CPU limits (--watchdog_level, --watchdog_memory_limit, --watchdog_utilization_limit, default 10 percent CPU). The project advises setting the level to -1 rather than disabling the watchdog outright where limits must be lifted. A scheduled query stopped by the watchdog is denylisted for one day by default; set "denylist": false only for queries you must keep running.
  • Evented process tables: process_events uses Audit on Linux (and OpenBSM on older macOS); bpf_process_events needs Linux kernel 4.18 or newer; es_process_events uses EndpointSecurity on macOS 10.15 and newer. On Linux, auditd must not run alongside osquery's Audit-based tables. Expect more CPU and much more log volume.

Common mistakes

  • Querying a table on the wrong OS: a pack mixing launchd and scheduled_tasks without a platform setting errors or returns nothing on half the fleet.
  • Missing required constraints: SELECT * FROM hash; returns no rows; it needs path or directory.
  • Recursive hashing at scale: joining file and hash over large trees on a schedule triggers the watchdog and slows hosts.
  • Trusting point-in-time results for short-lived processes: a process that ran for two seconds between queries is invisible without evented tables.
  • Treating every result as malicious: without a baseline from a clean image, persistence queries bury analysts in legitimate entries.
  • Assuming column names are stable: tables and columns are added between releases; check .schema on the installed version before reusing an old query.

Framework mapping

FrameworkReferenceWhere these queries help
NIST CSF 2.0DE.CM-09Monitoring computing hardware, software and runtime environments for adverse events
NIST SP 800-53 Rev. 5SI-4 System Monitoring; CM-8 System Component InventoryScheduled packs for change detection and inventory
MITRE ATT&CKTA0003 Persistence; T1057 Process Discovery; T1049 System Network Connections DiscoveryPersistence queries above; process and socket tables mirror the views attackers use, for defenders

Practitioner checklist

  • Confirm the installed osquery version and run .schema for each table before reusing saved queries.
  • Build baselines of persistence and listening ports from a clean image for each OS you run.
  • Schedule persistence queries as differential with tested intervals and a platform setting per pack.
  • Profile every new scheduled query with profile.py and pilot it on a small shard.
  • Enable evented process tables only after measuring CPU and log volume on representative hosts.
  • Rotate any credential an investigation finds, such as unencrypted SSH keys, and record the action in the case.
  • Restrict access to queries that return sensitive data, such as shell_history.
  • Save query text, host, time and output as evidence for every incident question answered.

Standards and references

Related NHI Mgmt Group resources: osquery · How to Hunt for Persistence on Windows · Linux Persistence Forensics Guide · Digital Forensics (DFIR) Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.