CREATE TRIGGER Statement - Oracle to MySQL Migration

Both Oracle and MySQL offer CREATE TRIGGER statement that allows you to define a trigger on table. But the syntax of this statement is different in these databases:

For example, let's create a trigger as follows:

Oracle:

  -- Sample tables used in the trigger
  CREATE TABLE cities (name VARCHAR2(30));
  CREATE TABLE cities_audit (name VARCHAR2(30), created DATE);
 
  CREATE OR REPLACE TRIGGER cities_tr
    BEFORE
    INSERT OR UPDATE 
    ON cities
    REFERENCING OLD AS OLD NEW AS NEW
    FOR EACH ROW
  BEGIN
    INSERT INTO cities_audit VALUES (:NEW.name, SYSDATE);
  END;
  /

Now if you insert a row into cities table, the corresponding audit record is added to cities_audit table:

  INSERT INTO cities VALUES ('Madrid');
 
  -- Check the audit table
  SELECT * FROM cities_audit;
 
  # NAME                                CREATED
  # ------------------------------ -----------
  # Madrid                              19-JUN-22

The corresponding MySQL trigger is as follows:

MySQL:

  -- Sample tables used in the trigger
  CREATE TABLE cities (name VARCHAR(30));
  CREATE TABLE cities_audit (name VARCHAR(30), created DATETIME);
 
  DROP TRIGGER IF EXISTS cities_tr;
 
  DELIMITER //
 
  -- Note that trigger is for INSERT only, see notes below
  CREATE TRIGGER cities_tr
    BEFORE
    INSERT 
    ON cities
    FOR EACH ROW
  BEGIN
    INSERT INTO cities_audit VALUES (NEW.name, SYSDATE());
  END;
  //
 
  DELIMITER ;

Note the following differences in CREATE TRIGGER for Oracle and MySQL:

  • In Oracle you can define multiple trigger events. In the example above we used INSERT OR UPDATE trigger. MySQL allows you to define trigger on one event only. So you have to create multiple triggers in MySQL, one trigger for every event.
  • In Oracle REFERENCING OLD and NEW clause allows you to redefine how you reference old and new columns in the trigger body. MySQL does not support this clause and OLD.col and NEW.col references are used.
  • Semicolon (:NEW.col or :OLD.col i.e.) is required to references columns in Oracle, but it's not used in MySQL (NEW.col or OLD.col i.e.)

For more information, see Oracle to MySQL Migration.