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.
4 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.

- 413,100
- 91
- 616
- 614
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

- 77
- 1
- 4
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)

- 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
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.

- 429
- 4
- 16
-
-
@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