0

I just wanted to know if somebody could explain this.

I was just testing my code and didn't check for empty input fields (I know I have to, but just testing).. In my database table, all the fields are NOT NULL, and I was expecting a exception because I wasn't inserting anything.. But it turns out that MySQL inserts all with blank values, also, from MySQL workbench is the same thing..

Is there a way to prevent this? (From a MySQL perspective)

2
  • Are there default values defined on your schema? Commented Mar 29, 2015 at 17:28
  • I'm fairly sure that MySQL not null property just indicates that the field will never be null, not that it won't be empty. Handling emptiness should be done on the application end. Commented Mar 29, 2015 at 17:45

1 Answer 1

4

This behavior, although atypical, is quite well documented:

Inserting NULL into a column that has been declared NOT NULL. 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.)

So, if you want to get an error, use VALUES() with a single row. Alternatively, define a trigger that does the check.

Why does MySQL work this way? I don't know, to differentiate itself from other databases and prevent ANSI-compatibility? More seriously, I assume that this a question of efficiency, and related to the fact that MySQL does not implement check constraints. The NOT NULL declaration is just an example of a check constraint, and these are not supported.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.