1

Hi I have two tables called users and userrewards. When a new row gets inserted into the users table, I want to take the userid and create a new row in the userrewards table, only if the usertype is "premium". In the userrewards table I just need to insert the userid - the rest of the fields are set to default values until the user makes changes themselves. How can I do this via a trigger?

1

1 Answer 1

3

You need to create an "after instert" trigger on user: that's the table you're watching. Now, if I guessed your column names correctly, the sql for creating the trigger should look like this:

CREATE TRIGGER user_ai AFTER INSERT ON user 
FOR EACH ROW
BEGIN
    IF new.usertype = 'premium' THEN
        INSERT INTO userrewards (user_id) VALUES new.id;
    END IF;
END; 

Another example of a trigger with if statements and :old / :new values can be found here. MySQL documentatation for create trigger here. MySQL documentation for the if-syntax here.

Sign up to request clarification or add additional context in comments.

2 Comments

MySQL does not use the colon before NEW and OLD. I think that's Oracle syntax.
Thanks, @BillKarwin. You're right: I confused MySQL with Oracle.

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.