11

In MySQL compatibility mode, the following SQL succeeds and returns 0:

CREATE TABLE test2 (i INTEGER NOT NULL);
INSERT INTO test2 VALUES (NULL);
SELECT * FROM test2;

It fails as expected in the default mode. It also fails with MySQL 5.5 / InnoDB. Does "MySQL compatibility" actually mean "MyISAM compatibility"?

1
  • MySQL will happily insert 0 if you use INSERT INTO test2 VALUES (NULL), (NULL); - at least in the default sql_mode. I think I also saw it insert 0 with a single value insert, but I can't recall the exact circumstances.
    – user330315
    Nov 18, 2013 at 20:54

2 Answers 2

10

This problem is due to both the way MySQL handles Null values and h2. Basically MySQL converts nulls received to empty string/0 where as in h2 there is clear distinction among all three types.

So, they(h2) have decided to convert the nulls to 0/empty string/current time stamp in MYSQL mode. But since the as per core h2 0/empty string are not nulls, so it inserts the data.

Use org.h2.engine.Mode and modify the variable related to this:

Mode mode = Mode.getInstance("MYSQL");
mode.convertInsertNullToZero = false;

This has worked for me. Thanks to this link.

1
  • do you know how to do this in spring/maven xml? I cant find any doc that shows that :\ Aug 31, 2017 at 16:59
4

From H2: MySQL Compatibility Mode:

When inserting data, if a column is defined to be NOT NULL and NULL is inserted, then a 0 (or empty string, or the current timestamp for timestamp columns) value is used. Usually, this operation is not allowed and an exception is thrown.

The MySQL manual says the following about INSERT, with no distinction between MyISAM or InnoDB:

Inserting NULL into a column that has been declared NOT NULL. For multiple-row INSERT statements [..], the column is set to the implicit default value for the column data type. [..] (For a single-row INSERT, no warning occurs when NULL is inserted into a NOT NULL column. Instead, the statement fails with an error.)

Thus I'm not sure why, or from whence, this choice was made by H2.

1
  • Oops. I guess I looked everywhere except the H2 docs. :-) I love how the MySQL behavior changes, depending on how many rows you insert. I think my best bet is to use the default mode in the future. Thanks for your help! Nov 16, 2013 at 1:12

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.