In Postgres, how do you restrict possible values for a particular column?

后端 未结 3 663
刺人心
刺人心 2021-01-30 08:09

I want to create a column element_type in a table (called discussion) that allows the text values \"lesson\" or \"quiz\" but will generate an error if

3条回答
  •  执念已碎
    2021-01-30 08:53

    This trigger throws an exception whenever someone try to insert or update a row with an invalid element_type.

    CREATE OR REPLACE FUNCTION check_discussion_element_type() RETURNS TRIGGER AS $$
    DECLARE new_element_type varchar(25);
    BEGIN
        SELECT element_type into new_element_type
            FROM discussion
            WHERE discussion.element_id = NEW.element_id;
    
        IF new_element_type != 'lesson' AND new_element_type != 'quiz'
           THEN RAISE EXCEPTION 'Unexpected discussion type';
        END IF;
        RETURN NEW;
    END;
    $$ LANGUAGE plpgsql;
    create trigger t_check_discussion_element_type after update or insert on discussion for each row execute procedure check_discussion_element_type();
    

    If you want to remove the hard-coded types you can adapt it to check if the new type exists in a type table.

提交回复
热议问题