I have an PostgreSQL server with an existing table which has two fixed-width-non-unique-string (variable size) columns such as this:
| ID_STRING_A | ID_STRING_B |
| 'AAAA' | 'BBBB' |
| 'BBBB' | 'CCCC' |
| 'AAAA' | 'DDDD' |
Now I want to compute an integer representation for the both-column-elements and store them into additional columns. The result should look like this:
| ID_STRING_A | ID_STRING_B | ID_INT_A | ID_INT_B |
| 'AAAA' | 'BBBB' | 1 | 2 |
| 'BBBB' | 'CCCC' | 2 | 3 |
| 'AAAA' | 'DDDD' | 1 | 4 |
My frist approach based on the answers is:
Unfortunately, my update part seems to be highly iniefficient although there are indices on ID_STRING_A/B. While the query itself is done in minutes, the update part seems not to end. Here's the code:
ALTER TABLE mytable ADD COLUMN ID_INT_B integer;
ALTER TABLE mytable ADD COLUMN ID_INT_A integer;
UPDATE mytable SET ID_INT_A = g.ID_INT_A , ID_INT_B = g.ID_INT_B FROM
(
WITH T( n , s ) AS
(
SELECT ROW_NUMBER() OVER ( ORDER BY s ) , s
FROM
(
SELECT ID_STRING_A FROM mytable
UNION
SELECT ID_STRING_B FROM mytable
) AS X( s )
)
SELECT m.ctid AS id_ , m.ID_STRING_A AS ID_STRING_A , m.ID_STRING_B AS ID_STRING_B , T1.n AS ID_INT_A , T2.n AS ID_INT_B FROM mytable AS m
JOIN T AS T1 ON m.ID_STRING_A = T1.s
JOIN T AS T2 ON m.ID_STRING_B = T2.s
) AS g
WHERE mytable.ctid = g.id_