Your UPDATE statement does not contain a WHERE clause (only the subselect does). Therefore, the UPDATE will operate on
all rows of the table.
Once that is established, let's look at the subselect: this is a correlated subquery to find any row from table SCH.CLIENT with the same ID as the current row from SCH.CASE. If there is a matching row in SCH.CLIENT, you will get the C.ID value. If there is no matching row (remember, all rows of SCH.CASE are updated), you will get NULL as result of the scalar subselect.
What you probably want to have is this:
Code:
UPDATE sch.case AS c1
SET cnameid = ( SELECT c.id
FROM sch.client AS c
WHERE c.id = c1.id
FETCH FIRST 1 ROWS ONLY )
WHERE EXISTS ( SELECT c.id
FROM sch.client AS c
WHERE c.id = c1.id
FETCH FIRST 1 ROWS ONLY )
Notes:
- The DISTINCT in the subselect is unnecessary. You are doing a FETCH FIRST 1 ROW ONLY, so at most 1 row can be returned. If you have only 1 row, you cannot have duplicates. Hence, you don't need the duplicate elimination of DISTINCT.
- Don't worry about the two subqueries. DB2 will merge and execute them only once.
- You are setting SCH.CASE.CNAMEID to SCH.CLIENT.ID. But in the subselect, you check that this ID is the same as C1.ID. So do you need the subselect at all?
- The SQL MERGE statement may be another alternative.