Postgresql insert trigger to set value

postgresql, postgresql-9.1, triggers

Solution

You are correct that you need a trigger, because setting a default value for the column won't work for you - default values only work for `null` values and don't help you in preventing blank values.

In postgres there are a couple of steps to creating a trigger:

Step 1: Create a function that returns type `trigger`:

CREATE FUNCTION my_trigger_function()
RETURNS trigger AS $$
BEGIN
  IF NEW.C1 IS NULL OR NEW.C1 = '' THEN
    NEW.C1 := 'X';
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql

Step 2: Create a trigger that invokes the above function and fires `BEFORE INSERT`, which allows you to change the incoming values before they hit the table:

CREATE TRIGGER my_trigger
BEFORE INSERT ON T
FOR EACH ROW
EXECUTE PROCEDURE my_trigger_function()

And you're done.

See the above code executing on SQLFIddle.

You mention in a comment that the value `'X'` is retrieved from a subquery. If so, change the relevant line so something like:

NEW.C1 := (select some_column from some_table where some_condition);

Problem

Assume in Postgresql, I have a table `T` and one of its column is `C1`. I want to trigger a function when a new record is adding to the table `T`. The function should check the value of column `C1` in the new record and if it is null/empty then set its value to `'X'`. Is this possible?

Original source