Mysql Column constraint as "not empty" / "required" - 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.

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.

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

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)

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.

Related

Not null confusion

In phpMyAdmin, as we create table there is not null constraints by default for all fields...and as per my knowledge when we set the constraint to not null...it doesn't allow user to remain field empty which are not null as per this link.....
http://www.techopedia.com/definition/27370/not-null-constraint
now my question is..according to this link, not null means every row of data must contain a value - it cannot be left blank during insert or update operations.....but when i insert data programatically like insert into, i am able to insert data in just two fields and other remains blank although there is not null constraints on that fields ...and still not generates any error....so i don't understand how not null works???
for example, i create table with lets say 5 fields...
create table myTable
(
Column1 int not null,
Column2 int not null,
Column3 int not null,
Column4 int not null,
Column5 int not null,
)
and insert values in just two fields like
"INSERT INTO myTable (column1,column2) VALUES(10,20)";
but other fields i don't give any '' so it takes 0 as value....and still i am able to insert data with no error...how is that possible??
Everything that has the NOT NULL constraint set needs to contain data. If you insert data programmatically and you do not insert data for a NOT NULL cell, then you will get an SQL Error.
e.g. you have this table:
CREATE TABLE test (
id INTEGER PRIMARY_KEY AUTO_INCREMENT,
some_value INTEGER NOT NULL,
some_other_value INTEGER);
Then some_value will contain data in every data set returned, some_other_value may or may not contain data in every data set returned. The only thing to work around this would be this:
CREATE TABLE test (
id INTEGER PRIMARY_KEY AUTO_INCREMENT,
some_value INTEGER NOT NULL DEFAULT 0,
some_other_value INTEGER);
If you now set data programatically and do not set data for some_value, some_value will default to 0 (or to whatever data you set the default to on table creation).
Maybe you can refer to this link:
For multiple-row INSERT statements or INSERT INTO ... SELECT
statements, the column is set to the implicit default value for the
column data type. This is 0 for numeric types, the empty string ('')
for string types, and the “zero” value for date and time types. INSERT
INTO ... SELECT statements are handled the same way as multiple-row
inserts because the server does not examine the result set from the
SELECT to see whether it returns a single row. (For a single-row
INSERT, no warning occurs when NULL is inserted into a NOT NULL
column. Instead, the statement fails with an error.)
If a column definition includes no explicit DEFAULT value and it is defined as "Not Null" then Mysql will automatically assign default value to the column based on datatype. e.g. 0 for integer and "" for varchar
If you create a unique index on a column, the default value will be accepted with the first row but will give an error with subsequent inserts.

How do I let MySQL give me an error when a field is null?

How do I create a table with fields that doesn't accept NULL values.
for example a table.
create table student
(
id_no int(3) unsigned primary key,
fname varchar(30),
lname varchar(30),
age
)
I want that fname and lname will be never empty and give me an error if I don't fill up anything in it. I've tried adding "Not Null" after the data types but It still accepts the record even if fname is not filled up.
Edit :
After a few research and trial, I've come up with a solution. Actually, you are inserting empty strings and they are not NULL. To check for NULL error do:
INSERT INTO `student` ( `fname`,`lname`) VALUES ('john',NULL)
You will get the error :
[Err] 1048 - Column 'lname' cannot be null
To prevent empty string either you have to use triggers, or do the checks on server side programming language to convert empty strings to NULL before performing INSERT query. An example trigger for INSERT is like this :
CREATE TRIGGER avoid_empty_records
BEFORE INSERT ON student
FOR EACH ROW
BEGIN
IF new.fname = '' THEN SET new.fname = NULL ;
END IF;
IF new.lname = '' THEN SET new.lname = NULL ;
END IF;
END;
Now if you try to leave either fname or lname blank, it will show the error below :
Column 'lname' cannot be null
The NOT NULL prevents NULL values, however an empty string is not the same as NULL.
To prevent NULL, you're doing the right thing adding NOT NULL, to prevent empty values you normally use for example a CHECK constraint.
The problem is that MySQL does not actually enforce CHECK constraints, so in this case you're struck with a trigger, something like;
delimiter //
create trigger trg_empty_names before insert on student
for each row
begin
if new.fname = '' OR new.lname= '' then
signal sqlstate '45000'
set message_text = 'MyError: Trying to insert an empty name';
end if;
end
//
An SQLfiddle to test with.

MySQL signal duplicate key error

I have a table, which includes an ENUM field. I would like for a particular value of ENUM to require uniqueness with the reference ID column. So let's say I have this:
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`type` ENUM('single','multi') NOT NULL,
`refid` INT UNSIGNED NOT NULL,
`extra` TEXT,
PRIMARY KEY (`id`)
I want (type,refid) to be a unique key, but only if type is single. This can't be done with conventional keys, so I figured I would use a Trigger to detect insertion of a row, check if type='single', look for a row with type='single' and refid=new.refid, and throw a duplicate entry error if one is found.
I'm using MySQL 5.5, so SIGNAL SQLSTATE is available to me. Can I use this to fire a Duplicate Key error in order to process the ON DUPLICATE KEY UPDATE part of the query, and if so, how?
As an alternative, I could update the row in the Trigger and return a generic error condition, but I think it would be nicer (or at least more intuitive) to have ON DUPLICATE KEY UPDATE work.
REPLACE INTO. Derp! Forgot all about that.
Try below trigger. I am not that good in writing triggers. I have not executed the code below. You can use this as a prototype.
CREATE TRIGGER checkDuplicateEntry
BEFORE INSERT OR UPDATE OF type, ref_id ON employees
DECLARE #duplicateCount INT;
FOR EACH ROW
IF ( new.type <> 'single' )
BEGIN
#duplicateCount = count(*) from yourTableName where type = 'single' AND refid = new.refid
END;
IF ( duplicateCount > 0 )
BEGIN
SIGNAL SQLSTATE VALUE '99999'
SET MESSAGE_TEXT = 'Duplicate Entry';
END

mysql trigger on a null value being inserted

I was wanting a mysql trigger for a specific field. When a NULL value is inserted into this field I would like to replace it with a default value. I know this code is not correct, but it would give you an idea of what I want.
CREATE TABLE IF NOT EXISTS example(
id INT NOT NULL AUTO_INCREMENT,
parent_id INT NOT NULL
);
CREATE TRIGGER insert_parentId_trigger BEFORE INSERT ON example
FOR EACH ROW BEGIN
IF parent_id = NULL THEN
SET parent_id = 0;
END IF
END;
Declare that column with not null default 0 instead of using trigger later.
When mysql is already handling that condition why we need to use trigger here?
You can use alter command to update your definition of your column
ALTER TABLE example MODIFY parent_id INT(11) NOT NULL DEFAULT 0
I agree with the example of a Null be simplistically set to 0, then using a "Default" is fine, but what if you're after a value that's variable and cannot be a Default? For example:
IF `Creator` Is NULL THEN
SET `Creator` = current_user();
END IF
For this type of use case, or something that requires a lookup, you will not be able to use Default.
Besides that Shakti Singh is totally right with the default value, you have to compare NULL values with IS instead of =
It should be IF parent_id IS NULL

MySQL: Constraining a set of columns so at least one is not NULL

I want to have a SQL table with two columns. One is a key into another table, the other holds a string literal. The idea is phone numbers can be entered either exactly (in which case the ID into the phonebook table is used) or as a wildcard (in which the string literal is used).
This means that one column in the table will hold a value, and the other will hold a NULL.
Is it possible to constrain a table in such a way that one column must have a value, and the other must be NULL? If both columns are NULL or both have a value, then the row is invalid.
I have a feeling that MySQL can't do this (as it doesn't seem to have a comprehensive toolbox when it comes to constraints), but it couldn't hurt to ask.
I am not aware of a way to enforce such a constraint.
As a workaround, you may consider to have two different columns: If you have one column for the data - containing the phonebook id or the string literal, and another column for the data type - either 'exact' or 'wildcard' -, you can set a NOT NULL constraint to both columns. One obvious drawback is that you cannot have a FK constraint to the phonebooks table any more.
Ever since GENERATED columns are a thing, this is possible.
CREATE TABLE `test_multiple_not_null` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`idOne` int(11) DEFAULT NULL,
`idTwo` int(11) DEFAULT NULL,
`not_null_constrain` int(11) GENERATED ALWAYS AS (coalesce(`idOne`,`idTwo`)) VIRTUAL NOT NULL,
PRIMARY KEY (`id`)
);
Since every time a row is inserted, the generated column must run to see it if satisfies NOT NULL constrain it will reply with 1048: Column 'not_null_constrain' cannot be null, if it would violate this restriction.
You can make triggers to run on before the insert, to check the values and determine if the insert or update should happen or not. A good example for how to create triggers like this can be found here: https://dba.stackexchange.com/questions/43284/two-nullable-columns-one-required-to-have-value
The following triggers worked for me:
CREATE TRIGGER tgr_OrgFeeOwnerInsert
BEFORE INSERT
ON OrganisationFee
FOR EACH ROW
BEGIN
IF (SELECT ((new.fieldA IS NULL) + (new.fieldB IS NULL) + (new.fieldC IS NULL)) <> 2)
THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'my error message';
END IF;
END;
CREATE TRIGGER tgr_OrgFeeOwnerUpdate
BEFORE UPDATE
ON OrganisationFee
FOR EACH ROW
BEGIN
IF (SELECT ((new.fieldA IS NULL) + (new.fieldB IS NULL) + (new.fieldC IS NULL)) <> 2)
THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'my error message';
END IF;
END;