0

There is a table 'target' that looks like this:

id val
1 A
2 A
3

5 A
8 A
9

There is also a 'source' table that looks like this
id val
1
2 B

4 B

8 B
9 B

The directioins ask to use the 'source' table to transform the 'target' table into the 'result' table, which looks like this:

result
id val
1
2 B
3

5 A
8 B
9 B

I understand the logic of what the question is asking, as I believe what I need to do is basically say

IF target.id = source.id  
SET target.val = source.val  
ELSE target.val = target.val  

However, I am not completely sure how to accomplish this kind of update in SQL based on conditions w/ multiple tables using postgresql.

moeron221
  • 11
  • 1

1 Answers1

1

This looks like homework so I won't give a complete answer.

First step is to turn these into tables you can actually use. A handy tool for this is provided by http://sqlfiddle.com, with its "text to table" feature. Because of the dodgy formatting of the input we've got to make some fixups before it'll work (assuming empty cols are null, not empty string; fixing whitespace errors) but then we get:

http://sqlfiddle.com/#!15/4a046

(SQLfiddle is far from a model of how you should write DDL - it's a useful debugging tool, that's all).

So now you have something to play with.

At this point, I suggest looking into the UPDATE ... FROM statement, which lets you update a join. Or you can use a subquery in UPDATE to perform the required logic.

UPDATE target
SET val = source.val
FROM /* you get to fill this in */
WHERE /* you get to fill this in */

Merging data

Luckily, the result table they've given you is the result of a simple join-update. Note that rows present in "source" but not "target" haven't been added to "result"

If you were instead supposed to merge the two, so that entries in source that do not exist in target at all get added to target, this becomes what's called an upsert. This has been written about extensively; see links included in this post. Be glad you don't have to deal with that.

Community
  • 1
  • 1
Craig Ringer
  • 307,061
  • 76
  • 688
  • 778