How to automatically increment several Integer columns based on alphabetically ordered text columns?
-
03-03-2021 - |
Question
Hello and thank you very much in advance for taking the time to look at my question. My question is as followed, I have a large dataset in PostgreSQL, recorded in a similar fashion as it is written in the table.
The Province, District and Town column are constantly updated and new rows are added. I would like to have incremental numbers for the Province_id, District_id and Town_id automatically assigned whenever a new entry is made in one of the text columns. Preferablly, the numbers would update dynamically whenever a new Province, District or Town is entered (alphabetically).
Could I use triggers to make this automatically? I have also looked a lot at things like the dense_rank() functions (but is this a good method to follow?) I would be very happy to hear if there are alternative solutions. Thank you.
Solution
Assumption:
These ID values will only be used for output/display and will not be used as Unique Keys or in other tables (as Foreign Keys), otherwise you'll need a lot of cascade updates and loss of performance as a single row insert would result in updating a huge part of the table and many other tables as well.
Solution:
You don't have to store these values. You can use window functions, e.g. DENSE_RANK()
to calculate these number when needed.
SELECT
province, district, town,
DENSE_RANK() OVER (ORDER BY province)
AS province_id,
DENSE_RANK() OVER (PARTITION BY province
ORDER BY district)
AS district_id,
DENSE_RANK() OVER (PARTITION BY province, district
ORDER BY town)
AS town_id
FROM
tableX AS t
;