
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
How to ceate MySQL Trigger before Insert?
For this, the syntax is as follows −
delimiter // create trigger yourTriggerName before insert on yourTableName FOR EACH ROW BEGIN yourStatement1 . . N END // delimiter ;
To understand the above syntax, let us create a table −
mysql> create table DemoTable1919 ( Value int ); Query OK, 0 rows affected (0.00 sec)
Here is the query to create MySQL trigger before inserting −
mysql> delimiter // mysql> create trigger sumis60 before insert on DemoTable1919 FOR EACH ROW BEGIN declare custom_message varchar(256); IF (SELECT sum(Value) from DemoTable1919) = 60 THEN set custom_message= "cannot insert because sum(Value) is greater than 60"; signal sqlstate '13500' set message_text= custom_message; END IF; END // Query OK, 0 rows affected (0.00 sec) mysql> delimiter ;
Now you can insert some records in the table using insert command and check the working of trigger −
mysql> insert into DemoTable1919 values(10); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1919 values(20); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1919 values(30); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1919 values(40); ERROR 1644 (13500): cannot insert because sum(Value) is greater than 60
- Related Articles
- MySQL trigger to insert row into another table?
- Use a trigger to stop an insert or update in MySQL?
- Implement MySQL trigger in the first table to insert records in the second table?
- How to ceate right justified JTextField in Java?
- How to validate documents before insert or update in MongoDB?
- How to set delay for MySQL trigger/procedure execution?
- What is MySQL event and how it is related to trigger?
- How can we create and use a MySQL trigger?
- How can MySQL handle the errors during trigger execution?
- How to form a MySQL Conditional Insert?
- How to easily insert datetime in MySQL?
- How to insert DECIMAL into MySQL database?
- How to prevent duplicate INSERT in MySQL?
- Drop trigger if exists in MySQL?
- How is it possible for a MySQL trigger to execute multiple statements?

Advertisements