Search code examples
sqlpostgresqlif-statementpgadmin-4

Add column to existing table in SQL with IF/ ELSE Statement


I am suing PgAdmin4
I have a table called Development. This table contains a column called Customer. I want to create a new column called Target which is equal to 1 when the Customer is null and 0 otherwise.

Here is my code:

ALTER TABLE development ADD COLUMN Target INTEGER;

IF Customer IS NULL then
  SET Target = 1;
else
  SET Target = 0;
END if;

I am getting this error:

ERROR:  syntax error at or near "IF"
LINE 3: IF Customer IS NULL then
        ^
SQL state: 42601
Character: 53

Solution

  • You could use an update statement with a case expression:

    UPDATE mytable
    SET target = CASE WHEN customer IS NULL THEN 1 ELSE 0 END