Insert data from another table based on condition, if not insert specific value PSQL

StackOverflow https://stackoverflow.com/questions/22976247

  •  30-06-2023
  •  | 
  •  

Question

I have table A with an id column and a bunch of others. I also have table B which has an id column like table A and also another column called countries. However, not all id in table A are in table B. I want to insert a new column into table A called countries2 that basically inserts the countries from table B that corresponds to the ids in both tables. If a specific id from A does not exist in B, then it always puts in the VARCHAR 'none' into countries2. So for example if Table A has the ids 1, 2, 3, 4 and table B looks like:
id--country
1---'foo1'
3---'foo2'

I want table A to become something like:
id--country2--other original data from table A
1---'foo1'--...
2---'none'--...
3---'foo2'--...
4---'none'--...

Was it helpful?

Solution

You need to first alter your TableA to add an extra column (i.e yourNewColumn) of type varchar/varchar2

to add the column try something like

ALTER TABLE TableA ADD COLUMN yourNewColumn varchar(10);

Then you can use something like below to update TableA

UPDATE TableA
SET yourNewColumn = ISNULL(TableB.countries, 'none')
FROM TableA
LEFT JOIN TableB ON TableA.id = TableB.id

The ISNULL function in PostgreSQL might be something like

SET yourNewColumn = CASE WHEN TableB.countries IS NULL THEN 'none' ELSE TableB.countries END
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top