Prevent having a zero value in a MySQL field?

MySQLMySQLi Database

Use trigger BEFORE INSERT on the table to prevent having a zero value in a MySQL field. Let us first create a table −

mysql> create table DemoTable(Value int);
Query OK, 0 rows affected (0.85 sec)

Let us create a trigger to prevent having a zero value in a MySQL field −

mysql> DELIMITER //
mysql> create trigger preventing_to_insert_zero_value
   before insert on DemoTable
   for each row
   begin
      if(new.Value = 0) then SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'You can not provide 0 value';
   END if;
end
//
Query OK, 0 rows affected (0.34 sec)
mysql> DELIMITER ;

Let us insert 0 value in the table and check the value is going to be inserted or not. It won’t allow −

mysql> insert into DemoTable values(0);
ERROR 1644 (45000): You cannot provide 0 value

So, in the above table, you cannot insert 0 value because of trigger. But, you can insert some other value.

Let us now insert some records in the table using insert command −

mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(-1000);
Query OK, 1 row affected (0.41 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Value |
+-------+
| 10    |
| -1000 |
+-------+
2 rows in set (0.00 sec)
raja
Published on 22-Aug-2019 07:22:24
Advertisements