← Back to SQL, page 10

sql-0198 · Easy fresher

What does first normal form (1NF) require? Is a column holding 'sql,joins,cte' a violation?

1NF requires that each column holds a single atomic value per row and that there are no repeating groups such as tag1, tag2, tag3 columns. A comma-separated list in one column violates 1NF because the database cannot index, constrain or join the individual values. Store one row per value in a child table instead.

Full answer

With a list in a column, simple questions get hard. "Which posts have the tag joins?" turns into a LIKE search that also matches 'self-joins', cannot use an index, and cannot enforce that tags exist.

A child table fixes it:

sql
CREATE TABLE post_tags (post_id INTEGER, tag TEXT, PRIMARY KEY (post_id, tag));
INSERT INTO post_tags VALUES (1,'sql'),(1,'joins'),(1,'cte'),(2,'self-joins');
SELECT post_id FROM post_tags WHERE tag = 'joins';
post_id
1

Now each tag is a row, a primary key prevents duplicates per post, and a foreign key could reference a tags table.

Atomic depends on how the data is used. A full address stored as one text value is fine if it is only ever printed; it is a problem if reports group by city. JSON and array columns are allowed by modern engines and are a deliberate trade-off, not automatically wrong, but they lose the protections listed above.

sql
CREATE TABLE post_tags (post_id INTEGER, tag TEXT, PRIMARY KEY (post_id, tag));
INSERT INTO post_tags VALUES (1,'sql'),(1,'joins'),(1,'cte'),(2,'self-joins');
SELECT post_id FROM post_tags WHERE tag = 'joins';

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • One atomic value per column per row
  • No repeating groups like tag1, tag2, tag3
  • Lists in a column cannot be indexed, constrained or joined
  • Atomicity depends on how the data is queried

Common mistakes

  • Storing comma-separated ids and joining with LIKE
  • Adding numbered columns whenever more values are needed

Follow-ups

  • How would you migrate a comma-separated column to a child table?
  • When is a JSON column a reasonable choice?

Tips

  • Show the child-table version