Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql Column constraint as "not empty" / "required"

Tags:

mysql

Can we specify a column in mysql as "not empty" / "required". The requirement is to ensure that the field never remains blank on any record insertion.

like image 696
dopeddude Avatar asked Jun 26 '14 07:06

dopeddude


People also ask

How do I make a column mandatory in MySQL?

You can set MySQL to strict mode to force valid values. This will reject a query that does not provide a value for a NOT NULL column as well as enforce integrity on all types of columns. Update: MySQL 5.7 and above now have strict mode on by default.

How do I drop NOT NULL constraint in MySQL?

To remove a NOT NULL constraint for a column in MySQL, you use the ALTER TABLE .... MODIFY command and restate the column definition, removing the NOT NULL attribute.


1 Answers

I assume you don't want blank (empty string, as opposed to NULL) values to be allowed in the table either.

Normally, that's what a CHECK constraint for. You do something like

CREATE TABLE
        mytable
        (
        myfield NOT NULL VARCHAR(200),
        CHECK(myfield > '')
        )

However, MySQL parses the constraint but does not enforce it. You are still allowed to insert empty values.

To work around that, create a BEFORE INSERT trigger and raise a signal on an attempt to insert a blank value:

CREATE TRIGGER
        tr_mytable_bi
BEFORE INSERT
ON      mytable
FOR EACH ROW
BEGIN
        IF NEW.myfield = '' THEN
                SIGNAL SQLSTATE '45001' SET MESSAGE_TEXT = 'Blank value on mytable.myfield';
        END IF;
END;

Do the same on BEFORE UPDATE if you want to forbid updates to a blank value as well.

like image 153
Quassnoi Avatar answered Sep 29 '22 23:09

Quassnoi