I have following two tables in my potgres database with each type.
user
userid | bigint (PK) NOT NULL
username | character varying(255)
businessname | character varying(255)
inbox
messageid | bigint (PK) NOT NULL
username | character varying(255)
businessname | character varying(255)
Upto now the referencing to user table from inbox happens using username and businessname fields without foreign key constraints. My intention is to introduce a new field to inbox as userRefId and refer to the userid in user table without a foreign key so i can drop username and businessname fields which has been a bad way of lookup up for user from inbox.
For now i've prepared postgres ALTER and UPDATE queries to do this migration, but the issue is its taking so much time in live database with too much records. So now i want to create a stored procedure to do this task.
Queries
ALTER TABLE inbox ADD userRefId bigint;
UPDATE inbox SET userRefId = (SELECT userid FROM user WHERE username=inbox.username AND
businessname=inbox.businessname) WHERE (SELECT userid FROM user WHERE username=inbox.username AND
businessname=inbox.businessname) IS NOT NULL;
What is the best approach to address this issue? Improving this existing query with indexing or crating a stored procedure. Provided examples are highly appreciated as i'm fairly new.
varcharcolumn has no performance or storage advantages over e.g. 342 or 271.