Sub topic 4
Writing Segment Rules
This chapter assumes you already know the basic email terms (campaign, open rate, click rate), have used an email service provider (ESP) or CRM, and understand AND, OR, and NOT. The SQL examples use PostgreSQL. If you don't write SQL, read them as plain descriptions of the rule your ESP's segment builder would express.
What a segment rule is
A segment rule is a test that each subscriber either passes or fails. The segment is the set of subscribers who pass. Every rule, however complex, is built from three parts:
- Conditions. A single test on one field or event, such as
status = 'subscribed'or "clicked an email". - Boolean logic. AND, OR, and NOT combine conditions into one test.
- Time windows. A limit on when an event must have happened, such as "in the last 30 days".
Most segment bugs come from one of these three parts being slightly wrong. The rest of the chapter covers each part and then the errors they produce.
Conditions
Conditions come in two kinds, matching the data foundations from the previous chapters.
- Profile conditions test a stored value on the subscriber record:
status,created_at,last_purchase_at, a country field, or a tag. They answer "what is true about this person now?" - Event conditions test the history of actions: an email click, a purchase, a page visit. They answer "what has this person done, and when?"
Event conditions need more than the event type. A useful event condition usually has four pieces: the event type, an optional property filter (for example topic = 'running'), a count threshold, and a time window. "Clicked an email" is incomplete. "Clicked at least twice on running content in the last 60 days" is a rule you can compute.
Always include the consent condition
Every segment used for sending should require status = 'subscribed'. Put it in the rule explicitly, even if your ESP also suppresses unsubscribed contacts at send time. A segment that is also used for reporting or exports will otherwise include people you must not email. The first SQL example below does this.
Boolean logic
AND narrows a segment. OR widens it. NOT removes people. Three habits keep rules correct.
Group explicitly. In most systems AND binds more tightly than OR, so A OR B AND C means A OR (B AND C). If you meant (A OR B) AND C, you must say so with brackets or with nested groups in the builder. Many ESP builders show "match all" and "match any" groups. A "match any" group nested inside a "match all" group is the visual form of brackets.
Be careful with NOT. "Did not click in the last 30 days" is not the same as "has no click events". The first includes people who clicked 45 days ago. The second excludes anyone who ever clicked. Decide which one you mean, then write the time window into the negation.
Watch for missing values. In SQL, a comparison with NULL is neither true nor false. last_purchase_at < now() - interval '90 days' silently drops anyone whose last_purchase_at is NULL, which is every person who never bought. Test for NULL explicitly with IS NULL or IS NOT NULL. Many ESP builders have a separate "is empty" operator for this reason.
| You mean | Rule shape | Common mistake |
|---|---|---|
| Clicked or purchased | `click OR purchase` | Using AND, which requires both |
| Subscribed and (new or active) | `subscribed AND (new OR active)` | Leaving out the brackets |
| Not clicked in 30 days | `NOT EXISTS (click in last 30 days)` | Testing only for "no clicks ever" |
| Never purchased | `last_purchase_at IS NULL` | Using `= 0` or `< date`, which skip NULLs |
Time windows
A time window has two properties that change a segment's meaning: whether it is relative or absolute, and where it starts.
- A relative window is measured back from the moment the segment is evaluated:
occurred_at >= now() - interval '30 days'. The membership changes each day as old events fall out of the window. Use relative windows for behaviour and interest. - An absolute window uses fixed dates:
occurred_at >= '2026-11-01'. Membership only grows as new events arrive. Use absolute windows for one-off questions, such as "who clicked during the Black Friday campaign".
Choose the window length from how quickly the signal goes stale. A click on a flash-sale email is stale in days. A purchase of running shoes stays meaningful for months. A window that is too short makes a tiny segment. A window that is too long includes people whose behaviour no longer reflects their interest.
Also be explicit about the time zone and the boundary. now() returns a moment in time, so now() - interval '30 days' is a rolling 30 × 24 hours. If your ESP evaluates "in the last 30 days" at midnight in a given time zone, the edge can shift by up to a day. For rules where the boundary matters, check how your tool defines it.
A worked example in SQL
The next rule selects subscribers who clicked any email in the last 30 days. It is a behavioural rule that combines a profile condition, an event condition, and a relative time window.
-- PostgreSQL: subscribers who clicked an email in the last 30 days
SELECT s.id
FROM subscribers s
WHERE s.status = 'subscribed'
AND EXISTS (
SELECT 1
FROM events e
WHERE e.subscriber_id = s.id
AND e.event_type = 'email_click'
AND e.occurred_at >= now() - interval '30 days'
);Read it as three conditions joined by AND. The profile condition (status = 'subscribed') is the consent check. The event condition is the EXISTS subquery, which tests whether at least one matching event exists. The time window sits inside the subquery, so it applies to the event and not to the subscriber record.
To negate it, change EXISTS to NOT EXISTS. The result is subscribers with no click in the last 30 days. That is the correct form of "did not click recently". It still includes people who have never clicked and people who clicked 31 days ago.
Adding a count threshold
A single click is a weak signal. People click by accident, and email security scanners can follow links automatically. A count threshold asks for repeated behaviour.
-- PostgreSQL: subscribers who clicked at least twice on running content in the last 60 days
SELECT subscriber_id
FROM events
WHERE event_type = 'email_click'
AND topic = 'running'
AND occurred_at >= now() - interval '60 days'
GROUP BY subscriber_id
HAVING COUNT(*) >= 2;Here WHERE filters individual events before they are counted. HAVING filters the groups after counting. Putting COUNT(*) >= 2 in WHERE is an error, because counts do not exist until grouping happens.
This query does not check status. It returns anyone with matching events, including people who have since unsubscribed. Before you send, join it to the subscribers table or add the consent condition, as the combined example in a later chapter does.
Rule order and evaluation
Two evaluation behaviours matter when you write rules.
First, a segment rule gives a yes or no for each subscriber independently. Two different segments can contain the same person. If you need each person in only one group, as with lifecycle stages, you must write rules that cannot overlap. The CASE expression does this because it checks branches in order and stops at the first match:
-- PostgreSQL: assign each subscribed contact exactly one lifecycle stage
SELECT id,
CASE
WHEN last_purchase_at >= now() - interval '90 days' THEN 'active_customer'
WHEN last_purchase_at IS NOT NULL THEN 'lapsed_customer'
WHEN created_at >= now() - interval '14 days' THEN 'new_subscriber'
ELSE 'prospect'
END AS lifecycle_stage
FROM subscribers
WHERE status = 'subscribed';The order is part of the rule. The second branch, last_purchase_at IS NOT NULL, only means "lapsed" because the first branch already caught recent buyers. If you swapped the first two branches, every buyer would be labelled lapsed. When you write ordered rules, add a comment that states the dependency.
Second, many ESPs evaluate dynamic segments at send time or on a schedule, not instantly. A subscriber who clicks a link a minute before you send may not be in the segment yet. The next chapter covers when that matters.
Common errors
The mistakes below account for most broken segments. Check for them before you send.
- Missing consent condition. The segment includes unsubscribed or pending contacts.
- Wrong operator between groups. AND where you meant OR produces an empty or tiny segment. OR where you meant AND produces a segment that is too large.
- Unbracketed mixed logic.
A OR B AND Cdoes not mean(A OR B) AND C. - NULL blindness. Comparisons skip subscribers with missing values.
- Negation without a window. "Has not clicked" can mean never, or not recently.
- Window on the wrong thing. Filtering
created_atwhen you meant to filteroccurred_aton events. - Unverified size. A rule that returns zero or the entire list is almost always a bug. Check the count before you send.
Checklist for writing a rule
- State the goal in one sentence: who should get which message, and why.
- Write the consent condition first.
- Choose event type, property filter, count threshold, and window for each behaviour.
- Combine with AND, OR, and NOT, and bracket any mixed logic.
- Handle NULL values explicitly.
- Run it and check the size.
- Spot-check known subscribers.
Exercise
A teammate writes a segment as status = 'subscribed' AND clicked_running OR purchased_running, intending "subscribed people who clicked or purchased running content". Why is it wrong, and how do you fix it?
Show answer
AND binds more tightly than OR, so the rule means (status = 'subscribed' AND clicked_running) OR purchased_running. Anyone who purchased running content is included even if they have unsubscribed. Fix it with brackets: status = 'subscribed' AND (clicked_running OR purchased_running).
Exercise
You want "customers who have not purchased in 90 days or more, including people who have never purchased". Why does WHERE last_purchase_at < now() - interval '90 days' miss part of this group, and what condition fixes it?
Show answer
For people who never purchased, last_purchase_at is NULL, and a comparison with NULL is neither true nor false, so those rows are dropped. Use WHERE last_purchase_at < now() - interval '90 days' OR last_purchase_at IS NULL. If you want only past buyers, use the first condition alone.
Exercise
A rule says "did not click in the last 30 days". Write the SQL pattern that expresses it correctly, and name two kinds of subscriber it includes.
Show answer
Use NOT EXISTS over the events table with event_type = 'email_click' and occurred_at >= now() - interval '30 days', correlated on the subscriber id. It includes subscribers who have never clicked, and subscribers whose last click was more than 30 days ago.