Time-Zone-Aware Activity Drop Detection Query
SQL & DataModel answerLast updated
Write SQL to find countries where the most creators posted significantly less in the recent week than their baseline, accounting for local time zones.
You're analyzing user engagement across different regions. Given the schema below, write a single ANSI SQL query that identifies which countries have the highest proportion of content creators whose activity declined sharply in the most recent week compared to their baseline period. The query must respect each creator's local time zone when determining calendar day boundaries.
Schema:
creators
+------------+---------+----------------------+--------+
| creator_id | country | tz | status |
+------------+---------+----------------------+--------+
| 1 | US | America/Los_Angeles | active |
| 2 | US | America/New_York | active |
| 3 | JP | Asia/Tokyo | active |
| 4 | BR | America/Sao_Paulo | active |
| 5 | DE | Europe/Berlin | banned |
+------------+---------+----------------------+--------+
posts
+---------+------------+---------------------+---------+------------+
| post_id | creator_id | created_at_utc | is_test | is_deleted |
+---------+------------+---------------------+---------+------------+
| 101 | 1 | 2025-08-26 23:30:00 | 0 | 0 |
| 102 | 1 | 2025-08-27 08:10:00 | 0 | 0 |
| 103 | 2 | 2025-08-29 01:05:00 | 1 | 0 |
| 104 | 2 | 2025-08-30 13:40:00 | 0 | 0 |
| 105 | 3 | 2025-08-20 09:00:00 | 0 | 1 |
| 106 | 3 | 2025-08-31 23:55:00 | 0 | 0 |
| 107 | 4 | 2025-08-05 16:30:00 | 0 | 0 |
| 108 | 4 | 2025-08-28 22:05:00 | 0 | 0 |
| 109 | 4 | 2025-09-01 01:10:00 | 0 | 0 |
| 110 | 1 | 2025-07-30 11:00:00 | 0 | 0 |
+---------+------------+---------------------+---------+------------+
Requirements:
Use 2025-09-01 as the reference date (do not use CURRENT_DATE).
Define two analysis windows based on each creator's local time zone:
- Recent period: 2025-08-25 through 2025-08-31 (7 days)
- Baseline period: 2025-07-28 through 2025-08-24 (28 days)
Calculate daily posting rates:
- recent_rate = posts in recent period / 7
- baseline_rate = posts in baseline period / 28
A creator has "declined activity" if:
- Their recent_rate < 0.7 × baseline_rate (more than 30% drop)
- They had at least 1 valid post in the baseline period
Only include creators with status = 'active' who posted at least once during the baseline. Exclude posts where is_test = 1 or is_deleted = 1.
Output columns:
countrytotal_active_creators(count of active creators with ≥1 baseline post)declining_creators(count meeting decline criteria)share_declining(decimal fraction)median_gap_days(median time in days between consecutive posts during the recent period, calculated across all valid posts in that country)
Return the top 10 countries ordered by share_declining descending, then total_active_creators descending.
Assume your SQL engine supports time zone conversion functions like CONVERT_TIMEZONE or FROM_UTC_TIMESTAMP. Explain your approach to calculating the median gap and any edge cases you handle.
Hints
Hint 1
Convert UTC timestamps to local dates before applying date filters—a post at 23:55 UTC may fall on different calendar days depending on the creator's time zone.
Hint 2
To avoid floating-point division issues, rearrange the inequality: recent_rate < 0.7 × baseline_rate becomes 10 × recent_count < 7 × (baseline_count / 4), or more cleanly, 40 × recent_count < 7 × baseline_count.
Hint 3
Use LAG() within each creator's posts (ordered by timestamp) to compute inter-post intervals, then aggregate those intervals to a per-country median using PERCENTILE_CONT.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is correctly assigning posts to calendar-day windows in each creator's local time zone, then computing per-creator activity rates and per-country aggregates.
Step 1: Normalize timestamps to local dates
Join posts with creators and convert created_at_utc into the creator's time zone, then cast to a date. Filter out test posts, deleted posts, and non-active creators upfront. Apply a slightly padded UTC filter (±1 day) for performance—time zones range from UTC-12 to UTC+14, so a post on 2025-08-31 UTC might be 2025-09-01 in Tokyo or 2025-08-30 in Los Angeles.
Step 2: Count posts per creator in each window
Use conditional aggregation to count posts falling into the recent period (Aug 25–31 local) and baseline period (Jul 28–Aug 24 local). Store these as n_recent and n_baseline.
Step 3: Classify creators
Only creators with n_baseline ≥ 1 are in the analysis cohort. A creator has declining activity if their recent rate dropped by more than 30%:
n_recent / 7 < 0.7 × (n_baseline / 28)
Rearranging to avoid floating-point and integer-division pitfalls:
40 × n_recent < 7 × n_baseline
Step 4: Compute median inter-post gaps
For each country, calculate the time between consecutive posts during the recent period only. Use LAG() partitioned by creator and ordered by timestamp to find the predecessor post. Convert the timestamp difference to days. Then compute the per-country median using PERCENTILE_CONT(0.5). Posts with no predecessor (first post per creator in the window) yield NULL and are excluded from the median.
Step 5: Aggregate and rank
Group by country to count total active creators in the cohort and how many meet the decline criteria. Calculate the share and join with the median gaps. Sort by share descending, then by total creators descending, and return the top 10.
SQL Query
WITH valid_posts AS (
SELECT
p.post_id,
p.creator_id,
c.country,
p.created_at_utc,
CAST(CONVERT_TIMEZONE('UTC', c.tz, p.created_at_utc) AS DATE) AS local_date
FROM posts p
INNER JOIN creators c ON c.creator_id = p.creator_id
WHERE c.status = 'active'
AND p.is_test = 0
AND p.is_deleted = 0
AND p.created_at_utc >= TIMESTAMP '2025-07-27 00:00:00'
AND p.created_at_utc < TIMESTAMP '2025-09-02 00:00:00'
),
windowed_posts AS (
SELECT *
FROM valid_posts
WHERE local_date BETWEEN DATE '2025-07-28' AND DATE '2025-08-31'
),
creator_activity AS (
SELECT
creator_id,
country,
SUM(CASE WHEN local_date BETWEEN DATE '2025-08-25' AND DATE '2025-08-31'
THEN 1 ELSE 0 END) AS n_recent,
SUM(CASE WHEN local_date BETWEEN DATE '2025-07-28' AND DATE '2025-08-24'
THEN 1 ELSE 0 END) AS n_baseline
FROM windowed_posts
GROUP BY creator_id, country
),
creator_cohort AS (
SELECT
creator_id,
country,
CASE WHEN 40 * n_recent < 7 * n_baseline THEN 1 ELSE 0 END AS is_declining
FROM creator_activity
WHERE n_baseline >= 1
),
country_summary AS (
SELECT
country,
COUNT(*) AS total_active_creators,
SUM(is_declining) AS declining_creators,
CAST(SUM(is_declining) AS DECIMAL(10,6)) / COUNT(*) AS share_declining
FROM creator_cohort
GROUP BY country
),
recent_intervals AS (
SELECT
w.country,
EXTRACT(EPOCH FROM (
w.created_at_utc - LAG(w.created_at_utc) OVER (
PARTITION BY w.creator_id ORDER BY w.created_at_utc, w.post_id
)
)) / 86400.0 AS gap_days
FROM windowed_posts w
INNER JOIN creator_cohort c ON c.creator_id = w.creator_id
WHERE w.local_date BETWEEN DATE '2025-08-25' AND DATE '2025-08-31'
),
country_medians AS (
SELECT
country,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY gap_days) AS median_gap_days
FROM recent_intervals
WHERE gap_days IS NOT NULL
GROUP BY country
)
SELECT
s.country,
s.total_active_creators,
s.declining_creators,
s.share_declining,
m.median_gap_days
FROM country_summary s
LEFT JOIN country_medians m ON m.country = s.country
ORDER BY s.share_declining DESC,
s.total_active_creators DESC,
s.country ASC
FETCH FIRST 10 ROWS ONLY;
Note: The query uses Snowflake/Redshift CONVERT_TIMEZONE and PostgreSQL EXTRACT(EPOCH FROM ...). For Spark/Databricks, replace CONVERT_TIMEZONE('UTC', c.tz, p.created_at_utc) with FROM_UTC_TIMESTAMP(p.created_at_utc, c.tz) and use UNIX_TIMESTAMP(current) - UNIX_TIMESTAMP(previous) for intervals.
Complexity
- Time: O(P) to filter and join posts, O(P log P) to compute LAG over posts and PERCENTILE_CONT per country, where P is the number of posts in the analysis range.
- Space: O(C) for per-creator aggregates, O(P) for windowed posts and intervals, where C is the number of creators.
Key Edge Cases
- Time zone boundaries: A UTC timestamp near midnight can fall on different local dates. Post 106 at 2025-08-31 23:55 UTC is 2025-09-01 08:55 in Tokyo (UTC+9), so it falls outside the recent period. Post 109 at 2025-09-01 01:10 UTC is 2025-08-31 22:10 in São Paulo (UTC-3), so it falls inside the recent period.
- Creators with zero baseline posts: Excluded from the cohort entirely, so brand-new creators don't inflate the decline count.
- Creators with fewer than 2 recent posts: Contribute no intervals to the median. If a country has no intervals, the LEFT JOIN yields NULL rather than dropping the country from results.
- Integer division: Writing
n_recent / 7directly in many SQL dialects performs integer division and silently truncates. The inequality40 * n_recent < 7 * n_baselineuses only integer arithmetic and is exact. - Deterministic ordering: The
LAGwindow includespost_idas a tiebreaker so that posts with identical timestamps produce a stable result. The final ORDER BY includescountryas a tertiary sort to ensure deterministic output when shares and totals tie.
Common Mistakes
- Using UTC date instead of local date for window membership.
- Forgetting to exclude test/deleted posts or non-active creators.
- Dividing post counts as integers and losing precision.
- Computing intervals across the boundary between baseline and recent periods instead of within the recent period only.
- Including all creators (even those with zero baseline posts) in the denominator, which artificially inflates the decline share.