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.
-
Part 1 — Relational Schema & Indexing (Discussion / DDL): Design the three tables
documents,tags, anddocument_tags:documents: integer primary keyid, non-nulltitle, and non-nullcreated_attimestamp.tags: integer primary keyid, and non-null uniquename.document_tags: association table using composite primary key(document_id, tag_id), foreign keys referencingdocuments(id)andtags(id)withON DELETE CASCADE, and indexes supporting fast lookups in both directions (all tags for a given document, and all documents for a given tag).
-
Part 2 — SQL Queries:
- Query A — Graded SQL Deliverable (Per-Document Tag Counts): Return
document_id,title, andtag_countfor every row indocuments. Any document without attached tags must appear withtag_count = 0. Sort rows bytag_countdescending, thentitleascending, and finallydocument_idascending as a deterministic tie-breaker. - Query B — Companion Multi-Tag Filter (Discussion): Explain how to retrieve the
idandtitleof documents tagged with both'databases'and'featured'.
- Query A — Graded SQL Deliverable (Per-Document Tag Counts): Return
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
documentsmust appear once in Query A's output, showingtag_count = 0when 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, thentitle ASC, thendocument_id ASC. - If
documentsis empty, return zero rows with column headersdocument_id,title,tag_count.
Step-by-step walkthrough
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:
- Part 1 (Schema DDL): Define
documents,tags, and the join tabledocument_tagswith a composite primary key, cascading foreign keys, and indexes supporting fast lookups in both directions. - Part 2, Query A (graded here): Return
document_id,title, andtag_countfor every document (0when untagged), ordered bytag_count DESC, thentitle ASC, thendocument_id ASCas a final tie-breaker. - Part 2, Query B: Return
idandtitlefor documents tagged with both'databases'and'featured'.
- Part 1 (Schema DDL): Define
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 insidedocumentsmakes 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:
UNIQUEontags.nameguarantees'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 CASCADEensures every link points to a real document and a real tag, and automatically cleans updocument_tagsrows 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) );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 todoc 101in the primary-key index. Looking up "all documents withtag_id = 2", however, cannot seek on the second column whendocument_idis unknown —tag 2is scattered across every matching document! So we add a reverse index starting withtag_id:CREATE INDEX idx_document_tags_tag_id ON document_tags (tag_id, document_id);Including
document_idas the second column makes this a covering index (the database readsdocument_idstraight out of the index without touching the table) and also makesDELETE FROM tags WHERE id = 2(ON DELETE CASCADE) an instant index seek instead of a full table scan.Query A, phase 1: Preserve untagged documents with LEFT JOIN
Query A requires every document in
documentsto appear, showing0if it has no tags.- An
INNER JOINkeeps only documents that match at least one row indocument_tags, silently erasing untagged documents. - A
LEFT JOINstarting fromdocumentskeeps every document: because document104('Draft Notes') has zero rows indocument_tags,LEFT JOINstill outputs one row for document104withdt.document_id = NULLanddt.tag_id = NULL. - Notice we do not even need to join
tagsfor Query A — each row indocument_tagsalready 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- An
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:COUNT(dt.tag_id)vsCOUNT(*):COUNT(*)counts rows, and an untagged document'sNULL-padded row is still 1 row — soCOUNT(*)would falsely report1tag instead of0!COUNT(dt.tag_id)counts only non-NULLvalues ofdt.tag_id, turning thatNULLrow into0.GROUP BY d.id, d.title: Always group by the primary keyd.idso two distinct documents that happen to share the same title (say two editions titled'Dune') are never collapsed into one row. Includingd.titlesatisfies SQL engines (like PostgreSQL) that require non-aggregatedSELECTcolumns inGROUP BY.ORDER BY tag_count DESC, d.title ASC, d.id ASC: Sorts most-tagged first, breaks count ties alphabetically bytitle, and usesd.id ASCso 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 ASCTrace Query A on Example 1
Watch what
LEFT JOIN,COUNT(dt.tag_id), andORDER BYdo 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 ASCputs'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).Query B: Find documents matching every required tag
For Query B (documents tagged with both
'databases'and'featured'), beginners often writeWHERE t.name = 'databases' AND t.name = 'featured'. That always returns zero rows, becauseWHEREtests one row at a time and a single row'st.namecannot 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 usesHAVINGto keep only documents that matched all2distinct 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) = 2Tracing 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 byWHERE) ->COUNT(DISTINCT t.name) = 1 < 2-> dropped.'Distributed Consensus'(id = 103) and'Draft Notes'(id = 104) match zero target tags -> dropped.
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 alongdocuments(id)and the primary-key B-tree index — a balanced tree index that keeps keys sorted forO(log N)lookups and fast ordered scans — ondocument_tags(document_id, tag_id)) runs inO(D + L)time. Sorting theDper-document summary rows by(tag_count DESC, title ASC, id ASC)takesO(D log D)time andO(D)memory. - Query B — Time:
O(k log T + M)whereMis the total number of links across thektarget tags; Space:O(U_match). Looking up thektag names in theUNIQUEindex ontags(name)takesO(k log T), and seeking eachtag_idin 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 theMlink rows belonging to thosektags, keeping one counter per candidate document (U_match <= M).
Edge cases
- Untagged documents: Preserved by
LEFT JOIN, giventag_count = 0byCOUNT(dt.tag_id), and sorted after all tagged documents. - Empty
document_tagstable: Every document appears withtag_count = 0, ordered alphabetically bytitleand thendocument_id. - Distinct documents with the exact same
titleandtag_count: Kept separate byGROUP BY d.id, d.titleand ordered deterministically by the finald.id ASCtie-breaker. - Empty
documentstable: Returns zero rows while still exposing the column headersdocument_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_idortag_idvalues, 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
INlist: If a caller passesIN ('databases', 'databases'), theHAVINGthreshold must match the number of distinct required tags (1), not the raw list length (2).
Common mistakes
- Using
JOINinstead ofLEFT JOINin Query A: Drops untagged documents completely instead of returning them with0. - Writing
COUNT(*)instead ofCOUNT(dt.tag_id): Counts theNULL-padded row produced byLEFT JOIN, reporting1tag for every untagged document! - Grouping by
d.titlealone: Merges two different documents that share the same title into one combined tag count. - Filtering a right-table column in
WHEREafter aLEFT JOIN: PuttingWHERE t.deleted_at IS NULLorWHERE t.name <> 'archived'inWHEREruns after the outer join and deletes documents whose tags were all filtered out (instead of returning them with a count of0); right-table filters belong in theLEFT JOIN ... ONclause. - Writing
WHERE t.name = 'databases' AND t.name = 'featured'in Query B: Always returns zero rows because a single row'st.namecannot be two strings at once; use relational division (filteringWHERE t.name IN (...), grouping by document, and checkingHAVING COUNT(DISTINCT t.name) = k). - Relying solely on
PRIMARY KEY (document_id, tag_id)without a reverse index: Queries filtering bytag_id(andON DELETE CASCADEwhen deleting a tag!) cannot seek on the second column of(document_id, tag_id)and degrade to full scans ofdocument_tags.
Alternative approaches
- Pre-aggregate
document_tagsbeforeLEFT JOIN(Query A): Groupingdocument_tagsbydocument_idfirst (SELECT document_id, COUNT(*) AS cnt FROM document_tags GROUP BY document_id) andLEFT JOINing that summary todocumentswithCOALESCE(cnt, 0)avoids grouping widerd.titlestrings when documents have dozens of tags each. INTERSECTorEXISTSper tag (Query B):SELECT document_id FROM document_tags JOIN tags ... WHERE name = 'databases' INTERSECT SELECT document_id ... WHERE name = 'featured'(or chainingEXISTSprobes 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 byafirst andbsecond, so it directly servesWHERE a = ?andWHERE a = ? AND b = ?, but cannot seekWHERE 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 createPRIMARY 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 keydocument_idto every leaf entry without repeatingtag_idtwice! 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) = 5must scan the entiredocument_idlist 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)withEXISTS(or intersecting sorted index scans) is much faster. Denormalizingtag_ids INTEGER[]ontodocumentswith a PostgreSQL GIN (Generalized Inverted Index) — an index that maps each element to a compressed sorted posting list of row IDs — answerstag_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-termANDintersections, 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 NULLtotagsso soft-deleting sets a timestamp instead of firingON DELETE CASCADE, keeping historicaldocument_tagsrows intact if the tag is later restored. ReplaceUNIQUE (name)ontagswith a partial index (an index built only over rows matching aWHEREfilter) —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 jointagsviaLEFT JOIN tags AS t ON t.id = dt.tag_id AND t.deleted_at IS NULLand countCOUNT(t.id)(puttingt.deleted_at IS NULLinWHEREwould drop documents whose only tags were soft-deleted instead of reporting0!):
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
- 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?
- 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?
- How should the DDL constraints and tag-counting query change if tags use soft deletion instead of hard removal?
Similar questions
- Ranking Top Actors Across Shared Entity IDs
- Career Transition, Flagship Impact, Ambiguity, and Engineering Trade-offs
- Flexible-Schema Event Ingestion and Analytics Pipeline
- Resilient Event Ingestion with Strict Validation, Idempotency, and DLQ
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts