0

I'm having trouble understanding UPDATE with some sort of JOIN in PostgreSQL

I have the following table (names), sometimes a synonym is filled in the 3rd column:

id,name,synm,sd
41,xgvf
24,y4tg
32,zagr,xgvf
48,argv,bvre
53,bvre

I like to fill column 4 (sd) with the 'parent' id (sd column is empty now)

id,name,synm,sd
41,xgvf
24,y4tg
32,zagr,xgvf,41
48,argv,bvre,53
53,bvre

I tried the following sql statement (and many similar version of it) ...

update names
set sd =
(select n2.id from names n1
   inner join names n2 
   on 
   n1.synm = n2.name);

... i get the following error:

ERROR:  more than one row returned by a subquery used as an expression
SQL state: 21000

I understand my current wrong SQL tries to fill one sd row with all found id's. So somehow I do not get it.

How do I fill the synonym id (sd) in the whole table? Perhaps WITH RECURSIVE like statements?

1 Answer 1

1

You can simulate the join like this:

update names n1
set sd = n2.id
from names n2
where n2.name = n1.synm;

See the demo.
Results:

| id  | name | synm | sd  |
| --- | ---- | ---- | --- |
| 41  | xgvf |      |     |
| 24  | y4tg |      |     |
| 53  | bvre |      |     |
| 48  | argv | bvre | 53  |
| 32  | zagr | xgvf | 41  |
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it worked. Only I had to use "UPDATE names" without an alias somehow...

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.