Skip to content
Advertisement

update rows using inner join posgresql

I have 2 tables users and countries, and i’m trying to set the country.name with users.country_name for all countries with null name.

Schema :

enter image description here

// Creating tables
Table users as U {
  id int [pk, increment] // auto-increment
  full_name varchar
  created_at timestamp
  country_code int
  country_name varchar
}

Table countries {
  code int [pk]
  name varchar
  continent_name varchar
 }

Ref: U.country_code > countries.code

QUERY

update c set c.name = u.country_name from
countries as c inner join users as u 
on c.code = u.country_code 
where c.name is null;

Error : DBSQLException: SQL Error [42P01]

Advertisement

Answer

Follow the correct update join syntax and also remove the alias from the LHS of the SET clause:

update countries c
set name = u.country_name
from users as u 
where c.code = u.country_code and c.name is null;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement