1

I was wanting a mysql trigger for a specific field. When a NULL value is inserted into this field I would like to replace it with a default value. I know this code is not correct, but it would give you an idea of what I want.

CREATE TABLE IF NOT EXISTS example(
    id  INT NOT NULL    AUTO_INCREMENT,
    parent_id   INT NOT NULL    
);

CREATE TRIGGER insert_parentId_trigger BEFORE INSERT ON example
    FOR EACH ROW BEGIN
        IF parent_id = NULL THEN
           SET parent_id = 0;
        END IF
    END;
1
  • 2
    why don't you put 0 as default value? Commented Apr 28, 2011 at 16:37

3 Answers 3

4

Declare that column with not null default 0 instead of using trigger later.

When mysql is already handling that condition why we need to use trigger here?

You can use alter command to update your definition of your column

ALTER TABLE example MODIFY parent_id INT(11) NOT NULL DEFAULT 0
Sign up to request clarification or add additional context in comments.

Comments

2

I agree with the example of a Null be simplistically set to 0, then using a "Default" is fine, but what if you're after a value that's variable and cannot be a Default? For example:

IF `Creator` Is NULL THEN
   SET `Creator` = current_user();
END IF

For this type of use case, or something that requires a lookup, you will not be able to use Default.

Comments

0

Besides that Shakti Singh is totally right with the default value, you have to compare NULL values with IS instead of =
It should be IF parent_id IS NULL

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.