Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

MySQL triggers are named, row-level programs attached to permanent tables. They run automatically for qualifying INSERT, UPDATE, or DELETE rows, so they can normalize incoming data, enforce a rule, or write an audit record without relying on every application code path. On an Ubuntu VPS, the reliable process is to verify the server and table, create the trigger with the correct timing and row images, test every DML path your application uses, and deploy with a backup and an immediate rollback command.

What a MySQL trigger does

A trigger is a named database object associated with a table. MySQL activates it once for each row affected by a qualifying event. The core choices are timing (BEFORE or AFTER) and event (INSERT, UPDATE, or DELETE).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Choice When it runs Typical use
BEFORE INSERT Before each new row is written Set a missing value or validate/normalize input
AFTER INSERT After each new row is written successfully Record an audit row or maintain a related table
BEFORE UPDATE Before each changed row is written Check a transition or adjust a NEW value
AFTER UPDATE After each changed row is written successfully Capture old and new values for history
BEFORE DELETE Before each row is removed Validate or preserve information elsewhere
AFTER DELETE After each row is removed successfully Write deletion history or update a summary

Because execution is per row, a single multi-row statement can invoke a trigger many times. A trigger is not a scheduled job and does not run merely because a table changes outside the event types it supports.

Operations that activate triggers

  • Normal INSERT, UPDATE, and DELETE statements activate their corresponding triggers.
  • LOAD DATA can activate insert triggers.
  • Relevant REPLACE behavior can activate insert triggers and may also involve replacement semantics that you should test on your server.
  • TRUNCATE TABLE is not a row-by-row delete and does not activate delete triggers.
  • DROP TABLE does not activate delete triggers.
  • Cascaded foreign-key actions do not activate triggers.
  • Interfaces that change data without sending the corresponding SQL statements do not activate them.

Prepare MySQL on Ubuntu

Install and check the service

On a supported Ubuntu Server release, install the packaged server and check its systemd unit:

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.
sudo apt update
sudo apt install mysql-server
sudo systemctl status mysql

Ubuntu documents that the server should start automatically after installation. Restart it after configuration changes with:

sudo systemctl restart mysql.service

If startup or restart fails, inspect the service journal before changing database objects:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo journalctl -u mysql

Server configuration is under /etc/mysql. The packaged server’s primary daemon configuration file is commonly /etc/mysql/mysql.conf.d/mysqld.cnf.

Use a separate administrative and application account

For local administration on Ubuntu’s packaged server, the documented command is:

sudo mysql -u root

The local root account commonly uses socket authentication, so a shell user with sudo access can connect without a MySQL root password. Do not put that account in an application connection string. Create an application account with only the privileges its workload needs, and use a separate migration or database-owner account to create triggers.

Keep the database private unless remote access is required

Leave MySQL bound to localhost when applications run on the same VPS. If a remote client is genuinely needed, change the bind address in /etc/mysql/mysql.conf.d/mysqld.cnf, restrict the port with the VPS firewall and provider-level controls, and restart MySQL. Exposing port 3306 to the Internet without network restrictions turns a database configuration change into a security incident.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Inspect the schema before writing DDL

Connect as the migration account, select the intended database, and inspect the target table and existing triggers:

Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth
USE app_db;
DESCRIBE orders;
SHOW TRIGGERS FROM app_db;

Confirm the exact database and table before creating anything. A trigger must target a permanent base table; a view and a temporary table are not valid targets. Trigger names are unique within a schema, so a name that already exists cannot be reused for a second trigger in that schema.

Record the MySQL version as part of a deployment log, especially when moving DDL between servers:

SELECT VERSION();

Create a trigger: syntax and working examples

The general grammar

The essential form is:

CREATE [DEFINER = user] TRIGGER trigger_name
BEFORE | AFTER INSERT | UPDATE | DELETE
ON table_name
FOR EACH ROW
trigger_body;

For one SQL statement, the body can be a single statement such as SET. For several statements, wrap them in BEGIN ... END. The interactive MySQL client needs a temporary delimiter so it does not mistake the first semicolon inside the body for the end of CREATE TRIGGER.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Example: fill a missing timestamp before insert

Suppose orders.created_at may be omitted by older clients. A BEFORE INSERT trigger can supply it while preserving an explicitly supplied value:

USE app_db;

CREATE TRIGGER orders_bi_audit
BEFORE INSERT ON orders
FOR EACH ROW
SET NEW.created_at = COALESCE(NEW.created_at, CURRENT_TIMESTAMP);

NEW.created_at is the value about to be written. Assignments to NEW are primarily useful in BEFORE triggers, where you can adjust the incoming row before MySQL stores it. The column type, nullability, defaults, and other constraints still apply; a trigger is not a substitute for a correctly defined schema.

Example: write an update audit row

Assume an audit table already exists with columns order_id, old_status, new_status, and changed_at. This trigger records the values after an update succeeds:

DELIMITER $$

CREATE TRIGGER orders_au_audit
AFTER UPDATE ON orders
FOR EACH ROW
BEGIN
  INSERT INTO order_audit(order_id, old_status, new_status, changed_at)
  VALUES (OLD.id, OLD.status, NEW.status, CURRENT_TIMESTAMP);
END$$

DELIMITER ;

OLD.status is the value in the row before the update and NEW.status is the value produced by the update. For an INSERT, there is no prior row image to read as OLD; for a DELETE, there is no replacement row to read as NEW. Design each trigger around the row images available for its event.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black | LED mouse pad with 14 lighting modes, covers keyboard & mouse, anti-slip rubber base, waterproof surface, USB powered
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.

Choose timing based on the job

  • Use BEFORE when the trigger must validate or normalize the row, or assign values to NEW.
  • Use AFTER when the side effect should represent a row that passed the table’s write operation, such as an audit insert.
  • Keep the body small and deterministic. Every statement adds synchronous work to the transaction that caused the trigger.

Privileges and the DEFINER account

The account executing CREATE TRIGGER needs the TRIGGER privilege on the subject table. That creation privilege is separate from the privileges used later when the trigger fires.

At activation time, MySQL checks the trigger’s DEFINER account rather than the account that issued the DML. References to OLD and NEW require the documented read privileges; assigning to NEW requires update privilege; and statements that read or write other tables require those tables’ normal privileges. A trigger can therefore fail for an application user even though that user has permission to update the base table.

Omit or specify a definer deliberately

If you omit DEFINER, MySQL uses the account executing CREATE TRIGGER. That is simplest for a controlled migration, but it means the account must remain available when the trigger is activated and when objects are restored.

Use an explicit service account only when you have a reason to separate ownership from the migration operator. For example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
CREATE DEFINER = 'trigger_owner'@'localhost'
TRIGGER orders_au_audit
AFTER UPDATE ON orders
FOR EACH ROW
BEGIN
  INSERT INTO order_audit(order_id, old_status, new_status, changed_at)
  VALUES (OLD.id, OLD.status, NEW.status, CURRENT_TIMESTAMP);
END;

Grant that account only the privileges required by the trigger and keep it present during migrations, restores, and failover. An orphaned definer is a common reason for a trigger that exists but cannot execute.

Inspect, document, and order existing triggers

List and show the exact definition

SHOW TRIGGERS FROM app_db;
SHOW CREATE TRIGGER app_db.orders_au_audit;

The first command is useful for an inventory; the second preserves the exact body, timing, event, and definer for change review. Save the output with your deployment record before modifying a production trigger.

Make execution order explicit

If multiple triggers have the same timing and event on one table, use FOLLOWS or PRECEDES when creating a trigger:

Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.
CREATE TRIGGER orders_au_notify
AFTER UPDATE ON orders
FOR EACH ROW
FOLLOWS orders_au_audit
BEGIN
  INSERT INTO order_notifications(order_id, queued_at)
  VALUES (NEW.id, CURRENT_TIMESTAMP);
END;

Ordering is relevant only among triggers sharing the same event and timing. Name triggers by table, timing, and event so their purpose and intended order are visible during review.

Replace or drop a trigger safely

MySQL does not provide CREATE OR REPLACE TRIGGER. Replacing one therefore means dropping the old object and creating the new definition. Treat that as a deployment, not as an ad-hoc edit.

Capture the current definition first

SHOW CREATE TRIGGER app_db.orders_au_audit;

Copy the result into the change record and verify that the replacement has the same target table, event, timing, definer strategy, and ordering requirements.

Apply an explicit replacement

DROP TRIGGER IF EXISTS app_db.orders_au_audit;

DELIMITER $$
CREATE TRIGGER app_db.orders_au_audit
AFTER UPDATE ON orders
FOR EACH ROW
BEGIN
  INSERT INTO order_audit(order_id, old_status, new_status, changed_at)
  VALUES (OLD.id, OLD.status, NEW.status, CURRENT_TIMESTAMP);
END$$
DELIMITER ;

There is a short interval between the drop and create statements in which no trigger exists. Schedule the change during a controlled deployment window, pause writes if the audit is mandatory, and capture any DDL error immediately. The fastest object-level rollback is the reverse operation: drop the new trigger and recreate the saved definition.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
DROP TRIGGER IF EXISTS app_db.orders_au_audit;

DROP TRIGGER IF EXISTS is also safe for cleanup scripts because it does not fail merely because the object is already absent. Dropping a trigger does not remove the table or its data, but it does stop future automatic side effects.

Test the paths that matter

Do not infer trigger behavior from a successful CREATE TRIGGER. Test in a non-production database with representative rows, then repeat a controlled smoke test after deployment.

  1. Insert a row with the relevant columns omitted and verify the BEFORE INSERT result.
  2. Insert a row with an explicit value and verify that the trigger preserves or transforms it as intended.
  3. Update one row and confirm both OLD and NEW values in the audit result.
  4. Run a multi-row update or delete and count the resulting side-effect rows; row-level triggers should produce one invocation per affected row.
  5. Attempt a statement that violates a constraint and confirm that no misleading audit side effect remains from a failed transaction.
  6. Exercise any LOAD DATA or REPLACE path used by the application instead of assuming it behaves like a plain insert.
  7. Explicitly test operations that should not fire, such as TRUNCATE TABLE, and document that expectation for operators.

Use transactions where appropriate, inspect the base table and side-effect table after each case, and run SHOW CREATE TRIGGER to ensure the server has the definition you intended.

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Back up before deployment and plan rollback

A trigger change is DDL, but its effects are data changes made by later transactions. Before production work, record the schema, current trigger inventory, MySQL version, and service health. Back up the database with mysqldump or MySQL Shell Dump Utility, both documented in Ubuntu’s MySQL guidance.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical deployment sequence is:

  1. Confirm the connection target, selected schema, table definition, existing triggers, and MySQL service status.
  2. Take and verify a backup; ensure you know where the restore output will go.
  3. Apply the trigger DDL from a reviewed script, capturing the complete client output.
  4. Run representative insert, update, delete, multi-row, and failure-path tests.
  5. Verify side-effect rows, row values, the trigger definition, and application behavior.
  6. Keep the saved old definition and DROP TRIGGER IF EXISTS ... command ready for immediate object-level rollback.
  7. If the trigger has already caused incorrect data, stop the affected writes, preserve logs and backup metadata, remove or disable the trigger, and use the restore plan for broader recovery.

Backups protect data; they do not replace testing. A restore can also require the definer account and its privileges to exist before restored triggers can run.

Design trade-offs to decide before coding

Decision Prefer this when Risk or cost to account for
BEFORE versus AFTER Use BEFORE for validation/normalization; AFTER for effects that depend on a successful write Incorrect timing can expose uncommitted assumptions or prevent intended assignments
One trigger versus several ordered triggers One body keeps a simple rule together; separate bodies isolate responsibilities and use explicit ordering Multiple triggers increase ordering and deployment complexity
Trigger versus application processing Use a trigger when every SQL writer must receive the same invariant or audit behavior Trigger work is synchronous and less visible in application traces
Implicit versus explicit definer Implicit is simpler; an explicit service account can stabilize ownership across operators The explicit account must exist and retain precisely the needed privileges
Audit table side effect Use when a durable, transactionally coupled history is required Each source-row change adds a write and can enlarge transactions

Troubleshoot a trigger that does not fire

The trigger was never created in the schema you are using

Run SHOW TRIGGERS FROM app_db and check the connection’s current database with SELECT DATABASE(). A trigger belongs to the schema in which its target table exists; a similarly named object in another schema does not affect your statement.

The operation is not a firing event

Check whether the application uses TRUNCATE, a foreign-key cascade, a bulk loader, REPLACE, or a non-SQL data path. The firing rules differ, and some operations intentionally bypass row triggers.

The event or timing does not match

Inspect SHOW CREATE TRIGGER. An AFTER UPDATE trigger will not run for an insert, and a BEFORE INSERT trigger will not run for a delete. For multi-row statements, verify that your test actually changed rows; an update that matches zero rows invokes no row-level trigger.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The body fails because of privileges

Read the error returned to the client and inspect the trigger’s DEFINER. The definer needs the privileges required by every statement in the body, including access to related tables and the ability to assign NEW values where applicable. Restore a missing service account or recreate the trigger with an intentional owner rather than granting broad rights to the application.

The delimiter caused a truncated definition

When creating a multi-statement trigger interactively, set a temporary delimiter before CREATE TRIGGER and restore it afterward. If the client reports a syntax error near the first statement after BEGIN, inspect the delimiter handling and run SHOW CREATE TRIGGER after a successful retry.

Another trigger changes the result

List all triggers on the table and compare their event and timing. If two share both, add FOLLOWS or PRECEDES to make the intended order explicit. Also check whether a later trigger overwrites a value assigned by an earlier one.

Operational checklist

  • MySQL is installed, running, and reachable through the intended local socket or restricted network path.
  • The target schema and permanent table have been verified with USE and DESCRIBE.
  • The trigger name is unique in the schema.
  • Timing, event, and OLD/NEW references match the desired row image.
  • The creator has TRIGGER privilege, and the definer has only the privileges required at activation.
  • Existing same-event, same-time triggers have an intentional order.
  • A backup, saved definition, test script, and rollback command are available.
  • Insert, update, delete, multi-row, constraint-failure, and application-specific bulk paths have been tested.

The Bottom Line

Create triggers only after confirming the exact table and event they must cover. Use BEFORE triggers for controlled row changes, AFTER triggers for post-write side effects, inspect definitions and definers with SHOW CREATE TRIGGER, and deploy from a backup-backed script with a tested rollback.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.