简体   繁体   中英

How to verify table update and migrate data from another table - postgresql

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)

What i wanna achieve here is i want to add a new field called userRefId to inbox table and migrate data on user table's userid data into that where each username and businessname match in both tables.

These are the queries i use to do that.

ALTER TABLE inbox ADD userRefId bigint;

UPDATE inbox 
SET userRefId = u.userid
from "user" u
WHERE u.username = inbox.username 
AND u.businessname = inbox.businessname;

Now i want to verify the data has been migrated correctly. what are the approaches i can take to achieve this? (Note : the username on inbox can be null)

Would this be good enough to verification?

Result of select count(*) from inbox where username is not null; being equal to

select count(userRefId) from inbox;

Is the data transferred correctly? First, the update looks correct, so you don't really need to worry.

You can get all rows in consumer_inbox where the user names don't match

select ci.*. -- or count(*)
from consumer_inbox ci
where not exists (select 1
                  from user u
                  where ci.userRefId = u.userId
                 );

This doesn't mean that the update didn't work. Just that the values in consumer_inbox have no matches.

Under the circumstances of your code, this is equivalent to:

select ci.*
from consumer_inbox ci
where userId is null;

Although this would not pick up a userId set to a non-matching record (cosmic rays, anyone?).

You can also validate the additional fields used for matching:

select ci.*. -- or count(*)
from consumer_inbox ci
where not exists (select 1
                  from user u
                  where ci.userRefId = u.userId and
                        ci.username = u.username and
                        ci.businessname = u.businessname
                 );

However, all this checking seems unnecessary, unless you have trigger on the tables or known non-matched records.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM