Query a Comma Separated Column
article.tags holds a comma-separated list, because somebody
decided a join table was overkill.
Return every tag that appears on more than one article:
tag— the tag, lowercase, with surrounding whitespace removedarticles— how many articles carry it
Order by articles descending, then tag
ascending.
The data has already drifted. Some entries have spaces around them, some differ in case, one article's list contains an empty entry, and one article has no tags at all. An empty entry is not a tag and must not appear in the result.
Expected output
tag | articles
----------+---------
databases | 3
postgres | 3
sql | 2
Editorial
WITH tag AS (
SELECT a.id, lower(trim(t)) AS tag
FROM article a
CROSS JOIN unnest(string_to_array(a.tags, ',')) AS t
WHERE trim(t) <> ''
)
SELECT tag, count(DISTINCT id) AS articles
FROM tag
GROUP BY tag
HAVING count(DISTINCT id) > 1
ORDER BY articles DESC, tag ASC;
What unnest in the FROM clause is doing
string_to_array('sql, databases,Postgres', ',') gives
{sql," databases",Postgres}, and unnest turns that
array into three rows. Putting a set-returning function in
FROM beside a table is an implicit LATERAL: it is
evaluated once per article row, with access to that row's columns.
One article with three tags becomes three rows, which is the grain the question
needs.
Article 5 has NULL tags.
unnest(string_to_array(NULL, ',')) produces no
rows, so the CROSS JOIN drops article 5 entirely — which
is the wanted behaviour here, and a trap if you ever need the article listed
anyway. For that you would need LEFT JOIN LATERAL ... ON true.
The cleaning is the problem
Three separate repairs, each for a different flavour of drift:
trim(t)—' databases'and'databases'are different strings, so without it the answer splits one tag into twolower(...)— article 2 wroteSQLand article 1 wrotesqlWHERE trim(t) <> ''— article 3's trailing comma produces a fourth, empty element
Every one of these is work the schema should have made unnecessary. Nothing is validating this column, so every reader of it re-derives what a tag is, and two readers who disagree produce two different answers from the same data.
count(DISTINCT id), not count(*)
The question is how many articles carry the tag. If one article's
list said 'sql,sql' — and nothing stops it —
count(*) would report 2 for a single article. This is the same
grain mistake as fan-out, arriving through a string instead of a join.
The schema this should have been
CREATE TABLE tag (
id int PRIMARY KEY,
name text NOT NULL UNIQUE
);
CREATE TABLE article_tag (
article_id int REFERENCES article(id) ON DELETE CASCADE,
tag_id int REFERENCES tag(id),
PRIMARY KEY (article_id, tag_id)
);
and then the question is five lines with no cleaning:
SELECT t.name AS tag, count(*) AS articles
FROM article_tag at JOIN tag t ON t.id = at.tag_id
GROUP BY t.name HAVING count(*) > 1;
The join table buys four things the text column cannot: the
UNIQUE on tag.name makes
'SQL' and 'sql' impossible rather than merely
undesirable, the composite primary key makes a duplicate tag on one article
impossible, the foreign key makes a tag on a deleted article impossible, and an
index on tag_id makes "articles with tag X" a seek instead of a
full scan with string surgery on every row.
When the array is the right answer
Not never. PostgreSQL has a real array type and a real index for it:
ALTER TABLE article ADD COLUMN tags_arr text[];
CREATE INDEX article_tags_gin ON article USING gin (tags_arr);
SELECT * FROM article WHERE tags_arr @> ARRAY['postgres'];
💡 GIN = an inverted index. It stores one entry per element pointing back at the rows containing it, which is what makes a containment query on an array or JSONB fast. That is a legitimate design when the list is small, read as a unit, and has no attributes of its own. It still gives you no uniqueness, no referential integrity and no place to hang a tag description — so the question to ask is whether a tag is an entity or just a value. Entities get tables.
text with commas in it is neither option. It is the array design
without the type, the index, or the operators.
What an interviewer is checking
That you can do the query, and then that you say the schema is wrong. The query is the answer to the question asked; naming the join table is the answer to the question behind it. The follow-up is usually "how would you migrate it", and the shape of that answer is: add the new tables, backfill with the query above, write both for a while, move readers over, then drop the column.
article
6 rows
| idinteger | titletext | tagstext |
|---|---|---|
| 1 | Indexes Explained | sql, databases,Postgres |
| 2 | Query Plans | SQL,postgres |
| 3 | Sharding | databases, scaling, |
| 4 | Vacuum Internals | postgres |
| 5 | Hiring Loops |
Showing 5 of 6 rows.