SQL To Flag First-Time Sender To Recipient Messages

Last updated: November 29, 2026

Quick Overview

Given a messages table with tenant_id, message_id, sender, recipient and received_at, write a query that labels each message as first contact if that sender had never emailed that recipient within the same tenant before, then count first-contact messages per tenant per day.

Abnormal Security
Data Manipulation (SQL/Python)
Data Engineer
Abnormal Security
November 29, 2026
Data Engineer
Phone Screen
Data Manipulation (SQL/Python)
Easy

0

0

0 solved


Given a messages table with tenant_id, message_id, sender, recipient and received_at, write a query that labels each message as first contact if that sender had never emailed that recipient within the same tenant before, then count first-contact messages per tenant per day.

First contact between a sender and recipient is one of the simplest behavioral signals behind Abnormal's detections and a common analytics building block. The interviewer checks window function fluency, correct partitioning that includes the tenant, and tie handling when two messages share a timestamp.

What the Interviewer Expects
  • Partitions by tenant, sender and recipient
  • Uses ROW_NUMBER or MIN over a window rather than a self join
  • Handles timestamp ties deterministically
  • Aggregates by tenant and calendar day correctly
  • Mentions case normalization of email addresses
Key Topics to Cover
window functions
ROW_NUMBER
partitioning
date truncation
deduplication
How to Approach This
  1. Clarify the schema and expected output format before writing queries.
  2. Use CTEs (WITH clauses) to break complex queries into readable steps.
  3. Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
  4. Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
  5. For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
  • How would you change this to mean no contact in the last 90 days?
  • The table has 50 billion rows. How would you compute this incrementally each day?
  • How would you also count the recipient emailing the sender as prior contact?
  • How do you treat messages with many recipients?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice SQL Problems
Sample Answer
Clarify the Data

One row per (message, recipient); a message to five people has five rows. Addresses may differ in case. received_at is a UTC timestamp. Prior contact is only within the same tenant, because the same...

Approach

Rank each (tenant, sender, recipient) pair's rows by time. The row ranked 1 is the first contact. Break ties with message_id so the result is deterministic. Then aggregate by tenant and day....


Submit Your Answer
Markdown supported

Related Questions