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:
For more information, see Oracle to MySQL Migration.