Skip to content

Prometheus

PromQL queries, typed samples with pushdown, metadata and server status from any Prometheus-compatible API

Connector software
Free and open source
Service credentials
Required
Use with an agent

Install the Orchard skill in your project to help your agent find connectors, configure them, and verify SQL results.

npx skills add Query-farm/vgi-skills --skill orchard

Copy this request into your coding agent to get started.

Use https://query.farm/products/orchard/connectors/prometheus/index.md to help me query Prometheus with DuckDB or Haybarn 2.0.1 and VGI protocol 3.4. Ask only for missing details about the result I need or whether I want local execution, self-hosting or Query Farm hosting. Check the connector's actual hosting availability, credentials and input requirements. Read one format of each needed reference and the exact object declarations before writing SQL. Use a released connector, and distinguish a saved example result from anything you actually execute. If you cannot run the query, tell me what remains to verify.

Find unhealthy monitoring targets

Uses your connected account. Set up the connector and credentials to run it with your data.

SELECT job, instance, last_error
FROM prometheus.main.targets()
WHERE health = 'down'
ORDER BY job, instance

Quick start

Choose where to run Prometheus, then follow the steps below.

The connector runs alongside DuckDB or Haybarn. No Query Farm account is needed.

1. Install the vgi extension

Run this in your SQL client. On DuckDB, keep FROM query_farm on LOAD in later sessions.

setup.sql
SET allow_extension_repositories = 'allowed';

CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
    WITH PREFIX 'https://duckdb-extensions.query.farm';

INSTALL vgi FROM query_farm;
LOAD vgi FROM query_farm;

2. Attach the connector

Attach the release directly

Downloads the latest release for your platform and caches it locally.

ATTACH 'prometheus' AS prometheus (
  TYPE vgi,
  LOCATION 'github-auto://Query-farm/vgi-prometheus'
);

3. Add service credentials

After attaching, create the secret for the service you want to query in the same SQL session. Replace the placeholders with your service settings.

prometheus credentials

Connection to a Prometheus-compatible HTTP API (Prometheus, Thanos, Mimir, Cortex, VictoriaMetrics, Grafana Cloud, Amazon Managed Prometheus).

Get these credentials →
secret.sql
CREATE SECRET prometheus (
    TYPE prometheus,
    base_url      '<base_url>',
    bearer_token  '<BEARER_TOKEN>',  -- secret
    username      '<username>',
    password      '<PROMETHEUS_PASSWORD>',  -- secret
    tenant_id     '<tenant_id>',
    extra_headers '<PROMETHEUS_EXTRA_HEADERS>'  -- secret
);
Credential fields and requirements →

4. Run a query

query.sql
SELECT job, instance, last_error
FROM prometheus.main.targets()
WHERE health = 'down'
ORDER BY job, instance
More example queries →
Technical details
Verified connector release
v0.2.1
Engine
2.0.1
VGI protocol
3.4.0
Verified on
December 1, 2026
Release notes on GitHub
Pin a version for production

When running the connector yourself, keep a specific release until you’re ready to upgrade. Replace the ATTACH statement above with this one and follow the same extension and credential setup.

Attach the release directly

Uses the verified release each time you attach the connector.

ATTACH 'prometheus' AS prometheus (
  TYPE vgi,
  LOCATION 'github-auto://Query-farm/[email protected]'
);

Overview

Query Prometheus-compatible HTTP APIs (Prometheus, Thanos, Mimir, VictoriaMetrics, Grafana Cloud) from DuckDB: PromQL instant and range queries, typed samples with filter pushdown, series metadata, server status and offline PromQL tools.

Catalog

Everything prometheus exposes once attached — read straight from the worker's released build.

prometheus 1 schema
main 18 functions

PromQL queries, raw samples, series metadata and server status from one Prometheus-compatible API, plus offline PromQL tools.

Schema examples (31)
Examples (31)

Current temperature of every node at one site at a fixed time

SELECT instance, value
FROM prometheus.main.query('fixture_temperature_celsius{site="ams"}', time := TIMESTAMPTZ '2026-01-01 00:15:00+00')
ORDER BY instance;

How many targets are up per job right now

SELECT labels['job'] AS job, value AS targets_up
FROM prometheus.main.query('sum by (job) (up)')
ORDER BY job;

Six-hour average and peak temperature per node at one-minute resolution

SELECT instance, avg(value) AS avg_c, max(value) AS max_c
FROM prometheus.main.query_range('fixture_temperature_celsius', TIMESTAMPTZ '2026-01-01 00:00:00+00', TIMESTAMPTZ '2026-01-01 06:00:00+00', 60)
GROUP BY instance
ORDER BY instance;

Hourly request rate by status code from a five-minute rate()

SELECT date_trunc('hour', ts) AS hour, labels['code'] AS code,
  avg(value) AS req_per_s
FROM prometheus.main.query_range('sum by (code) (rate(fixture_requests_total[5m]))', TIMESTAMPTZ '2026-01-01 00:00:00+00', TIMESTAMPTZ '2026-01-01 06:00:00+00', 300)
GROUP BY ALL
ORDER BY hour, code;
27 more examples

Raw samples for two nodes over one hour; the job/instance filters and the ts range are pushed into the PromQL selector and request window

SELECT instance, count(*) AS samples, min(value) AS lo, max(value) AS hi
FROM prometheus.main.samples('fixture_temperature_celsius')
WHERE job = 'fixture' AND instance IN ('node-a:9100', 'node-b:9100') AND ts >= TIMESTAMPTZ '2026-01-01 00:00:00+00' AND ts < TIMESTAMPTZ '2026-01-01 01:00:00+00'
GROUP BY instance
ORDER BY instance;

Five-minute resampled averages per environment and site, with env exposed as a pushdown column

SELECT env, site, avg(value) AS avg_c
FROM prometheus.main.samples('fixture_temperature_celsius', label_columns := 'env,site', step_seconds := 300)
WHERE env LIKE 'prod%' AND ts BETWEEN TIMESTAMPTZ '2026-01-01 00:00:00+00' AND TIMESTAMPTZ '2026-01-01 06:00:00+00'
GROUP BY ALL
ORDER BY ALL;

Cardinality audit: series per metric for one job

SELECT metric, count(*) AS series
FROM prometheus.main.series('{job="fixture"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 06:00:00+00')
GROUP BY metric
ORDER BY series DESC, metric;

How many temperature series each environment contributes

SELECT labels['env'] AS env, count(*) AS series
FROM prometheus.main.series('fixture_temperature_celsius', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00')
GROUP BY env
ORDER BY env;

Which labels the temperature metric carries

SELECT label
FROM prometheus.main.label_names(match := 'fixture_temperature_celsius', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00')
ORDER BY label;

How many distinct label names the server knows

SELECT count(*) AS label_names FROM prometheus.main.label_names();

Every fixture metric name

SELECT value AS metric
FROM prometheus.main.label_values('__name__', match := '{job="fixture"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00')
WHERE value LIKE 'fixture_%'
ORDER BY value;

The instances reporting temperature

SELECT value AS instance
FROM prometheus.main.label_values('instance', match := 'fixture_temperature_celsius', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00')
ORDER BY value;

Type and help text of every fixture metric

SELECT metric, type, help
FROM prometheus.main.metric_metadata()
WHERE metric LIKE 'fixture_%'
ORDER BY metric;

How many metrics of each type the server has seen

SELECT type, count(*) AS metrics
FROM prometheus.main.metric_metadata()
GROUP BY type
ORDER BY metrics DESC, type;

Target health per scrape pool

SELECT scrape_pool, health, count(*) AS targets
FROM prometheus.main.targets(state := 'active')
GROUP BY ALL
ORDER BY ALL;

Down targets and why

SELECT job, instance, last_error
FROM prometheus.main.targets()
WHERE health = 'down'
ORDER BY job, instance;

Every alerting rule with its state

SELECT group_name, rule_name, state, active_alerts
FROM prometheus.main.rules(rule_type := 'alert')
ORDER BY group_name, rule_name;

Rule health summary

SELECT rule_type, health, count(*) AS rules
FROM prometheus.main.rules()
GROUP BY ALL
ORDER BY ALL;

Active alerts with severity

SELECT alert_name, state, labels['severity'] AS severity
FROM prometheus.main.alerts()
ORDER BY alert_name;

Firing alerts per severity

SELECT labels['severity'] AS severity, count(*) AS alerts
FROM prometheus.main.alerts()
WHERE state = 'firing'
GROUP BY severity
ORDER BY alerts DESC;

How many Alertmanagers are active and dropped

SELECT state, count(*) AS alertmanagers
FROM prometheus.main.alertmanagers()
GROUP BY state
ORDER BY state;

Where alerts are being sent

SELECT url
FROM prometheus.main.alertmanagers()
WHERE state = 'active'
ORDER BY url;

The five metrics with the most head series

SELECT name AS metric, value AS series
FROM prometheus.main.tsdb_status(top_n := 5)
WHERE section = 'series_count_by_metric_name'
ORDER BY series DESC, metric;

Head-block totals

SELECT name, value
FROM prometheus.main.tsdb_status()
WHERE section = 'head'
ORDER BY name;

Which Prometheus version the secret points at

SELECT version, go_version FROM prometheus.main.build_info();

Check the server is Prometheus 3.x

SELECT version LIKE '3.%' AS is_v3 FROM prometheus.main.build_info();

Rules whose expression no longer parses with the current PromQL grammar

SELECT rule_name, query
FROM prometheus.main.rules()
WHERE NOT prometheus.main.is_valid(query);

Why each broken rule fails to parse

SELECT rule_name, prometheus.main.parse_error(query) AS problem
FROM prometheus.main.rules()
WHERE prometheus.main.parse_error(query) IS NOT NULL;

Rules that are the same expression written differently

SELECT prometheus.main.format_expr(query) AS canonical, count(*) AS rules
FROM prometheus.main.rules()
GROUP BY 1
HAVING count(*) > 1;

Which metrics the most rules depend on

SELECT m AS metric, count(*) AS rules
FROM prometheus.main.rules(),
     unnest(prometheus.main.metric_names(query)) u(m)
GROUP BY m
ORDER BY rules DESC;

Spread a one-minute budget over each scrape pool's targets

SELECT scrape_pool,
  prometheus.main.duration_seconds('1m') / count(*) AS seconds_per_target
FROM prometheus.main.targets()
GROUP BY scrape_pool;
Scalar functions
duration_seconds (duration VARCHAR) 2 examples

Seconds in a Prometheus duration string such as '5m' or '1h30m' (NULL when invalid)

Arguments
duration VARCHAR
A Prometheus duration string, for example 1h30m. NULL or an invalid duration gives NULL.
ReturnsDOUBLE
Examples (2)

Spread a one-minute budget over each scrape pool's targets

SELECT scrape_pool,
  prometheus.main.duration_seconds('1m') / count(*) AS seconds_per_target
FROM prometheus.main.targets()
GROUP BY scrape_pool;
SELECT d, prometheus.main.duration_seconds(d) AS seconds
FROM (VALUES ('1h30m'), ('5m'), ('250ms'), ('1d'), ('soon')) t(d)
ORDER BY d;
Result
d seconds
1d 86,400
1h30m 5400
250ms 0.25
5m 300
soon NULL
Link
format_expr (expr VARCHAR) 2 examples

Canonical single-line text of a PromQL expression (NULL when it does not parse)

Arguments
expr VARCHAR
PromQL expression text, e.g. 'sum by (job) (rate(http_requests_total[5m]))'. NULL gives NULL.
ReturnsVARCHAR
Examples (2)

Rules that are the same expression written differently

SELECT prometheus.main.format_expr(query) AS canonical, count(*) AS rules
FROM prometheus.main.rules()
GROUP BY 1
HAVING count(*) > 1;
SELECT DISTINCT prometheus.main.format_expr(e) AS canonical
FROM (VALUES ('sum(rate(http_requests_total[5m]))by(job)'), ('sum by (job) (rate(http_requests_total[5m]))')) t(e);
Result
canonical
sum by (job) (rate(http_requests_total[5m]))
Link
is_valid (expr VARCHAR) 2 examples

True when a PromQL expression parses, false otherwise

Arguments
expr VARCHAR
PromQL expression text, e.g. 'sum by (job) (rate(http_requests_total[5m]))'. NULL gives NULL.
ReturnsBOOLEAN
Examples (2)

Rules whose expression no longer parses with the current PromQL grammar

SELECT rule_name, query
FROM prometheus.main.rules()
WHERE NOT prometheus.main.is_valid(query);
SELECT e, prometheus.main.is_valid(e) AS ok
FROM (VALUES ('rate(x[5m])'), ('rate(x[5m]'), ('sum by (job) (up)')) t(e)
ORDER BY e;
Result
e ok
rate(x[5m] false
rate(x[5m]) true
sum by (job) (up) true
Link
metric_names (expr VARCHAR) 2 examples

Sorted distinct metric names a PromQL expression reads (NULL when it does not parse)

Arguments
expr VARCHAR
PromQL expression text, e.g. 'sum by (job) (rate(http_requests_total[5m]))'. NULL gives NULL.
ReturnsVARCHAR[]
Examples (2)

Which metrics the most rules depend on

SELECT m AS metric, count(*) AS rules
FROM prometheus.main.rules(),
     unnest(prometheus.main.metric_names(query)) u(m)
GROUP BY m
ORDER BY rules DESC;
SELECT prometheus.main.metric_names('sum(rate(errors_total[5m])) / sum(rate(requests_total[5m])) > on() group_left vector(0.1) or errors_total') AS metrics;
Result
metrics
["errors_total", "requests_total"]
Link
parse_error (expr VARCHAR) 2 examples

The PromQL parser's error message (with position) for an expression, or NULL when it parses

Arguments
expr VARCHAR
PromQL expression text, e.g. 'sum by (job) (rate(http_requests_total[5m]))'. NULL gives NULL.
ReturnsVARCHAR
Examples (2)

Why each broken rule fails to parse

SELECT rule_name, prometheus.main.parse_error(query) AS problem
FROM prometheus.main.rules()
WHERE prometheus.main.parse_error(query) IS NOT NULL;
SELECT e, prometheus.main.parse_error(e) AS problem
FROM (VALUES ('up'), ('sum(rate(x[5m])')) t(e)
ORDER BY e;
Result
e problem
sum(rate(x[5m]) 1:16: parse error: unclosed left parenthesis
up NULL
Link
Table functions
alertmanagers (secret_name := VARCHAR) 2 examples

List the Alertmanagers the server discovered

Named arguments
secret_name := VARCHAR
Name of the prometheus secret to use when several exist.
Returns columns
url VARCHAR
Alertmanager API URL alerts are sent to.
state VARCHAR
'active' or 'dropped'.
Examples (2)

How many Alertmanagers are active and dropped

SELECT state, count(*) AS alertmanagers
FROM prometheus.main.alertmanagers()
GROUP BY state
ORDER BY state;

Where alerts are being sent

SELECT url
FROM prometheus.main.alertmanagers()
WHERE state = 'active'
ORDER BY url;
Link
alerts (secret_name := VARCHAR) 2 examples

List the currently pending and firing alerts

Named arguments
secret_name := VARCHAR
Name of the prometheus secret to use when several exist.
Returns columns
alert_name VARCHAR
The alertname label.
state VARCHAR
'pending' or 'firing'.
active_at TIMESTAMP WITH TIME ZONE
When the alert became active (pending).
value DOUBLE
Value of the alert expression when last evaluated.
labels MAP(VARCHAR, VARCHAR)
Alert labels.
annotations MAP(VARCHAR, VARCHAR)
Alert annotations.
keep_firing_since TIMESTAMP WITH TIME ZONE
When keep_firing_for started holding the alert; NULL otherwise.
Examples (2)

Active alerts with severity

SELECT alert_name, state, labels['severity'] AS severity
FROM prometheus.main.alerts()
ORDER BY alert_name;

Firing alerts per severity

SELECT labels['severity'] AS severity, count(*) AS alerts
FROM prometheus.main.alerts()
WHERE state = 'firing'
GROUP BY severity
ORDER BY alerts DESC;
Link
build_info (secret_name := VARCHAR) 2 examples

Version and build details of the server

Named arguments
secret_name := VARCHAR
Name of the prometheus secret to use when several exist.
Returns columns
version VARCHAR
Server version, e.g. '3.5.0'.
revision VARCHAR
Source revision.
branch VARCHAR
Source branch.
build_user VARCHAR
Who built it.
build_date VARCHAR
Build date as reported, e.g. '20250714-16:18:17'.
go_version VARCHAR
Go toolchain version.
Examples (2)

Which Prometheus version the secret points at

SELECT version, go_version FROM prometheus.main.build_info();

Check the server is Prometheus 3.x

SELECT version LIKE '3.%' AS is_v3 FROM prometheus.main.build_info();
Link
label_names (match := VARCHAR, start_date := TIMESTAMP WITH TIME ZONE, end_date := TIMESTAMP WITH TIME ZONE, secret_name := VARCHAR) 2 examples

List the label names known to the server, optionally for matching series

Named arguments
match := VARCHAR
Optional series selector restricting which series' labels are listed.
start_date := TIMESTAMP WITH TIME ZONE
Window start.
end_date := TIMESTAMP WITH TIME ZONE
Window end.
secret_name := VARCHAR
Name of the prometheus secret to use when several exist.
Returns columns
label VARCHAR
A label name present on at least one matching series.
Examples (2)

Which labels the temperature metric carries

SELECT label
FROM prometheus.main.label_names(match := 'fixture_temperature_celsius', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00')
ORDER BY label;

How many distinct label names the server knows

SELECT count(*) AS label_names FROM prometheus.main.label_names();
Link
label_values (label VARCHAR, match := VARCHAR, start_date := TIMESTAMP WITH TIME ZONE, end_date := TIMESTAMP WITH TIME ZONE, secret_name := VARCHAR) 2 examples

List the distinct values of one label, optionally for matching series

Positional arguments
label VARCHAR
Label name, e.g. 'job' or '__name__' (metric names).
Named arguments
match := VARCHAR
Optional series selector restricting which series' values are listed.
start_date := TIMESTAMP WITH TIME ZONE
Window start.
end_date := TIMESTAMP WITH TIME ZONE
Window end.
secret_name := VARCHAR
Name of the prometheus secret to use when several exist.
Returns columns
value VARCHAR
One distinct value of the label.
Examples (2)

Every fixture metric name

SELECT value AS metric
FROM prometheus.main.label_values('__name__', match := '{job="fixture"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00')
WHERE value LIKE 'fixture_%'
ORDER BY value;

The instances reporting temperature

SELECT value AS instance
FROM prometheus.main.label_values('instance', match := 'fixture_temperature_celsius', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00')
ORDER BY value;
Link
metric_metadata (metric := VARCHAR, secret_name := VARCHAR) 2 examples

List each metric's type, help text and unit

Named arguments
metric := VARCHAR
Only this metric's metadata; default: every metric.
secret_name := VARCHAR
Name of the prometheus secret to use when several exist.
Returns columns
metric VARCHAR
Metric family name (for counters the name without _total, as exposed in # TYPE).
type VARCHAR
Metric type: counter, gauge, histogram, gaugehistogram, summary, info, stateset or unknown.
help VARCHAR
HELP text; NULL when empty.
unit VARCHAR
UNIT (OpenMetrics); NULL when empty.
Examples (2)

Type and help text of every fixture metric

SELECT metric, type, help
FROM prometheus.main.metric_metadata()
WHERE metric LIKE 'fixture_%'
ORDER BY metric;

How many metrics of each type the server has seen

SELECT type, count(*) AS metrics
FROM prometheus.main.metric_metadata()
GROUP BY type
ORDER BY metrics DESC, type;
Link
query (promql VARCHAR, time := TIMESTAMP WITH TIME ZONE, secret_name := VARCHAR) 2 examples

Evaluate a PromQL expression at one instant and return the result series as rows

Positional arguments
promql VARCHAR
PromQL expression, e.g. 'sum by (job) (rate(http_requests_total[5m]))'.
Named arguments
time := TIMESTAMP WITH TIME ZONE
Evaluation time. Omit or NULL for the server's current time.
secret_name := VARCHAR
Name of the prometheus secret to use when several exist; default: the unscoped one.
Returns columns
result_type VARCHAR
PromQL result type: vector, matrix, scalar or string.
metric VARCHAR
Metric name (the __name__ label); NULL for expressions that drop it, e.g. rate() or sum().
job VARCHAR
Value of the 'job' label; NULL when the series has no such label.
instance VARCHAR
Value of the 'instance' label; NULL when the series has no such label.
labels MAP(VARCHAR, VARCHAR)
Every label of the series, __name__ included, as MAP(VARCHAR, VARCHAR). Read one with labels['env'].
ts TIMESTAMP WITH TIME ZONE
Sample timestamp (UTC, millisecond precision).
value DOUBLE
Float sample value; NaN, +Inf and -Inf are kept. NULL for native-histogram and string results.
histogram STRUCT of 3 fields
Native-histogram sample (count, sum, buckets with bounds and inclusivity); NULL for float samples.
STRUCT 3 fields
  • countDOUBLE
  • sumDOUBLE
  • bucketsSTRUCT[]
    STRUCT[] 5 fields
    • lowerDOUBLE
    • upperDOUBLE
    • countDOUBLE
    • lower_inclusiveBOOLEAN
    • upper_inclusiveBOOLEAN
string_value VARCHAR
Value of a PromQL string result; NULL otherwise.
Examples (2)

Current temperature of every node at one site at a fixed time

SELECT instance, value
FROM prometheus.main.query('fixture_temperature_celsius{site="ams"}', time := TIMESTAMPTZ '2026-01-01 00:15:00+00')
ORDER BY instance;

How many targets are up per job right now

SELECT labels['job'] AS job, value AS targets_up
FROM prometheus.main.query('sum by (job) (up)')
ORDER BY job;
Link
query_range (promql VARCHAR, start_date TIMESTAMP WITH TIME ZONE, end_date TIMESTAMP WITH TIME ZONE, step_seconds DOUBLE, max_points_per_chunk := BIGINT, secret_name := VARCHAR) 2 examples

Evaluate a PromQL expression over a time range at a fixed step, chunked under the server's point limit

Positional arguments
promql VARCHAR
PromQL expression evaluated at every step.
start_date TIMESTAMP WITH TIME ZONE
First evaluation time.
end_date TIMESTAMP WITH TIME ZONE
Last evaluation time; inclusive.
step_seconds DOUBLE
Resolution step in seconds (e.g. 60). Never changed by the worker.
Named arguments
max_points_per_chunk := BIGINT
Evaluation points per request; long ranges are split into chunks of this many steps (Prometheus rejects more than 11000). · default 11000
secret_name := VARCHAR
Name of the prometheus secret to use when several exist.
Returns columns
result_type VARCHAR
PromQL result type: vector, matrix, scalar or string.
metric VARCHAR
Metric name (the __name__ label); NULL for expressions that drop it, e.g. rate() or sum().
job VARCHAR
Value of the 'job' label; NULL when the series has no such label.
instance VARCHAR
Value of the 'instance' label; NULL when the series has no such label.
labels MAP(VARCHAR, VARCHAR)
Every label of the series, __name__ included, as MAP(VARCHAR, VARCHAR). Read one with labels['env'].
ts TIMESTAMP WITH TIME ZONE
Sample timestamp (UTC, millisecond precision).
value DOUBLE
Float sample value; NaN, +Inf and -Inf are kept. NULL for native-histogram and string results.
histogram STRUCT of 3 fields
Native-histogram sample (count, sum, buckets with bounds and inclusivity); NULL for float samples.
STRUCT 3 fields
  • countDOUBLE
  • sumDOUBLE
  • bucketsSTRUCT[]
    STRUCT[] 5 fields
    • lowerDOUBLE
    • upperDOUBLE
    • countDOUBLE
    • lower_inclusiveBOOLEAN
    • upper_inclusiveBOOLEAN
string_value VARCHAR
Value of a PromQL string result; NULL otherwise.
Examples (2)

Six-hour average and peak temperature per node at one-minute resolution

SELECT instance, avg(value) AS avg_c, max(value) AS max_c
FROM prometheus.main.query_range('fixture_temperature_celsius', TIMESTAMPTZ '2026-01-01 00:00:00+00', TIMESTAMPTZ '2026-01-01 06:00:00+00', 60)
GROUP BY instance
ORDER BY instance;

Hourly request rate by status code from a five-minute rate()

SELECT date_trunc('hour', ts) AS hour, labels['code'] AS code,
  avg(value) AS req_per_s
FROM prometheus.main.query_range('sum by (code) (rate(fixture_requests_total[5m]))', TIMESTAMPTZ '2026-01-01 00:00:00+00', TIMESTAMPTZ '2026-01-01 06:00:00+00', 300)
GROUP BY ALL
ORDER BY hour, code;
Link
rules (rule_type := VARCHAR, secret_name := VARCHAR) 2 examples

List recording and alerting rules with their health and state

Named arguments
rule_type := VARCHAR
Which rules: 'alert', 'record' or 'any'. · default "any"
secret_name := VARCHAR
Name of the prometheus secret to use when several exist.
Returns columns
group_name VARCHAR
Rule group name.
group_file VARCHAR
File the group was loaded from.
group_interval_seconds DOUBLE
Group evaluation interval in seconds.
rule_name VARCHAR
Alert name or recorded metric name.
rule_type VARCHAR
'alerting' or 'recording'.
query VARCHAR
The rule's PromQL expression.
duration_seconds DOUBLE
Alerting rules: the 'for' duration in seconds; NULL for recording rules.
keep_firing_for_seconds DOUBLE
Alerting rules: keep_firing_for in seconds; NULL for recording rules.
labels MAP(VARCHAR, VARCHAR)
Labels the rule adds.
annotations MAP(VARCHAR, VARCHAR)
Alerting rules: annotations; empty for recording rules.
health VARCHAR
'ok', 'err' or 'unknown'.
last_error VARCHAR
Last evaluation error; NULL when none.
state VARCHAR
Alerting rules: 'firing', 'pending' or 'inactive'; NULL for recording rules.
active_alerts BIGINT
Alerting rules: number of active (pending or firing) alerts; NULL for recording rules.
last_evaluation TIMESTAMP WITH TIME ZONE
Time of the rule's last evaluation; NULL if never evaluated.
evaluation_time_seconds DOUBLE
Duration of the last evaluation in seconds.
Examples (2)

Every alerting rule with its state

SELECT group_name, rule_name, state, active_alerts
FROM prometheus.main.rules(rule_type := 'alert')
ORDER BY group_name, rule_name;

Rule health summary

SELECT rule_type, health, count(*) AS rules
FROM prometheus.main.rules()
GROUP BY ALL
ORDER BY ALL;
Link
samples (metric VARCHAR, label_columns := VARCHAR, step_seconds := DOUBLE, start_date := TIMESTAMP WITH TIME ZONE, end_date := TIMESTAMP WITH TIME ZONE, chunk_seconds := BIGINT, max_points_per_chunk := BIGINT, secret_name := VARCHAR) 2 examples

Stored or resampled samples of one metric as typed rows; label and time filters push down into the PromQL selector

Positional arguments
metric VARCHAR
Metric name (e.g. 'node_load1') or a full series selector (e.g. 'up{job="api"}'); SQL filters add matchers to it.
Named arguments
label_columns := VARCHAR
Comma-separated label names to expose as their own columns (in addition to metric/job/instance) so they can be filtered and pushed down, e.g. 'env,region'. · default ""
step_seconds := DOUBLE
0 (default) returns raw stored samples; > 0 evaluates the selector at this fixed step (query_range). · default 0
start_date := TIMESTAMP WITH TIME ZONE
Window start when not given by a WHERE ts >= ... predicate.
end_date := TIMESTAMP WITH TIME ZONE
Window end (inclusive) when not given by WHERE ts <= ...; default: now.
chunk_seconds := BIGINT
Raw mode: seconds of data fetched per request. · default 3600
max_points_per_chunk := BIGINT
Step mode: evaluation points per request (Prometheus rejects more than 11000). · default 11000
secret_name := VARCHAR
Name of the prometheus secret to use when several exist.
Returns columns
metric VARCHAR
The __name__ label.
job VARCHAR
The job label (NULL when absent).
instance VARCHAR
The instance label (NULL when absent).
<label> VARCHAR
One per label_columns entry, e.g. `env`; NULL when the series lacks the label.
labels MAP(VARCHAR, VARCHAR)
Every label of the series.
ts TIMESTAMP WITH TIME ZONE
Sample time.
value DOUBLE
Float value (NaN/Inf kept); NULL for native histograms.
histogram STRUCT
Native-histogram sample; NULL for float samples.
Returns columns · depends on the arguments
metric VARCHAR
The __name__ label.
job VARCHAR
The job label (NULL when absent).
instance VARCHAR
The instance label (NULL when absent).
<label> VARCHAR
One per label_columns entry, e.g. `env`; NULL when the series lacks the label.
labels MAP(VARCHAR, VARCHAR)
Every label of the series.
ts TIMESTAMP WITH TIME ZONE
Sample time.
value DOUBLE
Float value (NaN/Inf kept); NULL for native histograms.
histogram STRUCT
Native-histogram sample; NULL for float samples.
Examples (2)

Raw samples for two nodes over one hour; the job/instance filters and the ts range are pushed into the PromQL selector and request window

SELECT instance, count(*) AS samples, min(value) AS lo, max(value) AS hi
FROM prometheus.main.samples('fixture_temperature_celsius')
WHERE job = 'fixture' AND instance IN ('node-a:9100', 'node-b:9100') AND ts >= TIMESTAMPTZ '2026-01-01 00:00:00+00' AND ts < TIMESTAMPTZ '2026-01-01 01:00:00+00'
GROUP BY instance
ORDER BY instance;

Five-minute resampled averages per environment and site, with env exposed as a pushdown column

SELECT env, site, avg(value) AS avg_c
FROM prometheus.main.samples('fixture_temperature_celsius', label_columns := 'env,site', step_seconds := 300)
WHERE env LIKE 'prod%' AND ts BETWEEN TIMESTAMPTZ '2026-01-01 00:00:00+00' AND TIMESTAMPTZ '2026-01-01 06:00:00+00'
GROUP BY ALL
ORDER BY ALL;
Link
series (match VARCHAR, start_date := TIMESTAMP WITH TIME ZONE, end_date := TIMESTAMP WITH TIME ZONE, secret_name := VARCHAR) 2 examples

List the series (label sets) that match a selector in a time window

Positional arguments
match VARCHAR
Series selector, e.g. 'up' or '{job="api"}'.
Named arguments
start_date := TIMESTAMP WITH TIME ZONE
Only series with samples after this time.
end_date := TIMESTAMP WITH TIME ZONE
Only series with samples before this time.
secret_name := VARCHAR
Name of the prometheus secret to use when several exist.
Returns columns
metric VARCHAR
Metric name (the __name__ label); NULL when absent.
job VARCHAR
The job label; NULL when absent.
instance VARCHAR
The instance label; NULL when absent.
labels MAP(VARCHAR, VARCHAR)
Every label of the series, __name__ included.
Examples (2)

Cardinality audit: series per metric for one job

SELECT metric, count(*) AS series
FROM prometheus.main.series('{job="fixture"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 06:00:00+00')
GROUP BY metric
ORDER BY series DESC, metric;

How many temperature series each environment contributes

SELECT labels['env'] AS env, count(*) AS series
FROM prometheus.main.series('fixture_temperature_celsius', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00')
GROUP BY env
ORDER BY env;
Link
targets (state := VARCHAR, secret_name := VARCHAR) 2 examples

List scrape targets with health, last scrape and labels

Named arguments
state := VARCHAR
Which targets: 'active' (being scraped), 'dropped' (removed by relabelling) or 'any'. · default "any"
secret_name := VARCHAR
Name of the prometheus secret to use when several exist.
Returns columns
state VARCHAR
'active' or 'dropped'.
scrape_pool VARCHAR
Scrape pool (usually the job_name of the scrape config).
scrape_url VARCHAR
URL scraped; NULL for dropped targets.
global_url VARCHAR
Scrape URL with the server's external hostname.
health VARCHAR
'up', 'down' or 'unknown'; NULL for dropped targets.
last_error VARCHAR
Last scrape error; NULL when the last scrape succeeded.
last_scrape TIMESTAMP WITH TIME ZONE
Time of the last scrape; NULL if never scraped.
last_scrape_duration_seconds DOUBLE
Duration of the last scrape in seconds.
scrape_interval VARCHAR
Configured scrape interval, e.g. '15s'.
scrape_timeout VARCHAR
Configured scrape timeout, e.g. '10s'.
job VARCHAR
The target's job label.
instance VARCHAR
The target's instance label.
labels MAP(VARCHAR, VARCHAR)
Target labels after relabelling (empty for dropped targets).
discovered_labels MAP(VARCHAR, VARCHAR)
Labels from service discovery, before relabelling.
Examples (2)

Target health per scrape pool

SELECT scrape_pool, health, count(*) AS targets
FROM prometheus.main.targets(state := 'active')
GROUP BY ALL
ORDER BY ALL;

Down targets and why

SELECT job, instance, last_error
FROM prometheus.main.targets()
WHERE health = 'down'
ORDER BY job, instance;
Link
tsdb_status (top_n := BIGINT, secret_name := VARCHAR) 2 examples

Head-block cardinality statistics and top-N lists

Named arguments
top_n := BIGINT
Entries per top-N list (the API's limit parameter). · default 10
secret_name := VARCHAR
Name of the prometheus secret to use when several exist.
Returns columns
section VARCHAR
'head' (head-block totals), 'series_count_by_metric_name', 'label_value_count_by_label_name', 'memory_in_bytes_by_label_name' or 'series_count_by_label_value_pair'.
name VARCHAR
Statistic or entry name (for head: num_series, num_label_pairs, chunk_count, min_time, max_time).
value BIGINT
Count, bytes, or for head min_time/max_time Unix milliseconds.
Examples (2)

The five metrics with the most head series

SELECT name AS metric, value AS series
FROM prometheus.main.tsdb_status(top_n := 5)
WHERE section = 'series_count_by_metric_name'
ORDER BY series DESC, metric;

Head-block totals

SELECT name, value
FROM prometheus.main.tsdb_status()
WHERE section = 'head'
ORDER BY name;
Link

Credentials

The secret type prometheus declares, as reported by the worker itself.

prometheus

How to get these credentials

Connection to a Prometheus-compatible HTTP API (Prometheus, Thanos, Mimir, Cortex, VictoriaMetrics, Grafana Cloud, Amazon Managed Prometheus).

secret.sql
CREATE SECRET prometheus (
    TYPE prometheus,
    base_url      '<base_url>',
    bearer_token  '<BEARER_TOKEN>',  -- secret
    username      '<username>',
    password      '<PROMETHEUS_PASSWORD>',  -- secret
    tenant_id     '<tenant_id>',
    extra_headers '<PROMETHEUS_EXTRA_HEADERS>'  -- secret
);
Key Type Required Description
base_url VARCHAR — Server root, e.g. 'http://prometheus:9090' or 'https://prometheus-prod-01.grafana.net/api/prom'. /api/v1/... is appended.
bearer_token secret VARCHAR — Token sent as 'Authorization: Bearer <token>'.
username VARCHAR — Basic-auth user name (Grafana Cloud: the instance id).
password secret VARCHAR — Basic-auth password or API key.
tenant_id VARCHAR — Tenant sent as the X-Scope-OrgID header (Mimir, Cortex, Loki-style multi-tenancy).
extra_headers secret VARCHAR — Additional request headers as a JSON object, e.g. '{"X-Custom": "v"}'.

The worker doesn't mark which keys are required.

Needed by alertmanagersalertsbuild_infolabel_nameslabel_valuesmetric_metadataqueryquery_rangerulessamplesseriestargets and 1 more functions

Create the secret in the same session, after attaching prometheus — the worker registers its secret types at ATTACH. Keys marked secret are masked in duckdb_secrets(); angle-bracket values are placeholders. Read credentials from your environment or secret store in your application and pass them through your SQL client’s parameter bindings. Keep real values out of saved SQL and history. Native DuckDB and Haybarn do not provide a SQL getenv() function.

Try these queries

Convert durations

SELECT d, prometheus.main.duration_seconds(d) AS seconds
FROM (VALUES ('1h30m'), ('5m'), ('250ms'), ('1d'), ('soon')) t(d)
ORDER BY d;
Result
d seconds
1d 86,400
1h30m 5400
250ms 0.25
5m 300
soon NULL
Example output · captured
Connector release
v0.2.1
Engine
2.0.1
VGI protocol
3.4.0

Uses duration_seconds

Check three expressions

SELECT e, prometheus.main.is_valid(e) AS ok
FROM (VALUES ('rate(x[5m])'), ('rate(x[5m]'), ('sum by (job) (up)')) t(e)
ORDER BY e;
Result
e ok
rate(x[5m] false
rate(x[5m]) true
sum by (job) (up) true
Example output · captured
Connector release
v0.2.1
Engine
2.0.1
VGI protocol
3.4.0

Uses is_valid

Errors for a broken and a valid expression

SELECT e, prometheus.main.parse_error(e) AS problem
FROM (VALUES ('up'), ('sum(rate(x[5m])')) t(e)
ORDER BY e;
Result
e problem
sum(rate(x[5m]) 1:16: parse error: unclosed left parenthesis
up NULL
Example output · captured
Connector release
v0.2.1
Engine
2.0.1
VGI protocol
3.4.0

Uses parse_error

Two spellings, one canonical form

SELECT DISTINCT prometheus.main.format_expr(e) AS canonical
FROM (VALUES ('sum(rate(http_requests_total[5m]))by(job)'), ('sum by (job) (rate(http_requests_total[5m]))')) t(e);
Result
canonical
sum by (job) (rate(http_requests_total[5m]))
Example output · captured
Connector release
v0.2.1
Engine
2.0.1
VGI protocol
3.4.0

Uses format_expr

Metrics read by a ratio query

SELECT prometheus.main.metric_names('sum(rate(errors_total[5m])) / sum(rate(requests_total[5m])) > on() group_left vector(0.1) or errors_total') AS metrics;
Result
metrics
["errors_total", "requests_total"]
Example output · captured
Connector release
v0.2.1
Engine
2.0.1
VGI protocol
3.4.0

Uses metric_names

Current temperature of every node at one site at a fixed time

SELECT instance, value
FROM prometheus.main.query('fixture_temperature_celsius{site="ams"}', time := TIMESTAMPTZ '2026-01-01 00:15:00+00')
ORDER BY instance

Uses query

29 more examples in the Catalog, each listed under the table or function it uses.

Questions it can answer

Plain-English questions from the worker's agent test tasks. An AI agent with this catalog attached should answer each one with SQL.

  • Using the prometheus worker, give the canonical form of the PromQL 'sum(rate(http_requests_total[5m]))by(job)'.
  • Using the prometheus worker, how many seconds is the Prometheus duration '1h30m'?
  • What was fixture_temperature_celsius for each instance at 2026-01-01 00:15:00 UTC?
  • Evaluate fixture_temperature_celsius every 60 seconds from 2026-01-01 00:00 to 06:00 UTC: how many points per instance?
  • How many raw stored samples does fixture_temperature_celsius have for instance node-a:9100 between 2026-01-01 00:00 (inclusive) and 01:00 UTC (exclusive)?
  • How many series does job 'fixture' have per metric name between 2026-01-01 00:00 and 06:00 UTC?

Prometheus is an independent open-source connector from Query.Farm. It is not affiliated with, endorsed by or sponsored by the services, projects or organisations it works with. Product names, logos and trademarks belong to their respective owners.