GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing docs.datadoghq.com (truncated) — DDSQL Reference For AI agents: A markdown version of this page is available at https://docs.datadoghq.com/ddsql_reference.md.
A documentation index is available at /llms.txt.
DDSQL ReferenceOverviewDDSQL is SQL for Datadog data. It implements several standard SQL operations, such as You can run DDSQL queries from AI agents using the Datadog MCP Server This documentation covers the SQL support available and includes:
SyntaxThe following SQL syntax is supported:
Data typesDDSQL supports the following data types:
Array typesAll data types support array types. See Arrays for array literals, element access, and array functions. Type literalsDDSQL supports explicit type literals using the syntax
The type prefix can be omitted and the type is automatically inferred from the value. For example, ExampleArraysArrays are ordered collections of values that all share the same data type. Every DDSQL base type has a corresponding array type. Array literalsUse the Element accessAccess individual array elements with a 1-based subscript. Accessing an index that is out of bounds returns To access elements of an array column, use the same subscript syntax: Array functionsThe following functions operate on arrays:
Examples
|
| Function | Return Type | Description |
|---|---|---|
MIN(variable v) | typeof v | Returns the smallest value in a set of data. |
MAX(variable v) | typeof v | Returns the maximum value across all input values. |
COUNT(any a) | numeric | Returns the number of input values that are not null. |
SUM(numeric n) | numeric | Returns the summation across all input values. |
AVG(numeric n) | numeric | Returns the average value (arithmetic mean) across all input values. |
BOOL_AND(boolean b) | boolean | Returns whether all non-null input values are true. |
BOOL_OR(boolean b) | boolean | Returns whether any non-null input value is true. |
CEIL(numeric n) / CEILING(numeric n) | numeric | Returns the value rounded up to the nearest integer. Both CEIL and CEILING are supported as aliases. |
FLOOR(numeric n) | numeric | Returns the value rounded down to the nearest integer. |
ROUND(numeric n) | numeric | Returns the value rounded to the nearest integer. |
POWER(numeric base, numeric exponent) | numeric | Returns the value of base raised to the power of exponent. |
LOWER(string s) | string | Returns the string as lowercase. |
UPPER(string s) | string | Returns the string as uppercase. |
ABS(numeric n) | numeric | Returns the absolute value. |
COALESCE(args a) | typeof first non-null a OR null | Returns the first non-null value or null if all are null. |
CAST(value AS type) | type | Converts the given value to the specified data type. |
LENGTH(string s) | integer | Returns the number of characters in the string. |
TRIM(string s) | string | Removes leading and trailing whitespace from the string. |
REPLACE(string s, string from, string to) | string | Replaces occurrences of a substring within a string with another substring. |
SUBSTRING(string s, int start, int length) | string | Extracts a substring from a string, starting at a given position and for a specified length. |
REVERSE(string s) | string | Returns the string with characters in reverse order. |
STRPOS(string s, string substring) | integer | Returns the first index position of the substring in a given string, or 0 if there is no match. |
SPLIT_PART(string s, string delimiter, integer index) | string | Splits the string on the given delimiter and returns the string at the given position counting from one. |
EXTRACT(unit from timestamp/interval) | numeric | Extracts a part of a date or time field (such as year or month) from a timestamp or interval. |
TO_TIMESTAMP(string timestamp, string format) | timestamp | Converts a string to a timestamp according to the given format. |
TO_TIMESTAMP(numeric epoch) | timestamp | Converts a UNIX epoch timestamp (in seconds) to a timestamp. |
TO_CHAR(timestamp t, string format) | string | Converts a timestamp to a string according to the given format. |
DATE_BIN(interval stride, timestamp source, timestamp origin) | timestamp | Aligns a timestamp (source) to buckets of even length (stride). Returns the start of the bucket containing the source, calculated as the largest timestamp that is less than or equal to source and is a multiple of stride lengths from origin. |
DATE_TRUNC(string unit, timestamp t) | timestamp | Truncates a timestamp to a specified precision based on the provided unit. |
CURRENT_SETTING(string setting_name) | string | Returns the current value of the specified setting. Supports the parameters dd.time_frame_start and dd.time_frame_end, which return the start and end of the global time frame, respectively. |
NOW() | timestamp | Returns the current UTC timestamp at the start of the current query. |
CARDINALITY(array a) | integer | Returns the number of elements in the array. |
ARRAY_POSITION(array a, typeof_array value) | integer | Returns the index of the first occurrence of the value found in the array, or null if value is not found. |
STRING_TO_ARRAY(string s, string delimiter) | array of strings | Splits the given string into an array of strings using the given delimiter. |
ARRAY_TO_STRING(array a, string delimiter) | string | Converts an array to a string by concatenating elements with the given delimiter. |
ARRAY_AGG(expression e) | array of input type | Creates an array by collecting all the input values. |
APPROX_PERCENTILE(double percentile) WITHIN GROUP (ORDER BY expression e) | typeof expression | Computes an approximate percentile value. The percentile must be between 0.0 and 1.0 (inclusive). Requires the WITHIN GROUP (ORDER BY ...) syntax. |
UNNEST(array a [, array b...]) | rows of a [, b…] | Expands arrays into a set of rows. This form is only allowed in a FROM clause. |
MINSELECT MIN(response_time) AS min_response_time
FROM logs
WHERE status_code = 200MAXSELECT MAX(response_time) AS max_response_time
FROM logs
WHERE status_code = 200COUNTSELECT COUNT(request_id) AS total_requests
FROM logs
WHERE status_code = 200 SUMSELECT SUM(bytes_transferred) AS total_bytes
FROM logs
GROUP BY service_nameAVGSELECT AVG(response_time)
AS avg_response_time
FROM logs
WHERE status_code = 200
GROUP BY service_nameBOOL_ANDSELECT BOOL_AND(status_code = 200) AS all_success
FROM logsBOOL_ORSELECT BOOL_OR(status_code = 200) AS some_success
FROM logsCEILSELECT CEIL(price) AS rounded_price
FROM productsFLOORSELECT FLOOR(price) AS floored_price
FROM productsROUNDSELECT ROUND(price) AS rounded_price
FROM productsPOWERSELECT POWER(response_time, 2) AS squared_response_time
FROM logsLOWERSELECT LOWER(customer_name) AS lowercase_name
FROM customersUPPERSELECT UPPER(customer_name) AS uppercase_name
FROM customersABSSELECT ABS(balance) AS absolute_balance
FROM accountsCOALESCESELECT COALESCE(phone_number, email) AS contact_info
FROM usersCASTSupported cast target types:
BIGINTDECIMALINETTIMESTAMPVARCHARSELECT
CAST(order_id AS VARCHAR) AS order_id_string,
'Order-' || CAST(order_id AS VARCHAR) AS order_label
FROM
ordersLENGTHSELECT
customer_name,
LENGTH(customer_name) AS name_length
FROM
customersINTERVALSELECT
TIMESTAMP '2023-10-01 10:00:00' + INTERVAL '30 days' AS future_date,
INTERVAL '1 MILLISECOND 2 SECONDS 3 MINUTES 4 HOURS 5 DAYS'TRIMSELECT
TRIM(name) AS trimmed_name
FROM
usersREPLACESELECT
REPLACE(description, 'old', 'new') AS updated_description
FROM
productsSUBSTRINGSELECT
SUBSTRING(title, 1, 10) AS short_title
FROM
booksREVERSESELECT
REVERSE(username) AS reversed_username
FROM
users
LIMIT 5STRPOSSELECT
STRPOS('foobar', 'bar')SPLIT_PARTSELECT
SPLIT_PART('aaa-bbb-ccc', '-', 2)EXTRACTSupported extraction units:
| Literal | Input Type | Description |
|---|---|---|
day | timestamp / interval | day of the month |
dow | timestamp | day of the week 1 (Monday) to 7 (Sunday) |
doy | timestamp | day of the year (1 - 366) |
epoch | timestamp / interval | seconds since 1970-01-01 00:00:00 UTC (for timestamps), or total number of seconds (for intervals) |
hour | timestamp / interval | hour of the day (0 - 23) |
minute | timestamp / interval | minute of the hour (0 - 59) |
second | timestamp / interval | second of the minute (0 - 59) |
week | timestamp | week of the year (1 - 53) |
month | timestamp | month of the year (1 - 12) |
quarter | timestamp | quarter of the year (1 - 4) |
year | timestamp | year |
timezone_hour | timestamp | hour of the time zone offset |
timezone_minute | timestamp | minute of the time zone offset |
SELECT
EXTRACT(year FROM purchase_date) AS purchase_year
FROM
sales-- Get the Unix epoch of a timestamp
SELECT EXTRACT(epoch FROM TIMESTAMP '2021-01-01 00:00:00+00')
-- Returns: 1609459200-- Get the total seconds in an interval
SELECT EXTRACT(epoch FROM INTERVAL '1 day 2 hours')
-- Returns: 93600-- Calculate how many seconds ago each event occurred
SELECT
event_time,
EXTRACT(epoch FROM now()) - EXTRACT(epoch FROM event_time) AS seconds_ago
FROM
eventsTO_TIMESTAMPTO_TIMESTAMP has two forms:
Form 1: Convert string to timestamp with format
Supported patterns for date/time formatting:
| Pattern | Description |
|---|---|
YYYY | year (4 digits) |
YY | year (2 digits) |
MM | month number (01 - 12) |
DD | day of month (01 - 31) |
HH24 | hour of day (00 - 23) |
HH12 | hour of day (01 - 12) |
HH | hour of day (01 - 12) |
MI | minute (00 - 59) |
SS | second (00 - 59) |
MS | millisecond (000 - 999) |
TZ | time-zone abbreviation |
OF | time-zone offset from UTC |
AM / am | meridiem indicator (without periods) |
PM / pm | meridiem indicator (without periods) |
SELECT
TO_TIMESTAMP('25/12/2025 04:23 pm', 'DD/MM/YYYY HH:MI am') AS tsForm 2: Convert UNIX epoch timestamp to timestamp
SELECT
TO_TIMESTAMP(1735142580) AS ts_from_epochTO_CHARSupported patterns for date/time formatting:
| Pattern | Description |
|---|---|
YYYY | year (4 digits) |
YY | year (2 digits) |
MM | month number (01 - 12) |
DD | day of month (01 - 31) |
HH24 | hour of day (00 - 23) |
HH12 | hour of day (01 - 12) |
HH | hour of day (01 - 12) |
MI | minute (00 - 59) |
SS | second (00 - 59) |
MS | millisecond (000 - 999) |
TZ | time-zone abbreviation |
OF | time-zone offset from UTC |
AM / am | meridiem indicator (without periods) |
PM / pm | meridiem indicator (without periods) |
SELECT
TO_CHAR(order_date, 'MM-DD-YYYY') AS formatted_date
FROM
ordersDATE_BINSELECT DATE_BIN('15 minutes', TIMESTAMP '2025-09-15 12:34:56', TIMESTAMP '2025-01-01')
-- Returns 2025-09-15 12:30:00
SELECT DATE_BIN('1 day', TIMESTAMP '2025-09-15 12:34:56', TIMESTAMP '2025-01-01')
-- Returns 2025-09-15 00:00:00DATE_TRUNCSupported truncations:
millisecondsseconds / secondminutes / minutehours / hourdays / dayweeks / weekmonths / monthquarters / quarteryears / yearSELECT
DATE_TRUNC('month', event_time) AS month_start
FROM
eventsCURRENT_SETTINGSupported setting parameters:
dd.time_frame_start: Returns the start of the selected time frame in RFC 3339 format (YYYY-MM-DD HH:mm:ss.sss±HH:mm).dd.time_frame_end: Returns the end of the selected time frame in RFC 3339 format (YYYY-MM-DD HH:mm:ss.sss±HH:mm).-- Define the current analysis window
WITH bounds AS (
SELECT CAST(CURRENT_SETTING('dd.time_frame_start') AS TIMESTAMP) AS time_frame_start,
CAST(CURRENT_SETTING('dd.time_frame_end') AS TIMESTAMP) AS time_frame_end
),
-- Define the immediately preceding window of equal length
previous_bounds AS (
SELECT time_frame_start - (time_frame_end - time_frame_start) AS prev_time_frame_start,
time_frame_start AS prev_time_frame_end
FROM bounds
)
SELECT * FROM bounds, previous_boundsNOWSELECT
*
FROM
sales
WHERE
purchase_date > NOW() - INTERVAL '1 hour'APPROX_PERCENTILE-- Calculate the median (50th percentile) response time
SELECT
APPROX_PERCENTILE(0.5) WITHIN GROUP (ORDER BY response_time) AS median_response_time
FROM
logs
-- Calculate 95th and 99th response time percentiles by service
SELECT
service_name,
APPROX_PERCENTILE(0.95) WITHIN GROUP (ORDER BY response_time) AS p95_response_time,
APPROX_PERCENTILE(0.99) WITHIN GROUP (ORDER BY response_time) AS p99_response_time
FROM
logs
GROUP BY
service_nameAll regular expression (regex) functions use the International Components for Unicode (ICU) flavor:
| Function | Return Type | Description |
|---|---|---|
REGEXP_LIKE(string input, string pattern) | Boolean | Evaluates whether a string matches a regular expression pattern. |
REGEXP_MATCH(string input, string pattern [, string flags ]) | array of strings | Returns substrings of the first pattern match in the string. This function searches the input string using the given pattern and returns captured substrings (capture groups) from the first match. If no capture groups are present, returns the full match. |
REGEXP_REPLACE(string input, string pattern, string replacement [, string flags ]) | string | Replaces the substring that is the first match to the pattern, or all such matches if you use the optional g flag. |
REGEXP_REPLACE (string input, string pattern, string replacement, integer start, integer N [, string flags ] ) | string | Replaces the substring that is the Nth match to the pattern, or all such matches if N is zero, starting from start. |
REGEXP_LIKESELECT
*
FROM
emails
WHERE
REGEXP_LIKE(email_address, '@example\.com$')REGEXP_MATCHSELECT regexp_match('foobarbequebaz', '(bar)(beque)');
-- {bar,beque}
SELECT regexp_match('foobarbequebaz', 'barbeque');
-- {barbeque}
SELECT regexp_match('abc123xyz', '([a-z]+)(\d+)(x(.)z)');
-- {abc,123,xyz,y}REGEXP_REPLACESELECT regexp_replace('Auth success token=abc123XYZ789', 'token=\w+', 'token=***');
-- Auth success token=***
SELECT regexp_replace('status=200 method=GET', 'status=(\d+) method=(\w+)', '$2: $1');
-- GET: 200
SELECT regexp_replace('INFO INFO INFO', 'INFO', 'DEBUG', 1, 2);
-- INFO DEBUG INFOYou can use the following flags with regular expression functions:
in or mgi flagSELECT regexp_match('INFO', 'info')
-- NULL
SELECT regexp_match('INFO', 'info', 'i')
-- ['INFO']n flagSELECT regexp_match('a
b', '^b');
-- NULL
SELECT regexp_match('a
b', '^b', 'n');
-- ['b']g flagSELECT icu_regexp_replace('Request id=12345 completed, id=67890 pending', 'id=\d+', 'id=XXX');
-- Request id=XXX completed, id=67890 pending
SELECT regexp_replace('Request id=12345 completed, id=67890 pending', 'id=\d+', 'id=XXX', 'g');
-- Request id=XXX completed, id=XXX pendingThis table provides an overview of the supported window functions. For comprehensive details and examples, see the PostgreSQL documentation.
| Function | Return Type | Description |
|---|---|---|
OVER | N/A | Defines a window for a set of rows for other window functions to operate on. |
PARTITION BY | N/A | Divides the result set into partitions, specifically for applying window functions. |
RANK() | integer | Assigns a rank to each row within a partition, with gaps for ties. |
ROW_NUMBER() | integer | Assigns a unique sequential number to each row within a partition. |
LEAD(column n) | typeof column | Returns the value from the next row in the partition. |
LAG(column n) | typeof column | Returns the value from the previous row in the partition. |
FIRST_VALUE(column n) | typeof column | Returns the first value in an ordered set of values. |
LAST_VALUE(column n) | typeof column | Returns the last value in an ordered set of values. |
NTH_VALUE(column n, offset) | typeof column | Returns the value at the specified offset in an ordered set of values. |
| Name | Return type | Description |
|---|---|---|
| json_extract_path_text(text json, text path…) | text | Extracts a JSON sub-object as text, defined by the path. Its behavior is equivalent to the Postgres function with the same name. For example, json_extract_path_text(col, ‘forest') returns the value of the key forest for each JSON object in col. See the example below for a JSON array syntax. |
| json_extract_path(text json, text path…) | JSON | Same functionality as json_extract_path_text, but returns a column of JSON type instead of text type. |
| json_array_elements(text json) | rows of JSON | Expands a JSON array into a set of rows. This form is only allowed in a FROM clause. |
| json_array_elements_text(text json) | rows of text | Expands a JSON array into a set of rows. This form is only allowed in a FROM clause. |
The inet type represents IPv4 and IPv6 network addresses with an optional CIDR prefix length (for example, 192.168.1.5/24 or ::1). Create inet values with the type literal syntax INET 'value' or by casting a string with CAST(column AS inet).
| Function | Return Type | Description |
|---|---|---|
host(inet addr) | VARCHAR | Returns the IP address as text, without the prefix length. |
network(inet addr) | INET | Returns the network part of the address, with host bits zeroed. |
netmask(inet addr) | INET | Returns the network mask for the address. |
masklen(inet addr) | BIGINT | Returns the prefix length of the network mask. |
broadcast(inet addr) | INET | Returns the broadcast address of the network. |
family(inet addr) | BIGINT | Returns the address family: 4 for IPv4, 6 for IPv6. |
| Operator | Return Type | Description |
|---|---|---|
inet a << inet b | BOOLEAN | Returns true if a is strictly contained within b. |
inet a <<= inet b | BOOLEAN | Returns true if a is contained within or equals b. |
inet a >> inet b | BOOLEAN | Returns true if a strictly contains b. |
inet a >>= inet b | BOOLEAN | Returns true if a contains or equals b. |
inet a && inet b | BOOLEAN | Returns true if the subnets of a and b overlap. |
hostSELECT host(INET '192.168.1.5/24')
-- Returns: 192.168.1.5networkSELECT network(INET '192.168.1.5/24')
-- Returns: 192.168.1.0/24netmaskSELECT netmask(INET '192.168.1.5/24')
-- Returns: 255.255.255.0masklenSELECT masklen(INET '192.168.1.5/24')
-- Returns: 24broadcastSELECT broadcast(INET '192.168.1.5/24')
-- Returns: 192.168.1.255/24familySELECT family(INET '::1')
-- Returns: 6
SELECT family(INET '192.168.1.5')
-- Returns: 4-- Check if an IP is within a subnet
SELECT INET '192.168.1.5' << INET '192.168.1.0/24'
-- Returns: true
-- Check containment or equality
SELECT INET '192.168.1.0/24' <<= INET '192.168.1.0/24'
-- Returns: true
-- Check if a subnet contains an IP
SELECT INET '10.0.0.0/8' >> INET '10.1.2.3'
-- Returns: true
-- Check if two subnets overlap
SELECT INET '192.168.1.0/24' && INET '192.168.1.128/25'
-- Returns: true-- Find all IPs in a private subnet and extract network info
SELECT
host(CAST(src_ip AS inet)) AS ip,
masklen(CAST(src_ip AS inet)) AS prefix_len,
network(CAST(src_ip AS inet)) AS network
FROM connections
WHERE CAST(src_ip AS inet) << INET '10.0.0.0/8'
AND family(CAST(src_ip AS inet)) = 4Table functions are used to query logs, metrics, cloud costs, and other data sources.
| Function | Description | Example |
|---|---|---|
dd.logs(
columns => array < varchar >,
filter ? => varchar,
indexes ? => array < varchar >,
storage ? => varchar,
from_timestamp ? => timestamp,
to_timestamp ? => timestamp
) AS (column_name type [, ...]) | Returns log data as a table. The columns parameter specifies which log fields to extract. Nested fields are accessed using dot notation, and non-core fields need to be prepended by @. The AS clause defines the schema of the returned table. Optional: filtering by index or time range. When time is not specified, DDSQL defaults to the global time setting, which in DDSQL Editor is set to the past 1 hour. Optional: specifying the storage to use (for example, hot, flex_tier). When not specified, the default is hot storage. | |
dd.metrics_scalar(
query varchar,
reducer varchar [, from_timestamp timestamp, to_timestamp timestamp]
) | Returns metric data as a scalar value. The function accepts a metrics query (with optional grouping), a reducer to determine how values are aggregated (avg, max, etc.), and optional timestamp parameters (default 1 hour) to define the time range. | |
dd.metrics_timeseries(
query varchar [, from_timestamp timestamp, to_timestamp timestamp]
) | Returns metric data as a timeseries. The function accepts a metrics query (with optional grouping) and optional timestamp parameters (default 1 hour) to define the time range. Returns datapoints over time rather than a single aggregated value. | |
dd.cloud_cost_scalar(
query varchar,
reducer varchar
[, from_timestamp timestamp,
to_timestamp timestamp]
) | Returns Cloud Cost Management data as a scalar value. The function accepts a cloud cost query (with optional grouping), an aggregation reducer (use sum for cost data; other reducers such as avg, min, and max are accepted but rarely applicable to cost queries), and optional timestamp parameters (default 1 hour) to define the time range. Note: Cloud cost data is typically delayed by 24-48 hours, so recent timestamps may return no results. | |
dd.cloud_cost_timeseries(
query varchar
[, from_timestamp timestamp,
to_timestamp timestamp]
) | Returns Cloud Cost Management data as a timeseries. The function accepts a cloud cost query (with optional grouping) and optional timestamp parameters (default 1 hour) to define the time range. Returns cost datapoints over time rather than a single aggregated value. Note: Cloud cost data is typically delayed by 24-48 hours, so recent timestamps may return no results. | |
SELECT *
FROM dd.logs(
columns => ARRAY['timestamp','host','service','message'],
from_timestamp => TIMESTAMP '2025-07-10 00:00:00.000-04:00',
to_timestamp => TIMESTAMP '2025-07-17 00:00:00.000-04:00'
) AS (
timestamp TIMESTAMP,
host VARCHAR,
service VARCHAR,
message VARCHAR
)SELECT *
FROM dd.logs(
columns => ARRAY['timestamp','host','service','message'],
from_timestamp => now() - INTERVAL '7 days',
to_timestamp => now()
) AS (
timestamp TIMESTAMP,
host VARCHAR,
service VARCHAR,
message VARCHAR
)SELECT *
FROM dd.logs(
columns => ARRAY['timestamp','host','service','message'],
filter => 'source:java',
indexes => ARRAY['trino'],
storage => 'hot'
) AS (
timestamp TIMESTAMP,
host VARCHAR,
service VARCHAR,
message VARCHAR
)Column aliases cannot contain dots; replace them with underscores or any other valid character when defining the alias.
SELECT timestamp, host, asset_id, view_url, data_resource_type
FROM dd.logs(
filter => 'service:mcp',
columns => ARRAY['timestamp','host','@asset.id','@view.url','@data.resource.type']
) AS (
timestamp TIMESTAMP,
host VARCHAR,
asset_id VARCHAR,
view_url VARCHAR,
data_resource_type VARCHAR
)DDSQL exposes tags as an hstore type, which is inspired by PostgreSQL. You can access the values for specific tag keys using the PostgreSQL arrow operator. For example:
SELECT instance_type, count(instance_type)
FROM aws.ec2_instance
WHERE tags->'region' = 'us-east-1' -- region is a tag, not a column
GROUP BY instance_type
Tags are key-value pairs where each key can have zero, one, or multiple tag values corresponding to it. When accessed, the tag value returns a single string, containing all corresponding values. When the data has multiple tag values for the same tag key, they are represented as a sorted, comma-separated string. For example:
SELECT tags->'team', instance_type, architecture, COUNT(*) as instance_count
FROM aws.ec2_instance
WHERE tags->'team' = 'compute_provisioning,database_ops'
GROUP BY tags->'team', instance_type, architecture
ORDER BY instance_count DESC
You can also compare tag values as strings or entire tag sets:
SELECT *
FROM k8s.daemonsets da INNER JOIN k8s.deployments de
ON da.tags = de.tags -- for a specific tag: da.tags->'app' = de.tags->'app'
Additionally, you can extract tag keys and values into individual arrays of text:
SELECT akeys(tags), avals(tags)
FROM aws.ec2_instance
| Name | Return type | Description |
|---|---|---|
| tags -> ’text' | Text | Gets the value for a given key. Returns null if key is not present. |
| akeys(hstore tags) | Array of text | Gets the keys of an HSTORE as an array |
| avals(hstore tags) | Array of text | Gets the values of an HSTORE as an array |
dd.matches(). Referencing $var anywhere else in a query is not supported. Contact Datadog support to request access.Template variables let you change query filters without editing SQL.
dd.matchesUse dd.matches(column, $var) in a WHERE clause to compare a column or expression with the variable’s selected values. For example, for a variable named env:
SELECT *
FROM aws.ec2_instance
WHERE dd.matches(tags->'env', $env);| Selected values | Matches |
|---|---|
prod | An exact, case-sensitive match. |
prod, staging | Either value. |
* | No filter. An empty selection also applies no filter. |
prod* | Values starting with prod. |
*prod | Values ending with prod. |
*prod* | Values containing prod. |
Pass $env directly, without single quotes or .value. The column or expression determines what is filtered; the variable’s tag is not added.
For non-text columns, cast the expression to VARCHAR first, for example dd.matches(CAST(status_code AS VARCHAR), $status).
Use $env for a lowercase variable name. Enclose names containing uppercase letters, spaces, or punctuation in double quotes, for example $"aws-region".
Queries that read large amounts of data or run heavy computations can be slow or return resource errors. The patterns below are the most common causes, each with a rewrite that usually resolves the issue.
Filter early and aggregate early. Computations in the query filter or a GROUP BY summary run against the index. Computations in a JOIN or a wide LIMIT are held in memory.
Before re-running a slow query, ask the following questions:
service:* or env:*)?LIMIT, could a GROUP BY summary work instead?JOIN clauses, could the query be rewritten as a single scan?JOIN key high-cardinality (user/ request/trace ID)?Always include a selective token in your data source query, such as service:, host:, env:, or any @attribute:value.
Wildcard filters such as service:* or env:* match every event, so they don’t actually narrow the data. Treat these filters as equivalent to leaving the filter blank.
Before
-- No filter; scans all logs in the time range
SELECT timestamp, service, host, message
FROM dd.logs(
columns => ARRAY['timestamp', 'service', 'host', 'message'],
from_timestamp => NOW() - INTERVAL '7 days',
to_timestamp => NOW()
) AS (
timestamp TIMESTAMP,
service VARCHAR,
host VARCHAR,
message VARCHAR
)
After
-- filter => narrows the scan to matching events before any SQL runs
SELECT timestamp, service, host, message
FROM dd.logs(
filter => 'service:checkout-api env:prod',
columns => ARRAY['timestamp', 'service', 'host', 'message'],
from_timestamp => NOW() - INTERVAL '7 days',
to_timestamp => NOW()
) AS (
timestamp TIMESTAMP,
service VARCHAR,
host VARCHAR,
message VARCHAR
)
Scan time grows with the time range. Consider starting with a window that covers the question (often a few hours or a day) and widening only when the question demands more. For long-term trends, a pre-aggregated metric or a daily-summary query runs faster than re-scanning raw events on every run.
Goal: understand log volume from the billing service over the last month.
Before
-- Scans 31 days of raw events
SELECT timestamp, message
FROM dd.logs([Page truncated to keep GeezerVison snappy.]