I need to limit the number of rows can be insert in a MySQL Table to 10 only. I need to implement this from MySQL only i.e without using any programming lan
I think there is no such inbuilt functionality providede by MySQL. One solution is that you can create trigger.
CREATE TRIGGER your_trigger_name
BEFORE INSERT ON your_table_name
FOR EACH ROW
BEGIN
DECLARE cnt INT;
SELECT count(*) INTO cnt FROM your_table_name;
IF cnt = 10 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'You can store only 10 records.';
END IF;
END;
Try above trigger on your table. Replace your table_name with your_table_name.
Hope this will help you.
As check constraint does not seems to work with MySql. You can try creating a BEFORE INSERT TRIGGER
on your table and set NEW.column
value as NULL
for some not nullable column to break the insert statement.
Ex:
CREATE TABLE mytable (
id INT NOT NULL,
col1 VARCHAR(255) NOT NULL,
col2 VARCHAR(255),
);
DELIMITER $$
CREATE TRIGGER mytable_before_trig BEFORE INSERT ON mytable
FOR EACH ROW
BEGIN
IF (SELECT COUNT(id) FROM mytable) > 3 THEN
SET NEW.id = NULL;
END IF;
END;
$$
Now try to insert records in mytable, it will ignore 4th records by throwing an error.
Here's one idea...:
CREATE TABLE my_table
(id int auto_increment PRIMARY KEY
,val char(1) NOT NULL
);
INSERT INTO my_table (val) SELECT 'b' FROM (SELECT 1) x WHERE (SELECT COUNT(*) FROM my_table) < 5;
Query OK, 1 row affected (0.02 sec)
INSERT INTO my_table (val) SELECT 'b' FROM (SELECT 1) x WHERE (SELECT COUNT(*) FROM my_table) < 5;
Query OK, 1 row affected (0.02 sec)
INSERT INTO my_table (val) SELECT 'b' FROM (SELECT 1) x WHERE (SELECT COUNT(*) FROM my_table) < 5;
Query OK, 1 row affected (0.02 sec)
INSERT INTO my_table (val) SELECT 'b' FROM (SELECT 1) x WHERE (SELECT COUNT(*) FROM my_table) < 5;
Query OK, 1 row affected (0.02 sec)
INSERT INTO my_table (val) SELECT 'b' FROM (SELECT 1) x WHERE (SELECT COUNT(*) FROM my_table) < 5;
Query OK, 1 row affected (0.02 sec)
INSERT INTO my_table (val) SELECT 'b' FROM (SELECT 1) x WHERE (SELECT COUNT(*) FROM my_table) < 5;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
INSERT INTO my_table (val) SELECT 'b' FROM (SELECT 1) x WHERE (SELECT COUNT(*) FROM my_table) < 5;
Query OK, 0 rows affected (0.00 sec)
SELECT * FROM my_table;
+----+-----+
| id | val |
+----+-----+
| 1 | b |
| 2 | b |
| 3 | b |
| 4 | b |
| 5 | b |
+----+-----+