Run SQL over the API

POST /v1/projects/{project_id}/sql: request and response, the dialect, the tables you can read, the row cap, the time bound, the scope, variables and a recipe for per-person counts.

Embed
Preview of the card
<a href="https://lucidace.com/help/sql-api"><img src="https://lucidace.com/help/_api/public/orgs/af34862a-c837-4478-8335-0505efe40459/spaces/2f4b888b-c4e6-488b-81bd-6e838fb12d2e/pages/7774860f-45d6-490f-9a63-3104be3c567d/social-card.svg?v=3e7ae33eec8b" alt="Run SQL over the API" width="600" height="315"></a>

POST /v1/projects/{project_id}/sql runs one read-only SELECT against your project's data and answers rows. Use it when the query API has no shape for the question. It is the same engine as the SQL editor in the app.

Request

curl -X POST "$LUCIDA_API/v1/projects/$PROJECT/sql" \
  -H "Authorization: Bearer $LUCIDA_KEY" -H "Content-Type: application/json" \
  -d '{"sql": "SELECT event, count() AS n FROM events WHERE timestamp >= now() - INTERVAL 7 DAY GROUP BY event ORDER BY n DESC LIMIT 20"}'

Field

Meaning

sql

required; one SELECT

variables

object of {variables.name} values, see below

date_range, filters, interval, breakdown

values for the {filters} placeholders; only used if the SQL contains them. date_range is {from, to?, explicit?}; unless explicit, days snap to whole UTC days

refresh

true skips the result cache

explain

true adds meta.generated_sql, the rewritten ClickHouse text with tenant scoping internals; off by default

validate_only

true compiles with your access and answers {valid, kind, columns} without running

Response

{"columns": ["event", "n"], "rows": [["$pageview", 1204], ["signup", 87]],
 "meta": {"limit": 20, "truncated": false, "tables": ["events"], "injected_bounds": [],
          "warnings": [], "cache_hit": false, "execution_ms": 41}}

rows are arrays in columns order. meta.generated_sql appears only with "explain": true. meta also carries rows_read, computed_at and sql_hash. A query still running after 5 seconds answers 202 with a query_id; poll GET /v1/projects/{project_id}/query/{query_id}. A compile error is 400 problem+json with message, line and column. Other answers: 404 (no access), 422, 429 (rate limit), 503.

Dialect

ClickHouse SQL, restricted to a plain SELECT (CTEs, joins, subqueries and window functions are fine). Refused with 400: any statement other than SELECT, SETTINGS and FORMAT clauses, INTO, recursive CTEs, table functions and x IN <table name>. Function names are checked against an allow-list. Identifiers may contain $, and event properties are read as properties.$browser or properties.plan. Strings use single quotes.

Tables

Table

One row per

events

event: uuid, event, distinct_id, person_id, session_id, timestamp, environment, properties, person_properties, source, elements_chain, is_internal, plus hot property columns such as $current_url, $pathname, $browser, $os, $device_type, $country, $channel

persons

person: person_id, properties, created_at, last_seen_at, platform

sessions

session: session_id, distinct_id, session_start, session_end, pageviews, events, entry_url, exit_url, channel, device_type, country, duration_s, ...

groups, replays, cohort_members, activity_log, sql_view_rows

groups, recordings, cohort membership, audit entries, rows of your saved SQL views

warehouse_rows and your SQL views

synced warehouse data and views you saved

GET /v1/projects/{project_id}/sql/schema lists exactly the tables and columns your key can read, with their types. Restricted properties and hidden warehouse tables are masked or removed for keys that may not see them. Every table is pinned to the project in the URL.

Events with no persons row

Not every event has a row in persons. An event sent with "$process_person_profile": false (the same flag the gateway reads on every capture route) is personless: Lucida never creates or updates a person for it. Its person_id is a stable id derived from distinct_id (so unique-user counts stay right) unless that id already belongs to a known person, but persons has no row for it. The same holds for events Lucida itself sends personless: log-drain events, group updates ($groupidentify) and the system events below. An inner join persons therefore drops them silently; use left join and expect NULL person columns:

SELECT e.event, e.distinct_id, p.properties.email AS email
FROM events e
LEFT JOIN persons p ON p.person_id = e.person_id
WHERE e.timestamp >= now() - INTERVAL 7 DAY
LIMIT 100

Lucida's own system events

Lucida writes a few events of its own into your project (so alert rules and workflows can trigger on them). They are kept out of your data: events in /sql, the default insights, the event list and the event taxonomy never include the health-issue events below, so a plain select count() from events counts only events your own code and SDKs sent. Read them explicitly from the system_events table, which has the same columns as events:

SELECT timestamp, event, properties.issue_id, properties.severity
FROM system_events
ORDER BY timestamp DESC
LIMIT 50

event

distinct_id

Table

When

$lc_health_issue_firing, $lc_health_issue_resolved

lucida:health

system_events

a project health issue (for example a broken tracking setup or a guide with no shows) starts or stops; properties issue_id, kind, severity, title; alert rules and workflows can trigger on them

$lc_agent_run, $lc_agent_record

$lc_agent:<agent id>

events

activity reported by an AI agent. You asked for these (they are your agents' activity), so they stay in events and can be charted

The split is by event name (the two health-issue names), not by a column, so there is nothing to filter. The system events are still stored with the same retention and still trigger alerts and workflows; they are only left out of events. properties.$process_person_profile = false finds every personless event, in either table.

Row cap and the time bound

  • Row cap. With no LIMIT, 100 rows come back and meta.truncated says whether more matched. LIMIT may be at most 50,000; a larger one is 400.

  • Time bound. Reading events with no condition on timestamp gets AND timestamp >= now() - INTERVAL 90 DAY added, and meta.injected_bounds names it. A SELECT that compares timestamp itself (or sits inside one that does) is left alone, so state the window you mean: WHERE timestamp >= '2026-10-01 00:00:00'. A CTE keeps the whole query's rule.

  • Cost. An API key's query may read at most 10 GiB (LC_QUERY_KEY_MAX_BYTES on a self-hosted install, 0 lifts it) and is limited to 120 calls a minute per key and project, before any plan factor.

Scope

A project key or account key needs insight:read (the older query:read and *:read also work) on the project; without access the answer is 404. Properties the key may not read are masked.

Variables

{variables.name} is replaced by a literal from variables before the query is parsed, so a value can never change the query's shape or reach more than the key may read. Strings are quoted and escaped, numbers and booleans are written as they are, null is NULL, and an object is 400. A placeholder with no value is 400 ("variable has no value"). An array variable renders as a list for IN: distinct_id IN {variables.ids} with "ids": ["a", "b"] is sent to the query as distinct_id IN ['a', 'b'] (an empty array matches nothing), and meta.generated_sql (with explain) shows it as IN (['a', 'b']). Both forms run.

Recipe: count and first time of an event per distinct_id

For a list of ids, how many times each did signup since a time, and when first:

curl -X POST "$LUCIDA_API/v1/projects/$PROJECT/sql" \
  -H "Authorization: Bearer $LUCIDA_KEY" -H "Content-Type: application/json" -d '{
  "sql": "SELECT distinct_id, count() AS n, min(timestamp) AS first_at FROM events WHERE event = {variables.event} AND timestamp >= {variables.since} AND distinct_id IN {variables.ids} GROUP BY distinct_id ORDER BY first_at LIMIT 1000",
  "variables": {"event": "signup", "since": "2026-10-01 00:00:00", "ids": ["user_123", "user_456", "user_789"]}
}'

Add "refresh": true when you poll for events you just sent: identical queries can answer from the result cache. An id with no matching event is missing from rows, not a zero row; fill those in on your side. The time is compared in UTC. Keep the id list in the low thousands; for more, send them in batches and merge. If the answer has "truncated": true, raise LIMIT (up to 50,000) or split the list.

Updated