Comparing Ways to Store a List in a Database

Sooner or later you need to store a list: tags on a blog post, toppings on a pizza, skills on a profile. Beginners usually reach for one of three approaches. This page compares them using tags on a post as the running example.

Approach 1: a comma-separated text column

idtitletags
1Learning SQLsql, beginners, databases

Pros: very quick to set up; easy to display.

Cons:

Approach 2: a separate table (or two)

CREATE TABLE tags (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE);
CREATE TABLE post_tags (
  post_id INTEGER REFERENCES posts(id),
  tag_id INTEGER REFERENCES tags(id),
  PRIMARY KEY (post_id, tag_id)
);

Pros:

Cons: more tables and a JOIN to read the list. For beginners, this feels like more work at first.

Approach 3: a JSON column

Many databases can store JSON, a text format for structured data, in a column:

["sql", "beginners", "databases"]

Pros: keeps the list together with the post; many databases offer functions to search inside JSON.

Cons:

Side by side

QuestionComma-separatedSeparate tableJSON column
Quick to set upYesMediumYes
Exact searchesFragileYesPossible, varies by database
Rename a tag onceNoYesNo
Count items per tagAwkwardEasyPossible, varies
Database checks validityNoYesLimited
Skills transfer between databasesYesYesLess so

Verdict by use case

SituationSuggested approach
Tags, categories or anything you search, count or renameSeparate table
A list you only ever display, never search, such as notes about a photoJSON column can be fine
Quick throwaway prototypeComma-separated is tolerable, but plan to replace it

The beginner rule of thumb

If you will ever ask "which rows have this item?", give the items their own table. That one question covers most real cases. Our normalisation self-check asks it as its very first question.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.

Related pages on this site