Custom SERIAL / autoincrement per group of values

This has been asked many times and the general idea is bound to fail in a multi-user environment – and a blog system sounds like exactly such a case.

So the best answer is: Don’t. Consider a different approach.

Drop the column category_id completely from your table – it does not store any information the other two columns (id, category) wouldn’t store already.

Your id is a serial column and already auto-increments in a reliable fashion.

If you need some kind of category_id without gaps per category, generate it on the fly with row_number():

Leave a Comment