Answer the question
In order to leave comments, you need to log in
How to make a field with automatic increment by condition in PostgreSQL?
Once I already asked something similar for mysql on the toaster: Mysql how to make an alternative numbering field?
What is the point, there is a table with entries, each entry has an id and a category, and you need to have a separate serial numbering for each category. That is, the third field alt_id in which the serial number of the record in the category should be written. (so that the order of this numbering does not go astray when deleting records, and so that you can always get one record and its serial number in the category with one request. Categories for records do not change)
This could be achieved, for example, by making a query before each insertion
select max(alt_id) from table where category = 'blabla';
Answer the question
In order to leave comments, you need to log in
But, firstly, after this request, another insert request may have time to execute and the counter will be incorrectThere is a lock for this.
I think for this task, I would not store the serial number in a separate column, but would calculate it on the fly through the window function.
Something like this:
WITH tmp AS (
SELECT
id,
name,
category,
ROW_NUMBER () OVER (
PARTITION BY category
ORDER BY name, id
) AS alt_id
FROM tablename
)
SELECT *
FROM tmp t
WHERE t.id = 123
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question