Relational Document-Tag Schema and Multi-Tag SQL Queries

Medium · Data Manipulation (SQL/Python) · Software Engineer · Onsite

Problem Statement

A knowledge-base service lets editors label published documents with reusable topic tags. A single document can carry multiple tags, and a single tag can be attached to many documents.

  1. Part 1 — Relational Schema & Indexing (Discussion / DDL): Design the three tables documents, tags, and document_tags:

    • documents: integer primary key id, non-null title, and non-null created_at timestamp.
    • tags: integer primary key id, and non-null unique name.
    • document_tags: association table using composite primary key (document_id, tag_id), foreign keys referencing documents(id) and tags(id) with ON DELETE CASCADE, and indexes supporting fast lookups in both directions (all tags for a given document, and all documents for a given tag).
  2. Part 2 — SQL Queries:

    • Query A — Graded SQL Deliverable (Per-Document Tag Counts): Return document_id, title, and tag_count for every row in documents. Any document without attached tags must appear with tag_count = 0. Sort rows by tag_count descending, then title ascending, and finally document_id ascending as a deterministic tie-breaker.
    • Query B — Companion Multi-Tag Filter (Discussion): Explain how to retrieve the id and title of documents tagged with both 'databases' and 'featured'.

Input Schema

documents

Column Type Description
id INTEGER Primary key identifying each document
title VARCHAR Display title of the document
created_at TIMESTAMP Creation timestamp of the document

tags

Column Type Description
id INTEGER Primary key identifying each tag
name VARCHAR Unique label of the tag

document_tags

Column Type Description
document_id INTEGER Foreign key referencing documents.id
tag_id INTEGER Foreign key referencing tags.id

Examples

Example 1

Input (documents):

id title created_at
101 'System Architecture' '2025-02-10 09:00:00'
102 'Query Optimization' '2025-02-11 14:30:00'
103 'Distributed Consensus' '2025-02-12 08:15:00'
104 'Draft Notes' '2025-02-13 16:45:00'

Input (tags):

id name
1 'databases'
2 'featured'
3 'systems'

Input (document_tags):

document_id tag_id
101 2
101 3
102 1
102 2
103 3

Expected Output (Query A):

document_id title tag_count
102 'Query Optimization' 2
101 'System Architecture' 2
103 'Distributed Consensus' 1
104 'Draft Notes' 0

Walk-through: - Documents 101 and 102 each have 2 rows in document_tags; 'Query Optimization' appears before 'System Architecture' under the alphabetical title ASC tie-breaker. - Document 103 has 1 tag, while document 104 ('Draft Notes') has zero rows in document_tags and still appears with tag_count = 0. - (For companion Query B, only (102, 'Query Optimization') carries both 'databases' and 'featured'.)

Constraints

  • Every document present in documents must appear once in Query A's output, showing tag_count = 0 when untagged.
  • Distinct documents may share an identical title; group per document (id) so separate documents are never merged.
  • Output row order matters: sort by tag_count DESC, then title ASC, then document_id ASC.
  • If documents is empty, return zero rows with column headers document_id, title, tag_count.

Step-by-step walkthrough

  1. Understand the goal and three-part prompt

    A document can carry multiple tags ('Query Optimization' is both 'databases' and 'featured'), and a tag can belong to multiple documents ('featured' belongs to both 'Query Optimization' and 'System Architecture'). That is a classic many-to-many relationship.

    The interview prompt asks for three deliverables:

    1. Part 1 (Schema DDL): Define documents, tags, and the join table document_tags with a composite primary key, cascading foreign keys, and indexes supporting fast lookups in both directions.
    2. Part 2, Query A (graded here): Return document_id, title, and tag_count for every document (0 when untagged), ordered by tag_count DESC, then title ASC, then document_id ASC as a final tie-breaker.
    3. Part 2, Query B: Return id and title for documents tagged with both 'databases' and 'featured'.
  2. Part 1a: Design the tables, composite key, and cascading foreign keys

    You cannot model a many-to-many relationship cleanly inside just two tables: storing 'databases,featured' as text inside documents makes tag lookups slow and fragile, while duplicating whole document rows per tag repeats titles and timestamps. Instead, we create a third join table (document_tags) with one two-integer row per (document_id, tag_id) link:

    documents                        document_tags               tags
    +-----+-----------------------+  +-------------+--------+    +----+-----------+
    | id  | title                 |  | document_id | tag_id |    | id | name      |
    +-----+-----------------------+  +-------------+--------+    +----+-----------+
    | 101 | System Architecture   |->|     101     |    2   |<---|  1 | databases |
    | 102 | Query Optimization    |  |     101     |    3   |    |  2 | featured  |
    | 103 | Distributed Consensus |  |     102     |    1   |    |  3 | systems   |
    | 104 | Draft Notes           |  |     102     |    2   |    +----+-----------+
    +-----+-----------------------+  |     103     |    3   |
                                     +-------------+--------+
    

    Key constraints in the DDL:

    • UNIQUE on tags.name guarantees 'databases' is stored once rather than duplicated under different IDs.
    • PRIMARY KEY (document_id, tag_id) (a composite primary key) enforces that the same tag cannot be attached to the same document twice, and automatically builds a B-tree index ordered by (document_id, tag_id).
    • REFERENCES ... ON DELETE CASCADE ensures every link points to a real document and a real tag, and automatically cleans up document_tags rows whenever a parent document or tag is deleted.
    CREATE TABLE documents (
        id         INTEGER PRIMARY KEY,
        title      TEXT NOT NULL,
        created_at TIMESTAMP NOT NULL
    );
    
    CREATE TABLE tags (
        id   INTEGER PRIMARY KEY,
        name TEXT NOT NULL UNIQUE
    );
    
    CREATE TABLE document_tags (
        document_id INTEGER NOT NULL REFERENCES documents (id) ON DELETE CASCADE,
        tag_id      INTEGER NOT NULL REFERENCES tags (id) ON DELETE CASCADE,
        PRIMARY KEY (document_id, tag_id)
    );
    
  3. Part 1b: Index both lookup directions

    Think of the primary key's B-tree index on (document_id, tag_id) like a paper phonebook sorted by (last_name, first_name):

    Primary key B-tree (document_id, tag_id)       Secondary B-tree (tag_id, document_id)
    ------------------------------------------     ----------------------------------------
    (doc 101, tag 2)  <-- contiguous for 101!      (tag 1, doc 102)
    (doc 101, tag 3)                               (tag 2, doc 101)  <-- contiguous for tag 2!
    (doc 102, tag 1)                               (tag 2, doc 102)
    (doc 102, tag 2)  <-- tag 2 is scattered!      (tag 3, doc 101)
    (doc 103, tag 3)                               (tag 3, doc 103)
    

    Looking up "all tags for document_id = 101" jumps straight to doc 101 in the primary-key index. Looking up "all documents with tag_id = 2", however, cannot seek on the second column when document_id is unknown — tag 2 is scattered across every matching document! So we add a reverse index starting with tag_id:

    CREATE INDEX idx_document_tags_tag_id ON document_tags (tag_id, document_id);
    

    Including document_id as the second column makes this a covering index (the database reads document_id straight out of the index without touching the table) and also makes DELETE FROM tags WHERE id = 2 (ON DELETE CASCADE) an instant index seek instead of a full table scan.

  4. Query A, phase 1: Preserve untagged documents with LEFT JOIN

    Query A requires every document in documents to appear, showing 0 if it has no tags.

    • An INNER JOIN keeps only documents that match at least one row in document_tags, silently erasing untagged documents.
    • A LEFT JOIN starting from documents keeps every document: because document 104 ('Draft Notes') has zero rows in document_tags, LEFT JOIN still outputs one row for document 104 with dt.document_id = NULL and dt.tag_id = NULL.
    • Notice we do not even need to join tags for Query A — each row in document_tags already represents one valid tag link.
    FROM documents AS d
    -- LEFT JOIN keeps documents that have zero rows in document_tags.
    LEFT JOIN document_tags AS dt
        ON dt.document_id = d.id
    
  5. Query A, phase 2: Count dt.tag_id (not *), group by key, and break ties

    After the LEFT JOIN, three small details make the aggregation and sorting airtight:

    1. COUNT(dt.tag_id) vs COUNT(*): COUNT(*) counts rows, and an untagged document's NULL-padded row is still 1 row — so COUNT(*) would falsely report 1 tag instead of 0! COUNT(dt.tag_id) counts only non-NULL values of dt.tag_id, turning that NULL row into 0.
    2. GROUP BY d.id, d.title: Always group by the primary key d.id so two distinct documents that happen to share the same title (say two editions titled 'Dune') are never collapsed into one row. Including d.title satisfies SQL engines (like PostgreSQL) that require non-aggregated SELECT columns in GROUP BY.
    3. ORDER BY tag_count DESC, d.title ASC, d.id ASC: Sorts most-tagged first, breaks count ties alphabetically by title, and uses d.id ASC so two identically titled books with equal tag counts still appear in a 100% deterministic order.
    SELECT
        d.id AS document_id,
        d.title AS title,
        -- Count matched tag_id values (not rows): an untagged document produces one
        -- NULL-padded row after LEFT JOIN, so COUNT(dt.tag_id) is 0 while COUNT(*) is 1.
        COUNT(dt.tag_id) AS tag_count
    FROM documents AS d
    -- LEFT JOIN keeps documents that have zero rows in document_tags.
    LEFT JOIN document_tags AS dt
        ON dt.document_id = d.id
    -- Group by primary key d.id so distinct documents sharing a title stay separate.
    GROUP BY d.id, d.title
    -- Sort by highest count, then alphabetical title, then document_id for ties.
    ORDER BY tag_count DESC, d.title ASC, d.id ASC
    
  6. Trace Query A on Example 1

    Watch what LEFT JOIN, COUNT(dt.tag_id), and ORDER BY do step by step across Example 1's four documents:

    After LEFT JOIN:                                After GROUP BY + COUNT(dt.tag_id):
    d.id | d.title               | dt.tag_id        doc_id | title                 | tag_count
    -----+-----------------------+----------        -------+-----------------------+----------
     101 | System Architecture   |     2              101  | System Architecture   |     2
     101 | System Architecture   |     3              102  | Query Optimization    |     2
     102 | Query Optimization    |     1              103  | Distributed Consensus |     1
     102 | Query Optimization    |     2              104  | Draft Notes           |     0
     103 | Distributed Consensus |     3
     104 | Draft Notes           |   NULL  <-- COUNT(dt.tag_id) skips NULL -> 0!
    

    Sorting by tag_count DESC, d.title ASC, d.id ASC puts 'Query Optimization' (2) ahead of 'System Architecture' (2) alphabetically, followed by 'Distributed Consensus' (1) and 'Draft Notes' (0): (102, 'Query Optimization', 2), (101, 'System Architecture', 2), (103, 'Distributed Consensus', 1), (104, 'Draft Notes', 0).

  7. Query B: Find documents matching every required tag

    For Query B (documents tagged with both 'databases' and 'featured'), beginners often write WHERE t.name = 'databases' AND t.name = 'featured'. That always returns zero rows, because WHERE tests one row at a time and a single row's t.name cannot equal two different strings at once!

    Instead, this pattern (called relational division) filters to rows matching any tag in the required list (IN (...)), groups by document, and uses HAVING to keep only documents that matched all 2 distinct tag names:

    SELECT
        d.id,
        d.title
    FROM documents AS d
    JOIN document_tags AS dt
        ON dt.document_id = d.id
    JOIN tags AS t
        ON t.id = dt.tag_id
    WHERE t.name IN ('databases', 'featured')
    GROUP BY d.id, d.title
    HAVING COUNT(DISTINCT t.name) = 2
    

    Tracing Example 1:

    • 'Query Optimization' (id = 102) matches 'databases' and 'featured' -> COUNT(DISTINCT t.name) = 2 -> kept (102, 'Query Optimization').
    • 'System Architecture' (id = 101) matches only 'featured' ('systems' is filtered out by WHERE) -> COUNT(DISTINCT t.name) = 1 < 2 -> dropped.
    • 'Distributed Consensus' (id = 103) and 'Draft Notes' (id = 104) match zero target tags -> dropped.
  8. Put the graded query (Query A) together

    Here is the complete SQL query for the graded deliverable (Query A):

    SELECT
        d.id AS document_id,
        d.title AS title,
        -- Count matched tag_id values (not rows): an untagged document produces one
        -- NULL-padded row after LEFT JOIN, so COUNT(dt.tag_id) is 0 while COUNT(*) is 1.
        COUNT(dt.tag_id) AS tag_count
    FROM documents AS d
    -- LEFT JOIN keeps documents that have zero rows in document_tags.
    LEFT JOIN document_tags AS dt
        ON dt.document_id = d.id
    -- Group by primary key d.id so distinct documents sharing a title stay separate.
    GROUP BY d.id, d.title
    -- Sort by highest count, then alphabetical title, then document_id for ties.
    ORDER BY tag_count DESC, d.title ASC, d.id ASC
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine organizing a knowledge base where one article (Query Optimization) can carry several subject stickers (databases, featured) and one sticker (featured) can sit on thousands of articles. Rather than stuffing a comma-separated list of stickers into the documents table, relational databases store each pairing as its own two-number index card in a join table (document_tags — a bridge table where each row links one document_id to one tag_id), guarded by a composite primary key (a primary key formed from two or more columns whose combination must be unique, preventing duplicate stickers on the same document). To count every document's stickers in Query A — including 0 for documents with no stickers — we start from documents with a LEFT JOIN (which keeps every row from the left table and fills unmatched right-table columns with NULL) and count COUNT(dt.tag_id) so NULL placeholders evaluate to 0.

Why do the obvious shortcuts fail? Using an INNER JOIN in Query A drops untagged documents completely because they have zero matching rows in document_tags, while writing COUNT(*) after a LEFT JOIN counts the single NULL-padded row and reports 1 tag instead of 0! Grouping by title alone merges two distinct documents that happen to share the same title, and in Query B writing WHERE t.name = 'databases' AND t.name = 'featured' always returns empty results because no single joined row can hold two different tag names at the same time.

Let's walk through Example 1's 4-document catalog:

documents LEFT JOIN document_tags                  GROUP BY d.id, d.title                     ORDER BY count DESC, title, id
-------------------------------------------        ---------------------------------------    ----------------------------------------
(101, 'System Architecture',   tag_id = 2)         (101, 'System Architecture',   cnt = 2)    (102, 'Query Optimization',    2)  'Q'<'S'
(101, 'System Architecture',   tag_id = 3)   -->   (102, 'Query Optimization',    cnt = 2) -> (101, 'System Architecture',   2)
(102, 'Query Optimization',    tag_id = 1)         (103, 'Distributed Consensus', cnt = 1)    (103, 'Distributed Consensus', 1)
(102, 'Query Optimization',    tag_id = 2)         (104, 'Draft Notes',           cnt = 0)    (104, 'Draft Notes',           0)
(103, 'Distributed Consensus', tag_id = 3)
(104, 'Draft Notes',           tag_id = NULL) <-- COUNT(dt.tag_id) = 0, whereas COUNT(*) would be 1!

Complexity

Let D be the number of rows in documents, T be the number of rows in tags, and L be the number of link rows in document_tags.

  • Query A — Time: O(D + L + D log D); Space: O(D). Every document and every link row is scanned once: a hash join + hash aggregate (or an ordered merge walk along documents(id) and the primary-key B-tree index — a balanced tree index that keeps keys sorted for O(log N) lookups and fast ordered scans — on document_tags(document_id, tag_id)) runs in O(D + L) time. Sorting the D per-document summary rows by (tag_count DESC, title ASC, id ASC) takes O(D log D) time and O(D) memory.
  • Query B — Time: O(k log T + M) where M is the total number of links across the k target tags; Space: O(U_match). Looking up the k tag names in the UNIQUE index on tags(name) takes O(k log T), and seeking each tag_id in the covering index (an index containing every column the query needs from that table) idx_document_tags_tag_id(tag_id, document_id) scans only the M link rows belonging to those k tags, keeping one counter per candidate document (U_match <= M).

Edge cases

  • Untagged documents: Preserved by LEFT JOIN, given tag_count = 0 by COUNT(dt.tag_id), and sorted after all tagged documents.
  • Empty document_tags table: Every document appears with tag_count = 0, ordered alphabetically by title and then document_id.
  • Distinct documents with the exact same title and tag_count: Kept separate by GROUP BY d.id, d.title and ordered deterministically by the final d.id ASC tie-breaker.
  • Empty documents table: Returns zero rows while still exposing the column headers document_id, title, tag_count.
  • Orphan or duplicate links: A foreign key (a database constraint requiring every child ID to reference an existing parent ID) prevents orphan document_id or tag_id values, and the composite primary key (document_id, tag_id) prevents duplicate links (if duplicates were ever possible, COUNT(DISTINCT dt.tag_id) would guard Query A).
  • Duplicate tag names inside Query B's IN list: If a caller passes IN ('databases', 'databases'), the HAVING threshold must match the number of distinct required tags (1), not the raw list length (2).

Common mistakes

  • Using JOIN instead of LEFT JOIN in Query A: Drops untagged documents completely instead of returning them with 0.
  • Writing COUNT(*) instead of COUNT(dt.tag_id): Counts the NULL-padded row produced by LEFT JOIN, reporting 1 tag for every untagged document!
  • Grouping by d.title alone: Merges two different documents that share the same title into one combined tag count.
  • Filtering a right-table column in WHERE after a LEFT JOIN: Putting WHERE t.deleted_at IS NULL or WHERE t.name <> 'archived' in WHERE runs after the outer join and deletes documents whose tags were all filtered out (instead of returning them with a count of 0); right-table filters belong in the LEFT JOIN ... ON clause.
  • Writing WHERE t.name = 'databases' AND t.name = 'featured' in Query B: Always returns zero rows because a single row's t.name cannot be two strings at once; use relational division (filtering WHERE t.name IN (...), grouping by document, and checking HAVING COUNT(DISTINCT t.name) = k).
  • Relying solely on PRIMARY KEY (document_id, tag_id) without a reverse index: Queries filtering by tag_id (and ON DELETE CASCADE when deleting a tag!) cannot seek on the second column of (document_id, tag_id) and degrade to full scans of document_tags.

Alternative approaches

  • Pre-aggregate document_tags before LEFT JOIN (Query A): Grouping document_tags by document_id first (SELECT document_id, COUNT(*) AS cnt FROM document_tags GROUP BY document_id) and LEFT JOINing that summary to documents with COALESCE(cnt, 0) avoids grouping wider d.title strings when documents have dozens of tags each.
  • INTERSECT or EXISTS per tag (Query B): SELECT document_id FROM document_tags JOIN tags ... WHERE name = 'databases' INTERSECT SELECT document_id ... WHERE name = 'featured' (or chaining EXISTS probes starting from the rarest tag) lets the planner short-circuit early when one tag is rare and another is very popular.

Follow-up questions

  • What changes in physical layout and index coverage when you declare the junction key as (document_id, tag_id) rather than (tag_id, document_id) in PostgreSQL versus InnoDB? A B-tree index on (a, b) sorts entries by a first and b second, so it directly serves WHERE a = ? and WHERE a = ? AND b = ?, but cannot seek WHERE b = ? alone — meaning you still need a second index in the opposite column order either way. In PostgreSQL, tables are stored as unordered heaps and both indexes are separate B-trees, so you create PRIMARY KEY (document_id, tag_id) plus a two-column covering index (tag_id, document_id) for index-only reverse scans. In MySQL (InnoDB), the primary key is a clustered index (meaning the table's physical rows are stored directly inside the primary-key B-tree in primary-key order), so (document_id, tag_id) physically groups all tags of a document onto adjacent disk pages, and a secondary index on (tag_id) alone automatically appends the primary key document_id to every leaf entry without repeating tag_id twice! Put the higher-QPS or latency-critical lookup first in the primary key — typically (document_id, tag_id) when every document page render fetches its tags.
  • When a search filters for at least five required tags at once, how does GROUP BY ... HAVING COUNT compare against PostgreSQL GIN-indexed arrays or an inverted-index search service? WHERE t.name IN (...) GROUP BY d.id HAVING COUNT(DISTINCT t.name) = 5 must scan the entire document_id list of all 5 tags, so a mega-tag like 'featured' (millions of documents) dominates runtime even if another requested tag has only 20 documents; inside relational SQL, starting from the rarest tag and probing (document_id, tag_id) with EXISTS (or intersecting sorted index scans) is much faster. Denormalizing tag_ids INTEGER[] onto documents with a PostgreSQL GIN (Generalized Inverted Index) — an index that maps each element to a compressed sorted posting list of row IDs — answers tag_ids @> ARRAY[1,2,3,4,5] rapidly by intersecting posting lists starting from the rarest tag, at the cost of losing foreign-key enforcement and rewriting document rows when a tag is deleted. At large catalog scale (faceted counts, relevance scoring, fuzzy text + 5+ tag filters), a dedicated search engine like Elasticsearch or OpenSearch uses SIMD-accelerated inverted-index bitsets built specifically for multi-term AND intersections, kept in sync asynchronously from the normalized SQL source of truth.
  • How should the DDL constraints and tag-counting query change if tags use soft deletion instead of hard removal? Add deleted_at TIMESTAMP NULL to tags so soft-deleting sets a timestamp instead of firing ON DELETE CASCADE, keeping historical document_tags rows intact if the tag is later restored. Replace UNIQUE (name) on tags with a partial index (an index built only over rows matching a WHERE filter) — CREATE UNIQUE INDEX uq_tags_active_name ON tags (name) WHERE deleted_at IS NULL — so a newly created active tag can reuse a soft-deleted tag's name. Crucially, in Query A you must join tags via LEFT JOIN tags AS t ON t.id = dt.tag_id AND t.deleted_at IS NULL and count COUNT(t.id) (putting t.deleted_at IS NULL in WHERE would drop documents whose only tags were soft-deleted instead of reporting 0!):

sql SELECT d.id AS document_id, d.title AS title, COUNT(t.id) AS tag_count FROM documents AS d LEFT JOIN document_tags AS dt ON dt.document_id = d.id LEFT JOIN tags AS t ON t.id = dt.tag_id AND t.deleted_at IS NULL GROUP BY d.id, d.title ORDER BY tag_count DESC, d.title ASC, d.id ASC

Follow-up questions

Similar questions

More Scribd interview questions

All 5 Scribd questions →