SQL CookbookResponses & answers

SQL COOKBOOK · RESPONSES

Responses & answers

Every answer in HiveCFM is stored under a key you cannot guess. Here is how to find out what the keys mean, and then what to do with them.

"Response".data is a jsonb object whose keys are survey element ids — cuids like i2fke6x7sch7i8ols37hw62s. Not question numbers. Not question text. Not a key you can derive from anything about the question: two independently authored surveys asking the identical NPS question have different keys for it. Across the 1191 surveys in the hivecfm database, no element id appears in more than one survey.

One exception is worth knowing, because it cuts the other way. Duplicating a survey does not re-key it. The Duplicate action calls copySurveyToOtherEnvironment with the current environment as the target (apps/web/modules/survey/list/components/survey-dropdown-menu.tsx:103-106), and that function assigns a fresh survey id and then deep-clones the blocks verbatim — id: createId() and blocks: structuredClone(existingSurvey.blocks) at apps/web/modules/survey/list/lib/survey.ts:387 and :392. So a duplicate shares every element id with its original. The same function backs copy-to-another-environment, so one element id can also occur in two environments; that is not a read hazard, because a data key is only reachable through r."surveyId" and a survey belongs to exactly one environment. The practical rule: an element id identifies a question, never a survey and never a tenant — always pair it with a surveyId and the tenant predicate below.

There is also no nps_score column on "Response" at origin/development. Nor csat_score, ces_score, or fcr_score:

echo "select column_name from information_schema.columns
      where table_name='Response'
        and column_name in ('nps_score','csat_score','ces_score','fcr_score');" \
  | docker exec -i hivecfm-postgres-t3060 psql -U postgres -d devhub_ref
# (0 rows)

The same query against the migration-era hivecfm database returns all four. That is where the folklore comes from — those columns are real on a migrator-branch schema and absent at this ref. The nearest stored analogue here is the "kpiScores" jsonb, and it is not the same measure — CSAT and CES are bucket-normalized, NPS is a per-response percentage, and all of it is frozen at write time. Recipe 4 works through the difference. If someone hands you a query with r.nps_score in it, they were working against the other schema.

The tenant predicate on this page. "Response" has no environmentId column — verified, zero rows returned for it in information_schema.columns on devhub_ref. The tenant is reachable only through the survey, so every recipe below joins and filters:

FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id'

Recipe 1 reads "Survey" alone and so filters s."environmentId" directly with no join. Everything that touches "Response" needs the join above.

Why explicit rather than relying on RLS: Read this first → RLS and tenancy.

Recipes below use the psql variables :'environment_id', :'survey_id', and :'element_id' — the quoted form the rest of this section uses; see Read this first for why bare :environment_id fails. Where a recipe is followed by real output, the run substituted the environment cmr0o5ivu000clc01glv55m4p and a real survey and element from the hivecfm database — which is also why the EXPLAIN output shows literals rather than parameters. Recipes 3 and 4 keep the element id inline rather than as a placeholder, because the query text is per-survey either way.

1. Resolve a survey’s element ids

Do this first. Every other recipe on this page needs the output.

SELECT b->>'id'                  AS block_id,
       e->>'id'                  AS element_id,
       e->>'type'                AS element_type,
       e->'headline'->>'default' AS headline
FROM "Survey" s,
     unnest(s.blocks)                    AS b,
     jsonb_array_elements(b->'elements')  AS e
WHERE s."environmentId" = :'environment_id'
  AND s.id             = :'survey_id';

Returns one row per element, in block order then element order, with the id you will paste into every later query.

Sample-run on hivecfm against survey zy219msndbi6ujs9jd4gccto:

         block_id         |        element_id        | element_type |            headline
--------------------------+--------------------------+--------------+------------------------------
 cm4za147fu1sh2zm9twmbay7 | i2fke6x7sch7i8ols37hw62s | nps          | Based on your recent visit…
 ljvcd7b436tmnf9yh2tzg1fm | atp92mq8s1oshvz6fqcrxu8w | openText     | Will you visit us again?
 xppovz2klcf0tlln8h2pkfzf | pg6d28nxcvxu6pvpv4vlllg3 | rating       | To what extent would you say…

EXPLAINed on devhub_ref, which shows the shape of the traversal:

 Nested Loop
   ->  Nested Loop
         ->  Index Scan using "Survey_environmentId_updated_at_idx" on "Survey" s
               Index Cond: ("environmentId" = 'cmr0o5ivu000clc01glv55m4p'::text)
               Filter: (id = 'zy219msndbi6ujs9jd4gccto'::text)
         ->  Function Scan on unnest b
   ->  Function Scan on jsonb_array_elements e

Why unnest() and not jsonb_array_elements()

Survey.blocks is jsonb[] — a Postgres array whose members are jsonb — not a single jsonb array. The catalog is unambiguous:

echo "select column_name, data_type, udt_name from information_schema.columns
      where table_name='Survey' and column_name in ('blocks','questions');" \
  | docker exec -i hivecfm-postgres-t3060 psql -U postgres -d devhub_ref
#  blocks    | ARRAY | _jsonb
#  questions | jsonb | jsonb

So you need unnest() for the outer level (array → rows) and jsonb_array_elements() for the inner level (b->'elements', a jsonb array → rows). Getting it backwards fails at parse time in both directions, with an error that names the type rather than the mistake — ERROR: function jsonb_array_elements(jsonb[]) does not exist and ERROR: function unnest(jsonb) does not exist, both reproduced against hivecfm.

Every block carries id, name and elements, and a block with skip logic also carries logic and logicFallback. Those five are the entire key set across every block of all 1191 surveys in hivecfm, and 37 of those surveys have at least one block carrying logic:

-- schema-shape probe, deliberately not tenant-scoped: it asks what keys the
-- column can hold, not what one tenant's data says.
select distinct k from "Survey" s, unnest(s.blocks) b, jsonb_object_keys(b) k;

Response.data keys are element ids, never block ids.

Caveats

  • A survey with no blocks returns zero rows, not an error. unnest() and jsonb_array_elements() are both strict: unnest(NULL::jsonb[]) and jsonb_array_elements(NULL::jsonb) each return 0 rows (measured). So an empty result set is ambiguous — it can mean “survey not in this environment”, “survey id wrong”, or “survey has no blocks”. Check array_length(s.blocks, 1) separately before concluding anything. What does error is a non-array in elements: jsonb_array_elements('"scalar"'::jsonb) gives ERROR: cannot extract elements from a scalar.
  • headline is an i18n object, and 'default' is a convention, not a guarantee. e->'headline' is keyed by language code plus default. ->>'default' returns NULL for an element whose headline lacks that key. Measured over all 5420 elements in hivecfm, the key counts are default 5420, en 4896, ar 358, fr 182, an 3, aa 1 — so default was present on every element there and is reliable in practice, but a NULL headline in your output is a missing key, not a missing question.
  • The legacy questions column still exists. "Survey".questions is a plain jsonb array from before the blocks model, and countAnsweredQuestions (apps/web/lib/response/utils.ts:50-65) still accepts ids found there. A blocks-only resolution under-reports for a pre-blocks survey. In the hivecfm database questions was empty for all 1191 surveys, so the legacy path is dormant there — do not assume that holds on an older tenant.
  • Element types are a closed set of 15, defined in packages/types/surveys/elements.ts:18-34: fileUpload, openText, multipleChoiceSingle, multipleChoiceMulti, nps, cta, rating, consent, pictureSelection, cal, date, matrix, address, ranking, contactInfo. Read the type off this query rather than inferring it from a headline.

2. Extract one question’s answers

SELECT r.id                                             AS response_id,
       r.created_at,
       r.language,
       r.data -> :'element_id'                            AS answer,
       jsonb_typeof(r.data -> :'element_id')              AS answer_type
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id'
  AND r."surveyId"      = :'survey_id'
  AND r.data ? :'element_id'
ORDER BY r.created_at DESC;

Returns one row per response that actually answered that element, newest first, with the raw jsonb value and its type.

Sample-run on hivecfm for the NPS element above. The query returned 16 rows; these are the first three:

       response_id        |       created_at        | language | answer | answer_type
--------------------------+-------------------------+----------+--------+-------------
 y003pjbj2mubvtuwv65x4s19 | 2025-02-13 09:33:52.223 |          | 4      | number
 yqavyk5r6goz93bxxs3w1yb9 | 2025-02-13 09:33:43.053 |          | 6      | number
 uwah29f74gtl9tmgl2fa44k6 | 2025-02-13 09:33:31.16  |          | 1      | number

Caveats

  • An unanswered question is a missing key, not a null. In the sample survey, response zeh18log4ql0okavy3zths8d has no key at all for the NPS element: data ? 'i2fke…' is false and jsonb_typeof(data -> 'i2fke…') is SQL NULL. Which test you use decides how a stored JSON null is treated, and the three operators do not agree — measured:

    d           | d ? 'a' | (d->'a') is not null | (d->>'a') is not null | jsonb_typeof(d->'a')
    ------------+---------+----------------------+-----------------------+----------------------
    {"a": 1}    | t       | t                    | t                     | number
    {"a": null} | t       | t                    | f                     | null
    {"b": 2}    | f       | f                    | f                     | (null)

    So ? :'element_id' and -> :'element_id' IS NOT NULL behave identically — both mean “the key is present”. ->> :'element_id' IS NOT NULL is the one to avoid: it silently discards a stored JSON null, making “answered with an explicit null” indistinguishable from “never asked”. jsonb_typeof() is the only expression that separates all three states, returning the string 'null' for a stored null and SQL NULL for a missing key.

  • Four possible value shapes, not one. ZResponseDataValue (packages/types/responses.ts:7-9) is string | number | string[] | Record<string, string>. Which element yields which is decided in the SDK’s element switch (packages/surveys/src/components/general/element-conditional.tsx): matrix is the object form (typeof value === "object" && !Array.isArray(value), line 280), while address, contactInfo, ranking, and multipleChoiceMulti are arrays, not objects — a natural but wrong assumption to make about the multi-field elements. A type census over all 1498 responses in hivecfm found 1688 number, 727 string, 73 array, and 0 object values, so the object form is legal but was unexercised in that dataset. Do not write a query that assumes scalar.

  • There is no index on data. "Response" has ten indexes at this ref and not one of them is a GIN on data (select indexname from pg_indexes where tablename='Response'). The surveyId index does the selection and every jsonb predicate lands as a heap filter on top of it — confirmed in the plans below. Nothing here was benchmarked, so treat “one survey at a time” as the shape the plans support, not as a measured cost.

  • language is frequently NULL. It is set by the writing path when known; the migrated rows above carry no language at all. Localized answer labels therefore cannot be resolved from the row alone.

3. Pivot a survey’s answers into columns

SELECT r.id,
       r.created_at,
       r.finished,
       r.data ->> 'i2fke6x7sch7i8ols37hw62s' AS "nps_recommend",
       r.data ->> 'pg6d28nxcvxu6pvpv4vlllg3' AS "csat_visit",
       r.data ->> 'atp92mq8s1oshvz6fqcrxu8w' AS "visit_again"
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id'
  AND r."surveyId"      = :'survey_id'
ORDER BY r.created_at DESC;

Returns one row per response, one column per element — the shape people actually want for an export or a spreadsheet.

Sample-run on hivecfm. The query returned all 17 responses on that survey; these three are lifted out of the middle of the result because they are the ones with empty cells:

            id            |       created_at        | finished | nps_recommend | csat_visit | visit_again
--------------------------+-------------------------+----------+---------------+------------+-------------
 y003pjbj2mubvtuwv65x4s19 | 2025-02-13 09:33:52.223 | t        | 4             | 8          | 1
 ora6shthtex0t8asaqr35wsd | 2025-02-13 09:31:37.77  | t        | 0             |            | 0
 zeh18log4ql0okavy3zths8d | 2025-02-13 09:31:31.38  | t        |               | 8          |
⚠️

This is a generated query, not a generic one. The element ids and the column aliases are literals, so the SQL text is specific to one survey and stops being correct the moment the survey is edited into new elements. There is no way around that in plain SQL: Postgres determines a result’s column list at plan time, before it has read a row, so a query cannot discover its own columns from blocks. Either generate the SQL from the output of recipe 1, or keep the long shape from recipe 2 and pivot in whatever consumes it.

Caveats

  • ->> collapses “unanswered” and “answered null” into the same empty cell. Both render as NULL. If that distinction matters — and for a partial-completion report it does — carry r.data ? '<id>' as its own boolean column.
  • Everything comes back as text. ->> extracts the value as text regardless of the underlying jsonb type, so 4 and "4" are indistinguishable in the output and an array answer arrives as its JSON literal (["Service quality"]). Keep -> plus jsonb_typeof() if the type matters; see recipe 4.
  • The pivot counts invitations as rows. Add AND r.answered_questions_count > 0 to restrict it to real responses — see recipe 5 for why, and note that predicate raises the recipe from sample-run to EXPLAIN-only.

4. Aggregate a rating or NPS question honestly

The cast you need is (r.data ->> :'element_id')::numeric, and it is a loaded gun. Guard it with jsonb_typeof, in the same query level as the cast:

WITH answers AS (
  SELECT (r.data ->> 'i2fke6x7sch7i8ols37hw62s')::numeric AS score
  FROM "Response" r
  JOIN "Survey" s ON s.id = r."surveyId"
  WHERE s."environmentId" = :'environment_id'
    AND r."surveyId"      = :'survey_id'
    AND jsonb_typeof(r.data -> 'i2fke6x7sch7i8ols37hw62s') = 'number'
)
SELECT count(*)                                         AS numeric_answers,
       count(*) FILTER (WHERE score >= 9)               AS promoters,
       count(*) FILTER (WHERE score >= 7 AND score < 9) AS passives,
       count(*) FILTER (WHERE score < 7)                AS detractors,
       round( ( count(*) FILTER (WHERE score >= 9)
              - count(*) FILTER (WHERE score < 7) )::numeric
              / nullif(count(*), 0) * 100, 1)           AS nps
FROM answers;

Returns one row: how many answers were stored as jsonb numbers, the three NPS buckets, and the score.

Sample-run on hivecfm, survey zy219msndbi6ujs9jd4gccto — 17 responses, 16 of which stored a numeric answer for that element:

 numeric_answers | promoters | passives | detractors |  nps
-----------------+-----------+----------+------------+-------
              16 |         3 |        2 |         11 | -50.0

Its EXPLAIN on devhub_ref is the reason the guard is placed where it is:

 Aggregate
   ->  Nested Loop
         ->  Index Scan using "Response_surveyId_singleUseId_key" on "Response" r
               Index Cond: ("surveyId" = 'zy219msndbi6ujs9jd4gccto'::text)
               Filter: (jsonb_typeof((data -> 'i2fke6x7sch7i8ols37hw62s'::text)) = 'number'::text)
         ->  Index Scan using "Survey_environmentId_updated_at_idx" on "Survey" s

The CTE is inlined — and that is fine here precisely because the guard and the cast are both inside the CTE body, so inlining moves them together and the guard still lands as a Filter on the scan below the projection. What is not safe is splitting them: a guard in an outer query over an inner one that does the cast, or in a CTE whose consumer does the cast. Keep the two in the same WHERE/SELECT pair, whatever level that is.

The cutoffs are not invented: classifyNPSAnswer (apps/web/lib/rating-mapping.ts:34-53) uses >= 9 promoter, >= 7 passive, else detractor for scale = 10, identically for the 0..10 and 1..10 variants. For scale = 5 the rule is different — 5 promoter, 4 passive, else detractor — so read e->>'scale' and e->>'startsAt' from recipe 1 before assuming the query above applies. Values outside the element’s bounds (getNPSBounds, apps/web/lib/rating-mapping.ts:62-69) are classified as neither by the application — classifyNPSAnswer returns null and the row is excluded from the KPI — whereas the SQL above buckets them anyway: below the minimum lands in detractors, above the maximum in promoters.

What breaks the cast

A text answer errors the whole query. Not a null, not a skipped row — the statement aborts. Demonstrated against hivecfm by removing the guard on a multipleChoiceSingle element. This one is deliberately not a recipe and carries no "Survey" join: a surveyId belongs to exactly one environment, so pinning a known survey id already confines the read to one tenant — the join in the recipes is there because they are also filtered by environment, not because surveyId leaks across tenants.

echo "SELECT (r.data ->> 'evr1ary37gn64vd7ykhrz0q4')::numeric
      FROM \"Response\" r WHERE r.\"surveyId\"='pffmos5tzfhp8hbm46ig3zc9';" \
  | docker exec -i hivecfm-postgres-t3060 psql -U postgres -d hivecfm
# ERROR:  invalid input syntax for type numeric: "option1"
🚫

EXPLAIN cannot catch this. EXPLAIN without ANALYZE plans but does not execute, so an unguarded ::numeric cast produces a perfectly clean plan and then errors at runtime on the first non-numeric answer. A clean plan on devhub_ref proves the identifiers resolve and the types check — it proves nothing about the data. The 727 string values in the type census are why this fires in practice.

A multi-select answer is a jsonb array, so ->> hands you ["Service quality"] and the cast fails on the brackets. Expand it instead of casting it:

SELECT choice, count(*) AS picks
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
CROSS JOIN LATERAL jsonb_array_elements_text(r.data -> :'element_id') AS choice
WHERE s."environmentId" = :'environment_id'
  AND r."surveyId"      = :'survey_id'
  AND jsonb_typeof(r.data -> :'element_id') = 'array'
GROUP BY choice
ORDER BY picks DESC, choice;

Sample-run on hivecfm for element tpextjz47ase36tgffurenj4:

         choice         | picks
------------------------+-------
 Service quality        |     2
 Other(please specify)) |     1

The EXPLAIN on devhub_ref is what makes this safe, and it is worth reading rather than trusting:

 ->  Nested Loop
       ->  Nested Loop
             ->  Index Scan using "Response_surveyId_singleUseId_key" on "Response" r
                   Index Cond: ("surveyId" = 'e6d50a0urt5shzjpq3tl8cxc'::text)
                   Filter: (jsonb_typeof((data -> 'tpextjz47ase36tgffurenj4'::text)) = 'array'::text)
             ->  Index Scan using "Survey_environmentId_updated_at_idx" on "Survey" s
                   Index Cond: ("environmentId" = 'cmr0o5ivu000clc01glv55m4p'::text)
                   Filter: (id = 'e6d50a0urt5shzjpq3tl8cxc'::text)
       ->  Function Scan on jsonb_array_elements_text choice

The type guard lands as a baserel Filter on the Response scan, and the Function Scan is the inner side of the nested loop that sits above it — so jsonb_array_elements_text is only ever invoked for rows that already passed the guard. The LATERAL reference is what makes that structural rather than lucky: the function’s argument depends on r, so the planner cannot evaluate it before the scan that produced r. Same rule as recipe 4’s cast: keep the guard in the WHERE of the level that does the extraction. Split them — guard in an outer query, extraction in an inner one — and cannot extract elements from a scalar comes back.

An unanswered question is a missing key, so it drops out of jsonb_typeof(...) = 'number' naturally and the denominator is “people whose answer was stored as a number”, not “people who were asked”. If you need the asked denominator, take it from recipe 5 and divide yourself.

⚠️

This query and the product can disagree on the denominator. computeKPIScores does not require a jsonb number — it coerces: typeof rawValue === "number" ? rawValue : Number(rawValue) (apps/web/lib/kpi-scores.ts:38 for rating, :54 for nps). So "8" stored as a string counts toward the application’s NPS while the jsonb_typeof(...) = 'number' guard above silently drops it.

How likely that is depends on who wrote the row, and the main-line writers are careful: the bot connector runs parseInt on nps and rating utterances and only falls back to the raw string when the utterance contains no digit at all (apps/web/app/api/v1/management/bot-connector/lib/question-formatter.ts:169-192), and the IVR route coerces stringified digits before storing. The realistic route to a string in a numeric slot is an API client: ZResponseData is z.record(ZResponseDataValue), so {"<elementId>": "8"} validates for any element, and no write path checks the value against the element’s type.

What the sample data actually shows: hivecfm holds 7 numeric-looking string answers across its 1498 responses, and all 7 are openText values — phone numbers such as "37099933321", not ratings. So on that dataset the divergence is real in the code and zero rows wide in practice. Measure your own tenant before deciding it matters:

SELECT count(*) FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id'
  AND r."surveyId"      = :'survey_id'
  AND jsonb_typeof(r.data -> :'element_id') = 'string';

If it returns rows, widen the guard to match the application — and keep the regex, because it is the part that stops the cast erroring once strings are admitted:

AND (   jsonb_typeof(r.data -> :'element_id') = 'number'
     OR (jsonb_typeof(r.data -> :'element_id') = 'string'
         AND r.data ->> :'element_id' ~ '^-?[0-9]+(\.[0-9]+)?$'))

Both forms plan as a single Filter on the same Response index scan (checked on devhub_ref), so the choice between them is about which rows you want counted, not about plan shape.

The stored alternative, and why it is often empty

"Response"."kpiScores" is a jsonb object — csatScore, cesScore, fcrScore, npsScore, all nullable numbers (packages/types/responses.ts:317-322) — written on every response create and update by computeKpiForPersist (apps/web/lib/kpi-scores-persist.ts:13-20). Reading it skips element resolution entirely:

SELECT count(*)                                              AS rows_with_stored_nps,
       round(avg((r."kpiScores" ->> 'npsScore')::numeric), 1) AS avg_stored_nps
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id'
  AND r."surveyId"      = :'survey_id'
  AND jsonb_typeof(r."kpiScores" -> 'npsScore') = 'number';

Sample-run on hivecfm, same survey where the raw cast found 16 answers:

 rows_with_stored_nps | avg_stored_nps
----------------------+----------------
                    0 |
⚠️

kpiScores is mostly, but not entirely, empty on a migrated tenant — measure it, do not assume it. Of the 1498 responses in hivecfm, 1450 carry the all-null object {"cesScore": null, "fcrScore": null, "npsScore": null, "csatScore": null} and 48 carry at least one value; only 35 have a numeric npsScore. 34 of those 35 are meta->>'source' = 'ist-old' rows, so the migrator does populate the column for some rows and not others — this harness cannot say which rule decides that. The consequence is the one that matters: on the survey used above, kpiScores yields 0 rows while the raw-data cast yields 16, so a dashboard built on kpiScores and one built on data disagree on the same tenant. Run this count on your own tenant before building on either:

SELECT count(*)                                                              AS responses,
       count(*) FILTER (WHERE jsonb_typeof(r."kpiScores" -> 'npsScore') = 'number') AS with_stored_nps
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id';

Three more things about the stored value, all from computeKPIScores (apps/web/lib/kpi-scores.ts:18-89):

  • It is already a percentage per response, (promoters - detractors) / total × 100 over that single row’s NPS answers — so it is -100, 0, or +100 when the survey has exactly one NPS element. avg() across responses equals pooled NPS only in that one-element case, and that case is not the common one: 138 of the 1191 surveys in hivecfm carry more than one nps element, the largest carrying seven. For those the stored value is already an internal mean, so averaging it again is a mean of ratios rather than a pooled score. Count your own before averaging — recipe 1 filtered to element_type = 'nps' answers it.
  • It is frozen at write time. Changing an element’s scale or startsAt later does not reclassify existing rows.
  • csatScore and cesScore are bucket-normalized to 1–5, not raw answers — the mapping table for each supported scale is CSAT_CES_BUCKET_MAP in apps/web/lib/rating-mapping.ts:9-15, and only rating elements whose ratingType is csat or ces contribute at all. fcrScore comes from a multipleChoiceSingle element with ratingType = "fcr" and a nominated fcrPositiveChoiceId. A raw average of a rating element is therefore not the CSAT the product reports.

5. Response vs invitation

Both are rows in "Response". There is no Invitation table at this ref. The discriminator is a column, and the schema comment is the rule:

Number of actual survey questions answered (data keys that match a survey element id, excluding hidden fields / metadata). A session counts as a real “response” only when this is > 0; sessions with 0 answered questions are “invitations”. Maintained on create/update and backfilled for old rows.

— packages/database/schema.prisma:242-246

The application encodes exactly that as two reusable PrismaPrismaThe TypeScript ORM HiveCFM uses to talk to Postgres. The schema lives at packages/database/schema.prisma. fragments, ANSWERED_RESPONSE_WHERE and INVITATION_WHERE (apps/web/lib/response/utils.ts:37-42). Your SQL should mirror them:

SELECT count(*)                                                AS sessions,
       count(*) FILTER (WHERE r.answered_questions_count > 0)   AS responses,
       count(*) FILTER (WHERE r.answered_questions_count = 0)   AS invitations,
       round(100.0 * count(*) FILTER (WHERE r.answered_questions_count > 0)
                   / nullif(count(*), 0), 1)                    AS response_rate_pct
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id'
  AND r."surveyId"      = :'survey_id';

Returns one row: sessions created, of which real responses and invitations, plus the rate.

🚫

Omitting the predicate inflates the numerator, not just the denominator. Every invitation is a "Response" row. count(*) over "Response" is “sessions we opened”, which for an email or link campaign is close to “messages we sent” — so a naive count(*) reported as “responses” can overstate participation by the entire invitation volume. The direction of the error is always the same: too high, and quietly.

Verification status and caveats

  • EXPLAIN-only. answered_questions_count does not exist on the hivecfm database — running this there gives ERROR: column r.answered_questions_count does not exist. It plans clean on devhub_ref and there are no rows there to run it against, so this recipe has never returned a number from real data in this harness. Say so if you quote it.
  • Do not substitute a key count. jsonb_object_keys(r.data) is not the same measure: data legitimately holds keys that are not element ids — the IVR route writes both data["callerNumber"] and data["callId"] (apps/web/app/api/v1/client/[environmentId]/ivr/[surveyId]/responses/route.ts:148-152) and the bot connector seeds data with the survey’s hidden fields (apps/web/app/api/v1/management/bot-connector/turn/route.ts:584). countAnsweredQuestions counts only keys that match an element id, which is why the column exists at all. As it happens, in hivecfm every one of the data keys resolved to an element id (0 non-element keys across all 1498 rows), so a key count would agree there — that is a property of migrated data, not of the model.
  • = 0 is not the same as data = '{}'. An invitation created by a campaign or a bot session can carry hidden fields and still be an invitation. That is the whole reason the counter is not data <> '{}'.
  • There is no index on answered_questions_count. In the query above it is only an aggregate FILTER, evaluated at the Aggregate node, so it costs nothing extra. Move it into a WHERE — as recipes 3 and 7 do — and it becomes a heap filter after the surveyId index scan (Filter: (answered_questions_count > 0) in recipe 7’s plan on devhub_ref).
  • Response rate has no send-side denominator here. This measures sessions HiveCFM created. If a message was never delivered, no row exists, and this rate cannot see it. Delivery numbers come from the campaign side — see Channels & campaigns.

6. Completion, partials and expiry

Four columns carry the lifecycle, all verified present on devhub_ref and all with an identified writer.

ColumnTypeWritten by
finishedboolean default falseThe request body — createResponse destructures it straight off responseInput (apps/web/app/api/v1/client/[environmentId]/responses/lib/response.ts:91); nothing infers it
expired_attimestamp without time zone nullable; UTC per the schema comment at schema.prisma:248Stamped at creation and refreshed once on invitation→response conversion (apps/web/lib/response/service.ts:622-637)
expiry_sourcetext nullableresolveDeadline() returns 'invitation' or 'session' — resolveDeadline is apps/web/lib/survey/session-ttl.ts:115-127 and the type TExpirySource is line 107
is_negative_responseboolean default falseevaluateIsNegativeResponse() (apps/web/lib/close-the-loop.ts:13-45), on every finished write
SELECT count(*)                                                             AS sessions,
       count(*) FILTER (WHERE r.answered_questions_count = 0)                AS invitations,
       count(*) FILTER (WHERE r.answered_questions_count > 0 AND r.finished) AS completed,
       count(*) FILTER (WHERE r.answered_questions_count > 0 AND NOT r.finished
                          AND (r.expired_at IS NULL
                               OR r.expired_at >= now() AT TIME ZONE 'UTC')) AS partial_live,
       count(*) FILTER (WHERE NOT r.finished
                          AND r.expired_at < now() AT TIME ZONE 'UTC')       AS expired,
       count(*) FILTER (WHERE NOT r.finished
                          AND r.expired_at < now() AT TIME ZONE 'UTC'
                          AND r.expiry_source = 'invitation')                AS expired_invitation_window,
       count(*) FILTER (WHERE NOT r.finished
                          AND r.expired_at < now() AT TIME ZONE 'UTC'
                          AND r.expiry_source = 'session')                   AS expired_session_window,
       count(*) FILTER (WHERE r.is_negative_response)                        AS negative
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id'
  AND r.created_at >= (now() AT TIME ZONE 'UTC') - interval '30 days';

Returns one row: the counts for an environment over a window, split by which expiry window closed and how many responses tripped a Close-the-Loop rule.

⚠️

These columns are not a partition — do not sum them. completed and partial_live are disjoint from expired, but expired is not disjoint from invitations: an unanswered session whose deadline has passed has answered_questions_count = 0 and NOT finished AND expired_at < now, so it is counted in both. sessions is the only total. If you need mutually exclusive buckets, add AND r.answered_questions_count > 0 to the three expired* filters and report expired invitations as their own column.

Caveats

  • EXPLAIN-only, for the same reason as recipe 5 — answered_questions_count and expiry_source are both absent from hivecfm.
  • “Expired” is a computed state, not a stored flag. There is no expired boolean and no job that sets one. getSessionExpiry (apps/web/lib/survey/session-ttl.ts:154-164) is three lines: a finished response never expires, a response with no expired_at never expires, otherwise now > expiredAt. The SQL above reproduces that exactly — including the strict comparison, hence expired_at < and not <=. A row can sit “expired” indefinitely with finished = false and nothing ever rewrites it.
  • now() AT TIME ZONE 'UTC', not bare now(). Every timestamp on "Response" is timestamp without time zone (created_at, updated_at, expired_at, survey_delivered_at — confirmed in information_schema.columns on devhub_ref) and is documented as holding UTC by the schema comment on expiredAt (packages/database/schema.prisma:248) — an assertion by the author, not something this harness measured. now() is timestamp with time zone, so comparing it against those columns silently casts it using your session’s TimeZone. Measured in the reference container: now()::timestamp is 14:27 under Etc/UTC and 17:27 under Asia/Riyadh — the same instant, three hours apart. Under a non-UTC session that misclassifies a three-hour band of rows in both directions, and the query still returns a plausible-looking number. now() AT TIME ZONE 'UTC' is timezone-independent and plans identically (the planner folds it into the same Filter: (created_at >= ((now() AT TIME ZONE 'UTC'::text) - '30 days'::interval))).
  • expired_at is frozen, and later survey edits do not reach it. Enabling or changing the Survey Expiration card (survey_expiration_card, jsonb) or the session timeout (session_ttl_minutes, Int?) affects only rows created afterwards. Two rows on the same survey can legitimately have different deadlines, which is why expiry_source is stored rather than derived — the comment at schema.prisma:251-255 says exactly that.
  • Two independent windows, and the row dies at whichever closes first. expiry_source = 'invitation' is the Survey Expiration card’s deadline measured from send; 'session' is the answering window measured from first answer. On conversion, resolveDeadline() keeps the earlier of the two and records which one it kept. Counting only one source undercounts expiry.
  • is_negative_response is only meaningful on finished responses. Every write path guards it as finished && survey ? evaluateIsNegativeResponse(...) : false — for example apps/web/app/api/v1/client/[environmentId]/responses/lib/response.ts:109-110. An unfinished response carrying a detractor answer still reads false. It is also false whenever the survey has no Close-the-Loop rules configured (evaluateIsNegativeResponse returns early on an empty rule list), so count(*) FILTER (WHERE is_negative_response) returning 0 does not mean nobody was unhappy.
  • finished is client-asserted. It arrives in the request body; it is not inferred from having answered every element. An abandoned response is finished = false forever, and a respondent who reaches an ending after two of ten questions is finished = true.

7. Response.meta — browser, device and source

The type is ZResponseMeta (packages/types/responses.ts:300-313): optional source, url, country, action, ipAddress, and an optional userAgent object of optional browser, os, device. Every field is optional, so the practical shape varies by writer. The browser route assembles source, url, userAgent{browser,device,os}, country and action on every write (apps/web/app/api/v1/client/[environmentId]/responses/route.ts:195-205), plus ipAddress when the survey enables IP capture; the keys whose value is undefined are simply absent from the stored jsonb, which is why a real browser row is often just { url, userAgent: { os, device, browser } }.

SELECT coalesce(r.meta ->> 'source', '(unset)')               AS source,
       coalesce(r.meta -> 'userAgent' ->> 'device',  '(none)') AS device,
       coalesce(r.meta -> 'userAgent' ->> 'browser', '(none)') AS browser,
       coalesce(r.meta -> 'userAgent' ->> 'os',      '(none)') AS os,
       count(*)                                               AS responses
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id'
  AND r.answered_questions_count > 0
GROUP BY 1, 2, 3, 4
ORDER BY responses DESC, source;

Returns one row per distinct source/device/browser/OS combination, with counts. coalesce is load-bearing: without it every non-browser row collapses into a NULL group that is easy to misread as “unknown browser” rather than “no browser involved”.

Sample-run on hivecfm with the answered_questions_count predicate dropped, since that column does not exist there:

 source  | device  | browser |   os    | responses
---------+---------+---------+---------+-----------
 ist-old | (none)  | (none)  | (none)  |      1497
 (unset) | desktop | Chrome  | Windows |         1

That is the honest picture of a migrated tenant: 1497 of 1498 responses carry no userAgent at all. Their meta is the migrator’s own shape — {"source": "ist-old", "agentId": …, "channelId": …, "crmCaseId": …, "customerId": …, "interactionId": …, "invitationDateTime": …}. The string ist-old appears nowhere at origin/development (git grep -rn "ist-old" origin/development returns no hits), so it is written by the migrator on a feature branch, not by any main-line code path. Do not build a source filter that expects it on a fresh install, and do not expect a device breakdown to mean anything on a tenant whose history was imported.

Where the values actually come from

Browser responses. userAgent is server-derived, not client-supplied: the route reads the user-agent request header and parses it with UAParser (apps/web/app/api/v1/client/[environmentId]/responses/route.ts:87-88, 195-204). source and url do come from the request body, so they are client-controlled. country is read from CF-IPCountry, X-Vercel-IP-Country, or CloudFront-Viewer-Country — absent behind any other proxy. ipAddress is attached only when survey.isCaptureIpEnabled is true.

device has a hard-coded fallback. The route writes agent.getDevice().type || "desktop", so anything UAParser cannot classify is recorded as desktop. desktop is a catch-all bucket, not a measurement. browser and os have no such fallback and are simply dropped when unparseable, which is why they can be missing while device is present.

One IVR path carries a synthetic userAgent, and only one. { browser: "IVR", device: "phone", os: "telephony" }, written literally at apps/web/app/api/v1/client/[environmentId]/ivr/[surveyId]/responses/route.ts:279-283 — the answer-submission route, which creates the row when the first answer arrives. So device = 'phone' in a breakdown means a phone survey, not a mobile browser; a real mobile-web response reports whatever UAParser returns for the handset. The IVR session-open route (.../ivr/[surveyId]/route.ts:212-226) creates its row with source: "genesys_ivr" and no userAgent, so an IVR session that opened but was never answered has neither.

⚠️

Two corrections to what you may have been told.

Bot-connector responses have no userAgent at all. The create at apps/web/app/api/v1/management/bot-connector/turn/route.ts:587-593 writes source, and conditionally genesysConversationId, agentId, and channel — and no userAgent key. Anything describing the bot path as carrying a synthetic user agent like the IVR path does is wrong; only the IVR path does that. A chat-channel response therefore lands in the (none) bucket above, indistinguishable by userAgent from a migrated row.

The IVR path writes two different source values. "ivr" — as meta?.source || "ivr", so a caller can override it — at .../ivr/[surveyId]/responses/route.ts:277, and "genesys_ivr" at two other createResponseWithQuotaEvaluation calls: .../ivr/[surveyId]/route.ts:221 and apps/web/app/api/v1/management/surveys/[surveyId]/route.ts:172. All three produce "Response" rows for the same phone-survey feature, so a filter of meta->>'source' = 'ivr' silently misses the other two. Match the set explicitly (in ('ivr','genesys_ivr')), and remember "ivr" is only the default.

Other source values written at this ref: "genesys_bot_connector" (bot connector) and "sms_campaign" (apps/web/lib/campaign/send-campaign.ts:321). Browser responses have whatever the client sent, which is frequently nothing — the literal "web" appears only in test fixtures at this ref, never in a production write path, so (unset) is the normal state for a web response rather than an anomaly.

Caveats

  • There is no index on meta. Same as data — no GIN index exists on "Response", so this groups over a full scan of the environment’s responses.
  • meta is merged, not replaced, on update. apps/web/lib/response/service.ts:613 spreads the existing object under the incoming one, so keys from an earlier write survive a later one. A row’s meta can be a union of two writers’ shapes.
  • Filtering on meta in Prisma uses a JSON path, not a column. The bot connector’s re-entry guard queries meta: { path: ["genesysConversationId"], equals: … } (turn/route.ts:527). The SQL equivalent is r.meta ->> 'genesysConversationId' = … — and note that for Genesys context there are also real top-level columns (genesys_conversation_id and eleven more); which one is populated depends on the writer. See Genesys & IVR.

Where to look in the code

All paths are at origin/development of hivecfm-core.

  • packages/database/schema.prisma:191-265 — the Response model, including the invitation rule at lines 242-246 and the expiry_source rationale at 251-255.
  • packages/types/responses.ts:7-9 — ZResponseDataValue, the four legal answer shapes; :300-313 ZResponseMeta; :317-322 ZResponseKpiScores.
  • packages/types/surveys/elements.ts:18-34 — TSurveyElementTypeEnum, all 15 element types.
  • apps/web/lib/response/utils.ts:28-65 — ANSWERED_RESPONSE_WHERE, INVITATION_WHERE, and countAnsweredQuestions, with the comment explaining why data <> '{}' is not the test.
  • apps/web/lib/response/service.ts:537-637 — the update path: KPI recompute, negative-response recompute, answered-count maintenance, and the invitation→response conversion that resets createdAt and re-resolves the deadline.
  • apps/web/lib/survey/session-ttl.ts:107-174 — TExpirySource, resolveDeadline, getSessionExpiry, isResponseExpired.
  • apps/web/lib/close-the-loop.ts:13-45 — evaluateIsNegativeResponse, numeric rules vs label-set rules.
  • apps/web/lib/kpi-scores.ts:18-89 and apps/web/lib/rating-mapping.ts:9-80 — how kpiScores is computed, the CSAT/CES bucket table, and the NPS cutoffs.
  • apps/web/app/api/v1/client/[environmentId]/responses/route.ts:87-94, 195-212 — where browser meta is assembled.
  • apps/web/app/api/v1/client/[environmentId]/ivr/[surveyId]/responses/route.ts:148-152, 276-283 — the IVR write: callerNumber into data, synthetic userAgent into meta.
  • apps/web/app/api/v1/management/bot-connector/turn/route.ts:580-593 — the bot-connector create, for comparison.
  • Read this first — quoting, per-table column casing, and why the tenant predicate is yours to write.
  • Genesys & IVR — the genesys_* columns on "Response" and which writer fills them.
  • Operational queries — expiry sweeps, orphans, and integration logs.
  • Survey Response Flow — what happens between a submitted answer and a committed row.

HiveCFM Developer Hub — internal team guide