Home > other >  Insert into enum type using IF statement psql
Insert into enum type using IF statement psql

Time:04-22

Im copying data in from a csv file, I want insert a value which depends on if the data in the csv file reads yes or no

CREATE TYPE colour_type as ENUM ('red', 'blue');

CREATE TABLE colour_table
(
 colour colour_type
);

CREATE TABLE Dummy 
 (
  colour_type_dummy varchar(40)
 );
 
 \copy TABLE FROM 'colours.csv' WITH (FORMAT CSV, HEADER);

-- This is the part where I cant figure out the syntax for the IF statement
INSERT INTO colour_table (colour)
SELECT 'red' IF colour_type_dummy = 'yes' else 'blue' FROM Dummy

CodePudding user response:

You can try to use CASE WHEN expression

INSERT INTO colour_table (colour)
SELECT CASE WHEN colour_type_dummy = 'yes' THEN 'red'::colour_type ELSE 'blue'::colour_type END
FROM Dummy

sqlfiddle

  • Related