6

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.

dopeddude
  • 4,943
  • 3
  • 33
  • 41

4 Answers4

9

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.

Quassnoi
  • 413,100
  • 91
  • 616
  • 614
6

MySQL8 now has value constraints, which allows you to implement value restrictions without using triggers

For example:

CREATE TABLE my_table (
    myfield VARCHAR(255) NOT NULL
        CONSTRAINT myfield_not_empty CHECK(
            LENGTH(myfield) > 0 
        )
);

Will ensure the values in myfield will never be empty

ARitz Cracker
  • 77
  • 1
  • 4
2

Use NOT NULL.

It causes input to be required.
But a field to be not empty you need validation script explicitly.

Example:

create table example(
  login_name varchar(16) not null
  pass_word varchar(32) not null
);

Refer to: Wiki on Null (SQL)

Ravinder Reddy
  • 23,692
  • 6
  • 52
  • 82
  • I have used "NOT NULL" but still the insert command runs fine and a row is inserted in the table(using sqlyog). But doing same through the command line terminal throws an error(as desired). I am not sure if this is due to the mode difference between the twos. – dopeddude Jun 26 '14 at 09:09
-1

You can define the column as NOT NULL as answered by @Ravinder

In addition to it you can set a default value to a column. If we take the example of previous answer, we can do it as below:

create table example( login_name varchar(16) = null pass_word varchar(32) = null );

Here if no value is received for these columns then NULL will be inserted by default.

Shivam Gupta
  • 429
  • 4
  • 16
  • That is an invalid `create table` statement. What is `= NULL` supposed to do? –  Jun 26 '14 at 07:56
  • @a_horse_with_no_name: Yes, mybad. I declared here the syntax of a stored procedure where we want to set a default value for a column of a table. – Shivam Gupta Jun 27 '14 at 03:46