How to UPDATE a table entry based on the most recent entry with the same id in another table?

Viewed 26

Apologies if I am asking the obvious, but as a beginner, the obvious is not always that obvious.

In an employee database, I am maintaining a table of positions the employee has had during his employment with the company. For the sake of simplicity, I will keep the code as short as possible.

I have a temporary table based on the position table.

CREATE TEMP TABLE IF NOT EXISTS tmp AS SELECT * FROM saireco.position LIMIT 0;

The temporary table gets the latest information from the source system. I remove unwanted entries from the temp table. Next, I update the temporary table if the EmployeeStatusCode in the temporary table is different from the EmployeeStatusCode in the position table (the SET command here does not have any particular meaning).

UPDATE tmp t
  SET "PositionCreationDate" = '2022-05-16'
FROM saireco."position" p
WHERE (t."EmployeeID" = p."EmployeeID"
   AND t."EmploymentStatusCode" != p."EmploymentStatusCode")
;

The above code is flawed because the position table can contain multiple entries for the same employee (the temporary table tmp will only contain a maximum of one entry per employee). I have come up with the following code which uses the latest sequence id "PositionID".

UPDATE tmp t
  SET "PositionCreationDate" = '2022-05-16'
FROM saireco."position" p
WHERE (t."EmployeeID" = p."EmployeeID"
   AND t."EmploymentStatusCode" != p."EmploymentStatusCode")
   AND p."PositionID" IN (SELECT MAX(pp."PositionID") FROM saireco."position" pp WHERE pp."EmployeeID" = t."EmployeeID")
;

My questions are twofold. Is this the correct way to achieve what I would like to achieve, e.g. update the temporary table if the most recent entry for the "EmployeeID" has changed; note the "PositionID" is a sequence which automatically gets incremented when a new entry is added to the table)? Secondly, because I already ensure the "EmployeeID" is equal here SELECT MAX(pp."PositionID") FROM saireco."position" pp WHERE pp."EmployeeID" = t."EmployeeID", does it mean I can get rid of the first condition t."EmployeeID" = p."EmployeeID", resulting in the following code?

UPDATE tmp t
  SET "PositionCreationDate" = '2022-05-16'
FROM saireco."position" p
WHERE (t."EmploymentStatusCode" != p."EmploymentStatusCode")
   AND p."PositionID" IN (SELECT MAX(pp."PositionID") FROM saireco."position" pp WHERE pp."EmployeeID" = t."EmployeeID")
;
0 Answers
Related