tutorials
Segment your email list with plain SQL
October 30, 2026

Every hosted email tool has a segment builder, and every segment builder eventually runs out of room: a fixed list of fields, a handful of operators, a cap on conditions, and no way to express "subscribed, tagged vip, on the annual plan, but has not opened anything in 60 days." When your list lives in a database you own, that segment is just a SELECT.
A segment is a question about your subscribers: who do I want to mail this time? SaaS platforms answer it with a point-and-click builder, which is fine until the question gets specific. The moment you want a NOT EXISTS, a self-join, your own date math, or a condition the dropdown does not offer, you are stuck, because you are renting an interface to your data instead of holding the data.
This post does it the direct way. We will segment a real subscriber schema (the one Tinbox provisions in D1) using nothing but SQL: status, custom merge fields stored as JSON, tags through a join table, and open/click engagement from an events table. Then we will save a useful query as a named segment a campaign can send to. The SQL is standard SQLite, so it runs against D1, a local .sqlite file, or any SQLite tool.
Can you segment an email list with plain SQL?
Yes, as long as your subscribers live in a SQL database. A segment is just a SELECT that returns the set of addresses you want to mail. The only discipline that matters is filtering on subscription status so a clever query never mails someone who opted out.
Here is the schema we are working against. It is the recipient model Tinbox stores in D1, and it is deliberately small:
contactsis one row per person: a unique lowercasedemail, aname, and anattribsJSON bag for arbitrary person-level attributes.audiencesis a list (Mailchimp calls it an audience): "Customers", "Newsletter".audience_membersis the(audience, contact)membership with the load-bearingstatuscolumn (pending,subscribed,unsubscribed,cleaned,transactional) and amerge_valuesJSON bag for per-audience custom fields.tagspluscontact_tagsgive you free-form labels per member.eventsis append-only telemetry: one row perdelivered/opened/clicked/bouncedevent, keyed byrecipientandoccurred_at(epoch millis).
Open the database. Against a remote D1 binding:
# Run a one-off query against the remote D1 database for your deployment.
wrangler d1 execute tinbox-db --remote \
--command "SELECT count(*) AS contacts FROM contacts;"
┌──────────┐
│ contacts │
├──────────┤
│ 18452 │
└──────────┘
Or, if you are working against the local demo database (a plain SQLite file), just use sqlite3:
sqlite3 .tinbox/local.sqlite \
"SELECT count(*) AS contacts FROM contacts;"
Either way, you now have a SQL prompt over your list. Everything below is portable between the two.
How do I get the set of subscribers I'm actually allowed to mail?
Join audience_members to contacts and filter status = 'subscribed'. That single condition is the difference between a clean send and a reputation problem, because it excludes everyone who unsubscribed, hard-bounced (cleaned), or never confirmed (pending).
-- The mailable base set for one audience.
SELECT c.email, c.name
FROM audience_members AS am
JOIN contacts AS c ON c.id = am.contact_id
WHERE am.audience_id = 'aud_newsletter'
AND am.status = 'subscribed';
audience_id = 'aud_newsletter' scopes the query to one list; drop it (and SELECT DISTINCT c.email) if you want everyone subscribed to anything. The reason status lives on the membership row and not on the contact is that one person can be subscribed to your product updates and unsubscribed from your marketing list at the same time. Status is per-audience; the contact is global.
There is a second, global do-not-send layer you should respect too: a suppressions table that is a hard kill-switch across every audience (complaints, manual blocks, compliance removals). A fully correct base set excludes those as well:
SELECT c.email, c.name
FROM audience_members AS am
JOIN contacts AS c ON c.id = am.contact_id
WHERE am.audience_id = 'aud_newsletter'
AND am.status = 'subscribed'
AND c.email NOT IN (SELECT email FROM suppressions);
From here, every segment is this query plus more ANDs and ORs. Build up from the safe base; never start from "all contacts" and try to subtract.
How do I filter on a custom field stored as JSON?
Use json_extract(column, '$.key'). SQLite has first-class JSON functions, and Tinbox stores custom data in two JSON columns: contacts.attribs (person-level) and audience_members.merge_values (per-audience merge fields like FNAME, PLAN, CITY).
Say you want subscribers on the annual plan in Berlin:
SELECT c.email,
json_extract(am.merge_values, '$.PLAN') AS plan,
json_extract(am.merge_values, '$.CITY') AS city
FROM audience_members AS am
JOIN contacts AS c ON c.id = am.contact_id
WHERE am.audience_id = 'aud_newsletter'
AND am.status = 'subscribed'
AND json_extract(am.merge_values, '$.PLAN') = 'annual'
AND json_extract(am.merge_values, '$.CITY') = 'Berlin';
A note on a real failure mode. json_extract returns NULL when the key is missing, and in SQL NULL = 'annual' is not true (it is unknown), so contacts missing the field are silently excluded. That is usually what you want. But it bites you on negation. This query does not mean "everyone whose plan is not annual":
-- WRONG if some contacts have no PLAN field at all.
WHERE json_extract(am.merge_values, '$.PLAN') != 'annual'
A contact with no PLAN key yields NULL != 'annual', which is NULL, which is filtered out, so people you almost certainly meant to include vanish. Be explicit about NULLs:
-- "Plan is not annual, including people with no plan set."
WHERE (json_extract(am.merge_values, '$.PLAN') IS NULL
OR json_extract(am.merge_values, '$.PLAN') != 'annual')
This NULL-versus-negation trap is exactly the kind of thing a dropdown segment builder hides from you (sometimes correctly, sometimes not). With SQL you can see it and decide.
Numeric fields work the same way, with a CAST if the JSON value is a string:
-- Subscribers whose stored lifetime value is over 500.
WHERE CAST(json_extract(am.merge_values, '$.LTV') AS REAL) > 500
How do I segment by tag?
Tags live in their own table and attach to members through a join, so a tag condition is an EXISTS (or a JOIN) against contact_tags. This keeps tags structured: no comma-joined string to parse, no ambiguity when a tag name itself contains a comma.
Subscribers tagged vip:
SELECT c.email
FROM audience_members AS am
JOIN contacts AS c ON c.id = am.contact_id
WHERE am.audience_id = 'aud_newsletter'
AND am.status = 'subscribed'
AND EXISTS (
SELECT 1
FROM contact_tags AS ct
JOIN tags AS t ON t.id = ct.tag_id
WHERE ct.audience_member_id = am.id
AND t.name = 'vip'
);
The shape pays off when you want set logic that builders struggle with. "Tagged vip but NOT tagged churned" is two existence tests, one positive and one negated:
WHERE am.status = 'subscribed'
AND EXISTS (
SELECT 1 FROM contact_tags ct JOIN tags t ON t.id = ct.tag_id
WHERE ct.audience_member_id = am.id AND t.name = 'vip'
)
AND NOT EXISTS (
SELECT 1 FROM contact_tags ct JOIN tags t ON t.id = ct.tag_id
WHERE ct.audience_member_id = am.id AND t.name = 'churned'
);
"Tagged with any of these three" is an IN list inside the EXISTS:
AND EXISTS (
SELECT 1 FROM contact_tags ct JOIN tags t ON t.id = ct.tag_id
WHERE ct.audience_member_id = am.id
AND t.name IN ('vip', '2025-cohort', 'beta')
)
How do I segment by who opened or clicked?
Use a subquery against the events table, which records one row per engagement event keyed by recipient (the address) and occurred_at in epoch milliseconds. Engagement segments are the ones SaaS builders charge the most for and constrain the hardest; in SQL they are a subquery and some date math.
The one gotcha is the units: occurred_at is milliseconds, and SQLite's unixepoch() returns seconds, so you multiply by 1000. Subscribers who opened anything in the last 30 days:
SELECT c.email
FROM audience_members AS am
JOIN contacts AS c ON c.id = am.contact_id
WHERE am.audience_id = 'aud_newsletter'
AND am.status = 'subscribed'
AND c.email IN (
SELECT recipient
FROM events
WHERE type = 'opened'
AND occurred_at > (unixepoch('now', '-30 days') * 1000)
);
Re-engagement campaigns want the inverse: subscribed, but no open or click in 90 days. Flip IN to NOT IN and widen the window:
AND c.email NOT IN (
SELECT recipient
FROM events
WHERE type IN ('opened', 'clicked')
AND occurred_at > (unixepoch('now', '-90 days') * 1000)
)
Two honest caveats. First, open tracking is privacy-sensitive and off by default for newsletters, so an opened subquery returns nothing unless you have enabled tracking; click events are more reliable because they fire on a real navigation. Second, NOT IN with a subquery that could contain NULL recipients behaves surprisingly (the whole condition can go unknown), so it is worth guarding the inner query with WHERE recipient IS NOT NULL, or using NOT EXISTS instead, which does not have that pitfall.
How do I save a SQL query as a reusable segment?
Promote the query to a saved segment so a campaign targets it by name and it re-evaluates on every send. A saved segment is a stored rule; a static segment is a frozen list. You want saved for "everyone who matches this right now" and static for "this exact set of people, do not recompute."
Tinbox keeps both in an audience_segments table with a type column (saved or static). Saved segments carry a typed conditions JSON the engine compiles down to the same SQL you just wrote; static segments store explicit membership in static_segment_members. The point is that a campaign sends to a segment name, and the engine resolves it to addresses at send time, applying status and global suppression for you.
In the console you build the rule once and name it. From the CLI it is one call:
# Create a saved segment that re-evaluates on every send.
tinbox segment create \
--audience newsletter \
--name "active-vip" \
--match all \
--rule "status is subscribed" \
--rule "tag has vip" \
--rule "opened in 30d"
Then a campaign references it by name and never has to know the query:
tinbox campaign send \
--audience newsletter \
--segment active-vip \
--template "june-update"
If you would rather freeze a one-off list (say, the result of a gnarly ad-hoc query you ran in sqlite3), pipe the addresses into a static segment instead, and they stay fixed until you change them:
sqlite3 .tinbox/local.sqlite \
"SELECT c.email FROM audience_members am
JOIN contacts c ON c.id = am.contact_id
WHERE am.status='subscribed'
AND json_extract(am.merge_values,'\$.PLAN')='annual';" \
| tinbox segment import --audience newsletter --name "annual-2026" --static
Saved segments give you freshness; static segments give you reproducibility. Both are addressable by name, and both respect the mailable rules so a query mistake cannot turn into a send to people who opted out.
Always count before you send
Run your WHERE as a COUNT(*) first. A segment is a send list, and the cheapest insurance against a bad query is knowing how many people it returns before a campaign goes out.
SELECT count(*) AS recipients
FROM audience_members AS am
JOIN contacts AS c ON c.id = am.contact_id
WHERE am.audience_id = 'aud_newsletter'
AND am.status = 'subscribed'
AND EXISTS (
SELECT 1 FROM contact_tags ct JOIN tags t ON t.id = ct.tag_id
WHERE ct.audience_member_id = am.id AND t.name = 'vip'
);
┌────────────┐
│ recipients │
├────────────┤
│ 312 │
└────────────┘
If that number is wildly off from what you expected (a surprising 0, or your whole list), the query is wrong, not the data. Common causes: a forgotten status filter, a JSON key typo ('$.Plan' versus '$.PLAN'), or the milliseconds-versus-seconds mistake in an engagement window. Catching it here costs nothing; catching it after the send is a deliverability incident.
Or skip the SQL: saved segments in Tinbox
If you want the expressiveness without hand-writing every query, that is what the saved-segment builder is for: you compose rules (status, tags, merge fields, engagement) in the console or CLI, name the result, and the engine compiles them to exactly this SQL and re-runs it on every send. You keep the option to drop into sqlite3 or wrangler d1 execute whenever the builder runs out of room, because the database is yours.
That is the real difference from a hosted tool. The data is in your own D1 on your own Cloudflare account, so a segment is never a feature you are waiting on a vendor to ship: it is a query you can write today. One honest caveat to set expectations: a Tinbox deployment is one brand and domain per deploy right now, so an agency running several clients queries each client's database separately rather than across one multi-tenant table.
For the table layout these queries assume, see the D1 email schema design. If you are moving a list in before you can segment it, exporting a Mailchimp audience cleanly gets the data in with status and tags intact, and sending bulk email in batches on Workers is what consumes the segment once you have it. For the argument behind doing this in SQL at all, the ways SQL beats a drag-and-drop segment builder makes the case without the schema detail.
Segmentation stops being a product feature and becomes a query the moment you own the table. Filter on status, read JSON fields with json_extract, join your tags, subquery your events, and count before you send. Once a segment is a query you own, splitting it for an experiment is trivial too, which is the premise behind the email A/B tests worth running on your own stack.
Deploy this yourself: npx tinbox init <domain>, then query your subscribers with wrangler d1 execute or save the query as a segment. The full schema and the saved-segment condition reference are in the docs.
Frequently asked questions
Can you segment an email list with SQL?
Yes, if your subscribers live in a SQL database. A segment is a SELECT that returns the addresses you want to mail. In a Tinbox deployment the recipients are in D1 (SQLite) tables: join audience_members to contacts to get each address, filter on status='subscribed' so you never mail someone who opted out, then add conditions on custom merge fields (json_extract), tags (a join through contact_tags), or engagement (a subquery against the events table). Anything you can express in SQL becomes a segment.
How do I query a JSON merge field in SQLite?
Use json_extract(column, '$.key'). Tinbox stores per-contact attributes in contacts.attribs and per-audience merge fields in audience_members.merge_values, both as JSON. To filter contacts whose plan is annual: WHERE json_extract(am.merge_values, '$.PLAN') = 'annual'. SQLite's json_extract returns NULL for missing keys, so a missing field simply fails the equality test rather than erroring, which is usually what you want for segmentation.
How do I segment by who opened or clicked a campaign?
Query the events table, which stores one append-only row per delivered/opened/clicked/bounced event keyed by recipient and occurred_at (epoch millis). To find subscribers who opened anything in the last 30 days: a subquery WHERE recipient IN (SELECT recipient FROM events WHERE type='opened' AND occurred_at > (unixepoch('now','-30 days') * 1000)). Open tracking is privacy-sensitive and off by default, so this only returns rows if you have tracking enabled.
What is the difference between a saved segment and a static segment?
A saved segment is a stored rule (a query) that is re-evaluated every time you send, so membership is always current. A static segment is a fixed list of members you added by hand or via an import, and it does not change until you edit it. In Tinbox both live in audience_segments with a type column; saved segments carry a conditions JSON the engine compiles to SQL, while static segments store explicit membership in static_segment_members. Use saved for 'everyone who matches X right now' and static for a frozen list.
Why can't I just query my list in a SaaS email tool?
Because hosted tools expose a segment builder, not the table. You get a fixed set of fields and operators in dropdowns, a capped number of conditions, and no way to write a NOT EXISTS, a self-join, or your own date math. The data is real but you are renting an interface to it. When the list lives in your own database the segment is just SQL, and you can also reach it from any script, BI tool, or the sqlite3 CLI.