Owner and Guest Document Edit Rates

Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen

Problem Statement

Write a SQL query that computes daily owner and anonymous-guest contribution rates across active non-private documents in a collaborative workspace.

Apply the following rules for each calendar day (YYYY-MM-DD):

  1. Eligible documents only: Consider only edits whose doc_id appears in documents with is_private not equal to TRUE (False or NULL). Ignore edits referencing private documents or doc_id values missing from documents.
  2. Document-level daily denominator: On each calendar day that has at least one eligible edit, the denominator is the count of distinct active non-private documents edited on that day (including documents edited only by signed-in non-owner collaborators). Multiple edits to the same document on the same day — even within the exact same second — count that document once.
  3. Owner and guest percentages (0–100 scale):
    • percent_owner_edits: percentage of active non-private documents on that day that received at least one edit where edits.user_id = documents.owner_id, rounded to 4 decimal places.
    • percent_guest_edits: percentage of active non-private documents on that day that received at least one edit where edits.user_id IS NULL (an anonymous guest), rounded to 4 decimal places.
    • Because the same document can be edited by both its owner and an anonymous guest on the same day, a single document may contribute to both numerators (so the two percentages can sum to more than 100.0).

Return columns date, percent_owner_edits, and percent_guest_edits for every calendar day with at least one eligible edit, in any row order.

Input Schema

edits

Column Type Description
user_id INTEGER Identifier of the editing user, or NULL when edited by an anonymous guest.
doc_id VARCHAR Identifier of the edited document.
timestamp TIMESTAMP ISO-formatted timestamp of the edit (YYYY-MM-DD HH:MM:SS or YYYY-MM-DDTHH:MM:SS).
edit_size_bytes INTEGER Byte size of the edit payload.

documents

Column Type Description
doc_id VARCHAR Unique identifier of the document.
owner_id INTEGER Identifier of the user who owns the document.
created_at TIMESTAMP Creation timestamp of the document.
is_private BOOLEAN TRUE if the document is private (excluded from reporting), FALSE otherwise.

Examples

Example 1

Input:

documents

doc_id owner_id created_at is_private
D1 301 2024-08-15 09:00:00 False
D2 302 2024-08-20 14:30:00 False
D3 303 2024-08-25 11:00:00 False
D4 304 2024-09-01 08:00:00 True

edits

user_id doc_id timestamp edit_size_bytes
301 D1 2024-09-10 09:15:00 120
NULL D1 2024-09-10 09:15:00 45
NULL D2 2024-09-10 14:20:00 80
NULL D2 2024-09-10 14:20:00 30
399 D3 2024-09-10 16:45:00 210
304 D4 2024-09-10 17:00:00 60
302 D2 2024-09-11 10:05:00 95
303 D3 2024-09-11 11:30:00 150
NULL D3 2024-09-11 15:00:00 40

Output:

date percent_owner_edits percent_guest_edits
2024-09-10 33.3333 66.6667
2024-09-11 100.0 50.0

Explanation: - 2024-09-10: Private document D4 is excluded, leaving 3 active non-private documents (D1, D2, D3). D1 has both an owner edit (301) and a guest edit (NULL); D2 has two same-second guest edits (counted once); D3 has only a signed-in peer edit (399, counted in the denominator only). Owner rate: 100.0 * 1 / 3 = 33.3333; guest rate: 100.0 * 2 / 3 = 66.6667. - 2024-09-11: 2 active non-private documents (D2, D3). Both are edited by their owners (2 / 2 = 100.0), and D3 is also edited by a guest (1 / 2 = 50.0).

Constraints

  • date must be formatted as 'YYYY-MM-DD'.
  • percent_owner_edits and percent_guest_edits are expressed on a 0–100 scale and rounded to 4 decimal places.
  • Days with zero edits to non-private documents present in documents must not appear in the output.
  • Output rows may be returned in any order.

Step-by-step walkthrough

  1. Understand the metric and its unit of counting

    We have two tables from a collaborative document editor:

    • edits(user_id, doc_id, timestamp, edit_size_bytes): every edit event (user_id is NULL when the editor is an anonymous guest).
    • documents(doc_id, owner_id, created_at, is_private): metadata for each document.

    For each calendar day that has at least one edit to a non-private document in documents, we must compute:

    • percent_owner_edits: percentage of active public documents edited at least once by their owner_id that day.
    • percent_guest_edits: percentage of active public documents edited at least once by an anonymous guest (user_id IS NULL) that day.

    Notice that the unit of counting is distinct active public documents on that day, not raw edit rows — and there are three kinds of editors:

    Three types of edits on a public document (owner_id = 301):
      1. e.user_id = 301   -> Owner edit        (enters denominator AND owner numerator)
      2. e.user_id IS NULL -> Anonymous guest   (enters denominator AND guest numerator)
      3. e.user_id = 399   -> Signed-in peer    (enters denominator ONLY — neither numerator!)
    
    Why we group by (day, doc_id) BEFORE computing percentages:
      Doc D1 edited 10 times by owner + Doc D2 edited 1 time by guest
        Wrong (edit-level):     10 / 11 = 90.91% owner,  1 / 11 =  9.09% guest
        Right (document-level):  1 / 2  = 50.00% owner,  1 / 2  = 50.00% guest
    

    Also, because a single document can be edited by both its owner and a guest on the same day (like D1 on 2024-09-10 and D3 on 2024-09-11 in Example 1), both metrics count that document, so the two percentages do not have to add up to 100.0.

  2. Filter to known public documents and extract calendar dates

    Before counting anything, we join edits to documents to look up owner_id and is_private, and slice each timestamp to its calendar date:

    • Use an inner JOIN, not a LEFT JOIN: Only documents present in documents and not private belong in the metric. If an edit references an unknown doc_id (say 'Z') and we used a LEFT JOIN, 'Z' would survive with d.is_private = NULL, pass the privacy filter, and falsely inflate the denominator! (Even if you pre-filtered documents to public rows first, a LEFT JOIN from edits would keep private-document edits with NULL metadata unless you immediately dropped unmatched rows — which is simply an inner JOIN.)
    • WHERE d.is_private IS NOT TRUE: Drops rows where is_private is true (1), while safely keeping False (0) and NULL.
    • date(e.timestamp): Extracts 'YYYY-MM-DD' cleanly whether timestamp uses a space ('2023-03-02 08:15:00') or an ISO 'T' separator ('2023-03-02T08:15:00').
    FROM edits AS e
    JOIN documents AS d
        ON d.doc_id = e.doc_id
    WHERE d.is_private IS NOT TRUE
    
  3. Collapse edits to one row per document per day

    Next, we group the filtered edits by (date(e.timestamp), e.doc_id) in a CTE called doc_days. Each group represents one public document that was active on one calendar day.

    Inside each (day, doc_id) group, we compute two 0/1 flags using MAX(CASE ...), which acts as "was there at least one edit of this kind?":

    • MAX(CASE WHEN e.user_id = d.owner_id THEN 1 ELSE 0 END) AS has_owner_edit: evaluates to 1 if the owner edited the document at least once that day. When e.user_id is NULL, NULL = d.owner_id is UNKNOWN, so the ELSE 0 branch safely yields 0.
    • MAX(CASE WHEN e.user_id IS NULL THEN 1 ELSE 0 END) AS has_guest_edit: evaluates to 1 if an anonymous guest edited the document at least once that day. Always write IS NULL — writing e.user_id = NULL is never true in SQL!

    Grouping by (day, doc_id) also automatically handles duplicate timestamps: whether an owner saves 1 edit or 5 edits in the exact same second, MAX(...) still produces a single row with has_owner_edit = 1.

    WITH doc_days AS (
        -- Phase 1: Collapse all edits on the same (day, doc_id) into ONE row per
        -- active public document, with 0/1 flags for owner and guest activity.
        -- INNER JOIN drops edits whose doc_id is missing from documents, and
        -- d.is_private IS NOT TRUE excludes private documents before counting.
        SELECT
            date(e.timestamp) AS day,
            e.doc_id,
            MAX(CASE WHEN e.user_id = d.owner_id THEN 1 ELSE 0 END) AS has_owner_edit,
            MAX(CASE WHEN e.user_id IS NULL THEN 1 ELSE 0 END) AS has_guest_edit
        FROM edits AS e
        JOIN documents AS d
            ON d.doc_id = e.doc_id
        WHERE d.is_private IS NOT TRUE
        GROUP BY date(e.timestamp), e.doc_id
    )
    
  4. Roll up daily percentages

    Now that doc_days holds exactly one row per active public document per day, the final daily summary is a clean second GROUP BY day:

    • COUNT(*) is the total number of distinct active public documents on day (including documents edited only by signed-in non-owner collaborators, where both flags are 0).
    • SUM(has_owner_edit) is how many of those documents had at least one owner edit.
    • SUM(has_guest_edit) is how many of those documents had at least one guest edit.
    • Multiplying by 100.0 (with a decimal point!) prevents integer division (100.0 * 1 / 3 = 33.3333..., whereas 100 * 1 / 3 truncates to 33), and ROUND(..., 4) rounds to 4 decimal places. Because a day only enters doc_days when at least one public document was edited, COUNT(*) is guaranteed to be at least 1.
    -- Phase 2: Roll up active public documents per calendar day.
    -- COUNT(*) counts every edited public document (including collaborator-only docs),
    -- and 100.0 forces floating-point division before rounding to 4 decimals.
    SELECT
        day AS date,
        ROUND(100.0 * SUM(has_owner_edit) / COUNT(*), 4) AS percent_owner_edits,
        ROUND(100.0 * SUM(has_guest_edit) / COUNT(*), 4) AS percent_guest_edits
    FROM doc_days
    GROUP BY day
    ORDER BY day
    
  5. Walk through Example 1 across both days

    Let's trace Example 1 (D1 owner 301, D2 owner 302, D3 owner 303, and private D4 owner 304):

    On '2024-09-10' (private doc 'D4' is dropped by WHERE d.is_private IS NOT TRUE):
      doc 'D1': owner 301 + guest NULL in same second -> has_owner_edit = 1, has_guest_edit = 1
      doc 'D2': two guest NULL edits in same second   -> has_owner_edit = 0, has_guest_edit = 1
      doc 'D3': peer 399 edit (not owner, not NULL)   -> has_owner_edit = 0, has_guest_edit = 0  (in denominator!)
    
      COUNT(*) = 3 active public docs:
        percent_owner_edits = ROUND(100.0 * 1 / 3, 4) = 33.3333
        percent_guest_edits = ROUND(100.0 * 2 / 3, 4) = 66.6667
    
    On '2024-09-11':
      doc 'D2': owner 302 edit                        -> has_owner_edit = 1, has_guest_edit = 0
      doc 'D3': owner 303 edit + guest NULL edit      -> has_owner_edit = 1, has_guest_edit = 1
    
      COUNT(*) = 2 active public docs:
        percent_owner_edits = ROUND(100.0 * 2 / 2, 4) = 100.0
        percent_guest_edits = ROUND(100.0 * 1 / 2, 4) = 50.0
    
  6. Complete SQL query

    WITH doc_days AS (
        -- Phase 1: Collapse all edits on the same (day, doc_id) into ONE row per
        -- active public document, with 0/1 flags for owner and guest activity.
        -- INNER JOIN drops edits whose doc_id is missing from documents, and
        -- d.is_private IS NOT TRUE excludes private documents before counting.
        SELECT
            date(e.timestamp) AS day,
            e.doc_id,
            MAX(CASE WHEN e.user_id = d.owner_id THEN 1 ELSE 0 END) AS has_owner_edit,
            MAX(CASE WHEN e.user_id IS NULL THEN 1 ELSE 0 END) AS has_guest_edit
        FROM edits AS e
        JOIN documents AS d
            ON d.doc_id = e.doc_id
        WHERE d.is_private IS NOT TRUE
        GROUP BY date(e.timestamp), e.doc_id
    )
    -- Phase 2: Roll up active public documents per calendar day.
    -- COUNT(*) counts every edited public document (including collaborator-only docs),
    -- and 100.0 forces floating-point division before rounding to 4 decimals.
    SELECT
        day AS date,
        ROUND(100.0 * SUM(has_owner_edit) / COUNT(*), 4) AS percent_owner_edits,
        ROUND(100.0 * SUM(has_guest_edit) / COUNT(*), 4) AS percent_guest_edits
    FROM doc_days
    GROUP BY day
    ORDER BY day
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine walking through a shared workspace at the end of each day to inspect every public whiteboard that someone wrote on: rather than counting individual marker strokes, you keep one checklist line per active whiteboard and tick two independent boxes — "Did the board's owner write on it today?" and "Did an anonymous visitor write on it today?" In SQL, summarizing raw events at the entity-day level before computing daily averages is a two-stage aggregation, written cleanly with a common table expression, or CTE (a named temporary step introduced with WITH). We pair edits with documents using an inner join (a join that keeps only rows whose doc_id exists in both tables) and filter out private documents first so unknown and private boards never enter the checklist.

The naive one-step approach — dividing owner edit rows or guest edit rows by total edit rows per day — fails because the metric asks for the percentage of documents, not edits: one owner making 50 rapid edits to a single document would dominate the entire day, and on 2024-09-11 in Example 1 (3 total edits across 2 docs) row-level division would report 66.6667% / 33.3333% instead of 100.0% / 50.0%. Another common trap is pre-filtering edits to user_id = owner_id OR user_id IS NULL before grouping, which throws away public documents edited exclusively by signed-in teammates and artificially inflates both percentages.

Walk through 2024-09-10 in Example 1: public Document D1 (owner_id = 301) gets an edit from 301 and an edit from NULL; public Document D2 (owner_id = 302) gets two edits in the exact same second from NULL; public Document D3 (owner_id = 303) gets an edit from signed-in teammate 399; and private Document D4 (is_private = True) is excluded up front: 1. doc_days groups by (day, doc_id), collapsing D2's same-second edits into a single row and yielding 3 active-document rows: D1 -> (owner = 1, guest = 1), D2 -> (owner = 0, guest = 1), and D3 -> (owner = 0, guest = 0). 2. The outer query groups by day, counting COUNT(*) = 3 active public documents in the denominator. 3. Summing the flags gives percent_owner_edits = ROUND(100.0 * 1 / 3, 4) = 33.3333 and percent_guest_edits = ROUND(100.0 * 2 / 3, 4) = 66.6667.

Complexity

Let E be the number of rows in edits, D be the number of rows in documents, and K (K <= E) be the number of distinct (day, doc_id) pairs among public edits.

  • Time: O(E + D) average time with a hash join and hash aggregation, or O(E log D + E log E) when probing a B-tree index and sorting. Building a hash lookup table on documents(doc_id) takes O(D) work and probing it once per edit takes O(E) work; grouping those public edits into K (day, doc_id) rows takes O(E) hash updates (or O(E log E) comparisons if sort-based), and the final daily roll-up scans only the K summarized rows (plus an inexpensive sort over the number of distinct days for ORDER BY day).
  • Space: O(D + K), since the database holds at most D document metadata records for the join and K (day, doc_id) flag rows in doc_days.
  • Indexes that help: A primary key or index on documents(doc_id) accelerates the join lookup. Because date(e.timestamp) is a function call, storing or partitioning edits by a precomputed edit_date column lets analytical engines prune date ranges and group without recomputing date(...) on every row.

Edge cases

  • Multiple edits on the same document in the same second: Collapsed into one (day, doc_id) group by GROUP BY date(e.timestamp), e.doc_id, with MAX(...) keeping the flag at 1.
  • Same document edited by both owner and guest: Both has_owner_edit and has_guest_edit equal 1, so both percentages include it and their sum can exceed 100.0 (such as 100.0 + 50.0 = 150.0 on 2024-09-11 in Example 1, or up to 200.0).
  • Documents edited only by signed-in non-owner collaborators: Remain in doc_days with (0, 0), contributing 1 to COUNT(*) in the denominator and 0 to both numerators.
  • Private documents and days with only private edits: Excluded by WHERE d.is_private IS NOT TRUE before grouping, so private-only days emit no row.
  • Edits referencing a doc_id absent from documents: Dropped immediately by the inner JOIN.
  • Documents with owner_id IS NULL: e.user_id = NULL evaluates to UNKNOWN even when e.user_id is also NULL, so ELSE 0 sets has_owner_edit = 0 while guest edits still count has_guest_edit = 1.
  • CSV boolean strings imported into SQLite: Raw CSV loaders sometimes import 'True' and 'False' as text strings rather than 1 and 0; in SQLite 'True' IS NOT TRUE is true, so CSV ingestion scripts should cast booleans (LOWER(is_private) IN ('true', '1')) on load.
  • Midnight boundaries and ISO 'T' timestamps: date('2023-03-01 23:59:59') (2023-03-01) and date('2023-03-02T00:00:00') (2023-03-02) cleanly land on separate days.

Common mistakes

  • Aggregating directly at the edit level without doc_days: Weights documents by how many times someone saved rather than counting distinct active documents.
  • Filtering to e.user_id = d.owner_id OR e.user_id IS NULL before grouping: Drops collaborator-only documents from COUNT(*) and inflates both percentages.
  • Using LEFT JOIN documents: Keeps edits to unknown doc_ids with d.is_private = NULL, which passes IS NOT TRUE and pollutes the denominator.
  • Writing e.user_id = NULL instead of e.user_id IS NULL: Comparisons with = NULL never evaluate to true in SQL, forcing percent_guest_edits to 0.0 on every day.
  • Defining guests as e.user_id <> d.owner_id: Miscounts signed-in collaborators as guests while missing real guests (because NULL <> owner_id is UNKNOWN, not true!).
  • Grouping by raw e.timestamp instead of date(e.timestamp): Produces one output row per timestamp second instead of per calendar day.
  • Integer division (100 * SUM(...) / COUNT(*)): Truncates 100 * 1 / 3 to 33 instead of 33.3333 in SQLite and PostgreSQL.

Follow-up questions

  • How would you include quiet calendar days or unedited public documents so the daily time series has no missing dates? First clarify which gap the stakeholder wants filled: if they want one row for every calendar day even when zero public documents were edited site-wide, generate a continuous calendar with a recursive CTE (a WITH RECURSIVE query that steps +1 day from the minimum to the maximum date), LEFT JOIN doc_days onto it, and divide by NULLIF(COUNT(dd.doc_id), 0) so quiet days appear with NULL rates and an explicit active_docs = 0 column rather than a misleading 0%. If instead they want unedited public documents included in every day's denominator ("share of all existing public documents touched by an owner today"), cross-join the calendar spine with public documents where date(created_at) <= day and LEFT JOIN doc_days so untouched documents contribute 0 to the numerators and 1 to the denominator.
  • How would you scale this pipeline in a data warehouse once raw edit logs reach billions of events? Use table partitioning (splitting edits physically on disk by edit_date) and build an incremental daily summary table (day, doc_id, has_owner_edit, has_guest_edit) so each night's job scans only the new day's raw edits rather than all historical billions of rows. Store data in columnar storage (saving each column separately so the engine reads only user_id, doc_id, and timestamp while skipping edit_size_bytes), filter is_private IS NOT TRUE early, and use a broadcast join (sending the much smaller public documents lookup table to every worker node so massive edits partitions never shuffle across the network). Recompute and overwrite the last 2–3 date partitions on each run so late-arriving events are captured and reruns stay idempotent (safe to run repeatedly with identical results).
  • What signals could link logged-out guest edits back to existing accounts, and why is IP matching alone unreliable? Log a persistent first-party browser cookie or device ID alongside every edit event: if that same cookie ID authenticates with a non-null user_id in an earlier or later session, deterministic identity stitching can link the logged-out edit back to that account (and check whether it actually belongs to owner_id or a collaborator!). Avoid linking on IP address alone because corporate offices, universities, VPNs, and cellular carriers share one IP across many people while mobile users switch IPs constantly; use IP only as a weak supporting signal combined with user-agent string, document access token, and tight time proximity. Validate precision against ground-truth sessions where an anonymous editor logs in mid-session, report both raw and stitched rates, and enforce privacy and cookie-consent rules before linking identifiers.

Follow-up questions

Similar questions

More Notion interview questions

All 9 Notion questions →