An attempt to update a NOT NULL var char field sets the field to an empty string rather than failing. Is this correct behaviour

StackOverflow https://stackoverflow.com/questions/15093893

  •  15-03-2022
  •  | 
  •  

Question

I would have expected this to fail, but instead it wipes the existing data and replaces it with an empty string. Is this correct behaviour? If it is, is there a work around to force an error instead

Eg

CREATE TABLE testtable 
    (columna VARCHAR(30) NOT NULL,
    columnb VARCHAR(2) NULL,
    columnc VARCHAR(10) NULL);

INSERT INTO testtable (columna, columnb, columnc)
VALUES ('first entry', '1', null),
    ('second entry', '2', null),
    ('third entry', '3', null);

INSERT INTO testtable (columna, columnb, columnc)
VALUES (null, '4', null);

This fails with error Error Code: 1048. Column 'columna' cannot be null which is what I would expect.

However,

UPDATE testtable
SET columna = null WHERE columnb = '2';

replaces contents of columna with an empty string

Select * from testtable;

first entry 1   
            2   
third entry 3   
Was it helpful?

Solution

Have found that this is down to the sql mode. By setting

SET GLOBAL sql_mode = 'TRADITIONAL';

the database now works as I would have expected and rejects invalid values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top