Full answer
sql
CREATE TABLE posts (id INTEGER PRIMARY KEY, comment_count INTEGER NOT NULL DEFAULT 0);
CREATE TABLE comments (id INTEGER PRIMARY KEY, post_id INTEGER NOT NULL);
CREATE TRIGGER c_ins AFTER INSERT ON comments BEGIN
UPDATE posts SET comment_count = comment_count + 1 WHERE id = NEW.post_id;
END;
CREATE TRIGGER c_del AFTER DELETE ON comments BEGIN
UPDATE posts SET comment_count = comment_count - 1 WHERE id = OLD.post_id;
END;
INSERT INTO posts (id) VALUES (1), (2);
INSERT INTO comments (post_id) VALUES (1), (1), (2);
DELETE FROM comments WHERE id = 1;
SELECT id, comment_count FROM posts ORDER BY id;| id | comment_count |
|---|---|
| 1 | 1 |
| 2 | 1 |
Post 1 got two comments and lost one; its counter reads 1. The triggers run in the same transaction as the comment write, so a rolled-back insert also rolls back its increment.
A drift check compares the counter with a fresh count:
sql
SELECT p.id, p.comment_count, COUNT(c.id) AS actual
FROM posts p LEFT JOIN comments c ON c.post_id = p.id
GROUP BY p.id, p.comment_count
HAVING p.comment_count <> COUNT(c.id);| id | comment_count | actual |
|---|
(0 rows)
No rows come back, which means every counter matches. Any row returned would name a post whose counter needs repair.
Under heavy concurrent writes in a server engine, every comment on a popular post updates the same row, which becomes a hot spot. Options then include batching increments or computing counts asynchronously.
sql
CREATE TABLE posts (id INTEGER PRIMARY KEY, comment_count INTEGER NOT NULL DEFAULT 0);
CREATE TABLE comments (id INTEGER PRIMARY KEY, post_id INTEGER NOT NULL);
CREATE TRIGGER c_ins AFTER INSERT ON comments BEGIN
UPDATE posts SET comment_count = comment_count + 1 WHERE id = NEW.post_id;
END;
CREATE TRIGGER c_del AFTER DELETE ON comments BEGIN
UPDATE posts SET comment_count = comment_count - 1 WHERE id = OLD.post_id;
END;
INSERT INTO posts (id) VALUES (1), (2);
INSERT INTO comments (post_id) VALUES (1), (1), (2);
DELETE FROM comments WHERE id = 1;
SELECT id, comment_count FROM posts ORDER BY id;
SELECT p.id, p.comment_count, COUNT(c.id) AS actual
FROM posts p LEFT JOIN comments c ON c.post_id = p.id
GROUP BY p.id, p.comment_count
HAVING p.comment_count <> COUNT(c.id);Checked on SQLite 3.46.1, run twice with identical output.
Key points
- AFTER INSERT and AFTER DELETE triggers adjust the counter
- Counter changes share the comment's transaction
- Recompute periodically to detect drift
- A single hot counter row can become a bottleneck
Common mistakes
- Updating counters only in some application paths
- Never verifying denormalized counts
Follow-ups
- What about comments that move between posts?
- How would you handle a very popular post?
Tips
- Include a drift check