1

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.

1
  • As a side note: using a "magic" number like 255 for the max length of a varchar column has no performance or storage advantages over e.g. 342 or 271. Commented Nov 6, 2020 at 20:18

1 Answer 1

4

Typically an UPDATE with a FROM clause is faster than a co-related subquery

UPDATE inbox 
  SET userRefId = u.userid
from "user" u
WHERE u.username = inbox.username 
  AND u.businessname = inbox.businessname
Sign up to request clarification or add additional context in comments.

2 Comments

Any suggestion for a stored procedure option?
@dineshalwis: the UPDATE won't be faster if you put it into a stored procedure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.