Skip to content

Instantly share code, notes, and snippets.

@RStankov
Created April 4, 2024 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RStankov/342f637505845d1aa6179a66e1450ef1 to your computer and use it in GitHub Desktop.
Save RStankov/342f637505845d1aa6179a66e1450ef1 to your computer and use it in GitHub Desktop.
Counter Cache in SQL
CREATE OR REPLACE FUNCTION comments_count_update()
RETURNS TRIGGER AS $$
BEGIN
-- Increase count on insert
IF (TG_OP = 'INSERT') THEN
UPDATE posts SET comments_count = comments_count + 1
WHERE posts.id = NEW.post_id;
RETURN NEW;
-- Decrease count on delete
ELSIF (TG_OP = 'DELETE') THEN
UPDATE posts SET comments_count = comments_count - 1
WHERE posts.id = OLD.post_id;
RETURN OLD;
-- Handle case where comment might change its post
ELSIF (TG_OP = 'UPDATE' AND OLD.post_id != NEW.post_id) THEN
UPDATE posts SET comments_count = comments_count - 1
WHERE posts.id = OLD.post_id;
UPDATE posts SET comments_count = comments_count + 1
WHERE posts.id = NEW.post_id;
RETURN NEW;
END IF;
END;
-- register the driggers
CREATE TRIGGER comments_insert AFTER INSERT ON comments
FOR EACH ROW EXECUTE FUNCTION comments_count_update();
CREATE TRIGGER comments_delete AFTER DELETE ON comments
FOR EACH ROW EXECUTE FUNCTION comments_count_update();
CREATE TRIGGER comments_update AFTER UPDATE ON comments
FOR EACH ROW EXECUTE FUNCTION comments_count_update();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment