If you are explicitly setting the value to NULL in your insert, but want MySQL to replace the NULL with 0, one way to do that is to define the column to allow NULL in the CREATE TABLE statement, and then replace the NULL with a TRIGGER.

Something like this:

CREATE TABLE `listings` (
  `ListingID` int(11) NOT NULL,
  `BathsFull` int(6) NULL DEFAULT 0,
  PRIMARY KEY (`ListingID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

delimiter $$

create trigger tr_b_ins_listings before insert on listings for each row
begin
  set new.BathsFull = coalesce(new.BathsFull,0);
end $$

delimiter ;

Try it for yourself in this SQL Fiddle

Answer from Ike Walker on Stack Overflow
๐ŸŒ
PopSQL
popsql.com โ€บ learn-sql โ€บ mysql โ€บ how-to-add-a-not-null-constraint-in-mysql
How to Add a Not Null Constraint in MySQL
mysql> SHOW CREATE TABLE products\G *************************** 1. row *************************** Table: products Create Table: CREATE TABLE `products` ( `product_id` bigint(20) NOT NULL, `product_name` varchar(100) DEFAULT '', `stocks` int(11) DEFAULT '0', (The rest of the output is truncated for brevity)
Discussions

mysql - Field both NOT NULL and DEFAULT NULL - Database Administrators Stack Exchange
This MySQL table had me perplexed for a moment: mysql> desc quux; +---------------------------+-----------------------+------+-----+---------+----------------+ | Field | Typ... More on dba.stackexchange.com
๐ŸŒ dba.stackexchange.com
November 23, 2016
mysql - What is the default value for a field if no default value is provided? - Stack Overflow
CREATE TABLE Books ( ID SMALLINT ... DEFAULT 0 ) It's good practice to declare ALL columns "not null", and provide default constraints as appropriate. In the "books" example above, if you "insert" without specifying PubID, the PubID will be zero. In the same example, if you "insert" without specifying ID or Name ... you'll get an error. If you want MySQL to auto-assign ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
VARCHAR/CHAR.. column NOT NULLABLE but DEFAULT NULL may should show Default NULL(not blank) in table structure view
In SQL, DEFAULT NULL is different from "", even column NOT NULLABLE: mysql> INSERT INTO `test`.`test` (`id`, `name`, `type`) value (1, DEFAULT, "TYPE"); ERROR 1364 (HY000): Field 'name' doesn't have a default value mysql> INSERT INTO `test`.`test` (`id`, `name`, `type`) value (1, "NAME", DEFAULT); Query OK, 1 row affected (0... More on github.com
๐ŸŒ github.com
12
March 14, 2022
Mysql: Unable to drop a columns NULL default - Database Administrators Stack Exchange
What?? I would expect 2 or 4 Warnings, not 3. mysql> SELECT * FROM t; +------+----+------+------+ | n | nn | ndn | nndn | +------+----+------+------+ | 11 | 22 | 33 | 44 | | NULL | 77 | NULL | 777 | | NULL | 0 | NULL | 0 | -- So, as if "DEFAULT 0" +------+----+------+------+ More on dba.stackexchange.com
๐ŸŒ dba.stackexchange.com
February 12, 2019
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ adding-a-column-whose-value-is-not-null-by-default-in-mysql
Adding a column whose value is not null by default in MySQL?
Here is the query to add a column whose value is NOT NULL by default: mysql> alter table AddingColumnDefaultValueNOTNULL add column City varchar(20) NOT NULL after Age; Query OK, 0 rows affected (2.17 sec) Records: 0 Duplicates: 0 Warnings: 0
Top answer
1 of 3
30

Referring to the manual,

For data entry for a NOT NULL column that has no explicit DEFAULT clause, if an INSERT or REPLACE statement includes no value for the column, or an UPDATE statement sets the column to NULL, MySQL handles the column according to the SQL mode in effect at the time:

  • If strict SQL mode is not enabled, MySQL sets the column to the implicit default value for the column data type.
  • If strict mode is enabled, an error occurs for transactional tables and the statement is rolled back. For nontransactional tables, an
    error occurs, but if this happens for the second or subsequent row of a multiple-row statement, the preceding rows will have been inserted.

So your question now may be, what are the implicit default values for the various column data types? Here you go:

Implicit defaults are defined as follows:

  • For numeric types, the default is 0, with the exception that for integer or floating-point types declared with the AUTO_INCREMENT
    attribute, the default is the next value in the sequence.
  • For date and time types other than TIMESTAMP, the default is the appropriate โ€œzeroโ€ value for the type. For the first TIMESTAMP column in a table, the default value is the current date and time. See Section 10.3, โ€œDate and Time Typesโ€.
  • For string types other than ENUM, the default value is the empty string. For ENUM, the default is the first enumeration value.
2 of 3
0

There IS no default value unless you specify one (i.e. unless you define a "default constraint" for the column in question).

Here's an example for adding a default on an existing column:

ALTER TABLE dbo.customer ALTER COLUMN contactname SET DEFAULT 'Unknown'

Here's an example creating the table with a default:

CREATE TABLE Books (
  ID SMALLINT NOT NULL,
  Name VARCHAR(40) NOT NULL,
  PubID SMALLINT NOT NULL DEFAULT 0
)

It's good practice to declare ALL columns "not null", and provide default constraints as appropriate.

In the "books" example above, if you "insert" without specifying PubID, the PubID will be zero.

In the same example, if you "insert" without specifying ID or Name ... you'll get an error.

If you want MySQL to auto-assign an ID, use this syntax instead:

CREATE TABLE Books (
  ID SMALLINT NOT NULL AUTO_INCREMENT,
  Name VARCHAR(40) NOT NULL,
  PubID SMALLINT NOT NULL DEFAULT 0
)
๐ŸŒ
GitHub
github.com โ€บ Sequel-Ace โ€บ Sequel-Ace โ€บ issues โ€บ 1419
VARCHAR/CHAR.. column NOT NULLABLE but DEFAULT NULL may should show Default NULL(not blank) in table structure view ยท Issue #1419 ยท Sequel-Ace/Sequel-Ace
March 14, 2022 - In SQL, DEFAULT NULL is different from "", even column NOT NULLABLE: mysql> INSERT INTO `test`.`test` (`id`, `name`, `type`) value (1, DEFAULT, "TYPE"); ERROR 1364 (HY000): Field 'name' doesn't have a default value mysql> INSERT INTO `test`.`test` (`id`, `name`, `type`) value (1, "NAME", DEFAULT); Query OK, 1 row affected (0...
Author ย  mrrao
Find elsewhere
๐ŸŒ
MySQL
bugs.mysql.com โ€บ bug.php
MySQL Bugs: #92553: Default Value in the table column is Null when column is set as Not NULL.
September 25, 2018 - Description: I created a table with columns as NOT NULL, by default MySQL set those columns default value as NULL and then the entries are also stored in the table with null values. How to repeat: Create table with columns as NOT NULL and then try to insert a record with default values.
๐ŸŒ
Stack Exchange
dba.stackexchange.com โ€บ questions โ€บ 229558 โ€บ mysql-unable-to-drop-a-columns-null-default
Mysql: Unable to drop a columns NULL default - Database Administrators Stack Exchange
February 12, 2019 - mysql> CREATE TEMPORARY TABLE t ( n INT NULL, nn INT NOT NULL, ndn INT NULL DEFAULT NULL, nndn INT NOT NULL DEFAULT 0 -- (does not allow DEFAULT NULL) ); mysql> DESCRIBE t; +-------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+-------+ | n | int(11) | YES | | NULL | | | nn | int(11) | NO | | NULL | | | ndn | int(11) | YES | | NULL | | | nndn | int(11) | NO | | 0 | | +-------+---------+------+-----+---------+-------+ mysql> SHOW CREATE TABLE t\G *************************** 1.
๐ŸŒ
MySQL
dev.mysql.com โ€บ doc โ€บ refman โ€บ 8.0 โ€บ en โ€บ data-type-defaults.html
MySQL :: MySQL 8.0 Reference Manual :: 13.6 Data Type Default Values
May 20, 2022 - CREATE TABLE t1 ( i INT DEFAULT -1, c VARCHAR(10) DEFAULT '', price DOUBLE(16,2) DEFAULT 0.00 ); SERIAL DEFAULT VALUE is a special case. In the definition of an integer column, it is an alias for NOT NULL AUTO_INCREMENT UNIQUE.
Top answer
1 of 2
4

The answer is to use the following (slightly odd) syntax:

ALTER TABLE items ALTER ordering DROP DEFAULT;
2 of 2
2

When trying to modify a column with ALTER TABLE, there are 4 keywords that can be used, each with different capabilities:

  • CHANGE [COLUMN]
  • MODIFY [COLUMN]
  • RENAME COLUMN
  • ALTER [COLUMN]

CHANGE is a MySQL extension to standard SQL. MODIFY and RENAME COLUMN are MySQL extensions for Oracle compatibility.

ALTER [COLUMN] is standard SQL (I think).

The docs about ALTER TABLE have more details:

Renaming, Redefining, and Reordering Columns

The CHANGE, MODIFY, RENAME COLUMN, and ALTER clauses enable the names and definitions of existing columns to be altered. They have these comparative characteristics:

  • CHANGE:

    • Can rename a column and change its definition, or both.
    • Has more capability than MODIFY or RENAME COLUMN, but at the expense of convenience for some operations. CHANGE requires naming the column twice if not renaming it, and requires respecifying the column definition if only renaming it.
    • With FIRST or AFTER, can reorder columns.
  • MODIFY:

    • Can change a column definition but not its name.
    • More convenient than CHANGE to change a column definition without renaming it.
    • With FIRST or AFTER, can reorder columns.
  • RENAME COLUMN:

    • Can change a column name but not its definition.
    • More convenient than CHANGE to rename a column without changing its definition.
  • ALTER:

    • Used only to change a column default value.

In this case, you have 3 options:

ALTER TABLE items
    CHANGE ordering ordering int NOT NULL;

ALTER TABLE items 
    MODIFY ordering int NOT NULL;

ALTER TABLE items
    ALTER ordering DROP DEFAULT ;
๐ŸŒ
W3Schools
w3schools.com โ€บ mysql โ€บ mysql_notnull.asp
MySQL NOT NULL Constraint
This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field. By default, a column can hold NULL values.
๐ŸŒ
Webmaster World
webmasterworld.com โ€บ databases_sql_mysql โ€บ 4943726.htm
MySQL: default none or null? - Databases forum at WebmasterWorld - WebmasterWorld
From my experience, every fraction of a second that I can save on a page load results in an increase of pages per session, so saving 100ms on a few queries could have a significant long term financial impact. As for coding, after playing around today it looks like I can leave it as NOT NULL and default to None, and then:
๐ŸŒ
Reddit
reddit.com โ€บ r/mysql โ€บ default values for different data types in 'strict mode'
r/mysql on Reddit: Default Values for different data types in 'strict mode'
May 26, 2022 -

I've been developing PHP / MySQL web based applications for 15 years (hand coded. no frameworks) and only this week, have I discovered 'strict mode' when the Host that I host most of my apps on ran updates overnight and MySQL is now in strict mode on their servers. (rude shock in the morning)

I've always had no default value for my table columns and set to not nullable and MySQL has taken care of the INSERT when the value was not supplied.

Now with many apps broken, I am frantically going through all the tables in my apps, adding default values, adding '0' for INTEGER and '1970-01-01' for DATE (and updating my display code to test for '1970-01-01' instead of testing for '0000-00-00').

My question is what to do for VARCHAR and TEXT columns. Should I have an empty string as the default, or should I make them nullable? I've been searching the internet since yesterday with most advice (from years ago with the upgrade to 5.7) and most of what I find just suggests to turn strict mode off again. This is not a viable solution.

If I choose NULL I will have to update some display code that tests for empty string, but is choosing empty string as a default, a safe and viable option?

Any advice on these two options or other alternatives would be greatly appreciated. Cheers.

Top answer
1 of 2
4

Are you using a framework where objects are automatically converted into SQL statements for saving? If the value of the property in your PHP class is not set and the column is nullable then it will insert null instead of 0.

Consider:

class Foo{
    protected $propertyName;
}

That is equivalent in PHP to

class Foo{
    protected $propertyName = null;
}

If the TINYINT(4) column for propertyName is nullable when it builds the query to save the data it will save as null in the database. If you are using a design pattern like this you need set the default value in the PHP class itself. Something like

class Foo{
    protected $propertyName = 0;
}

Note, if the column is not null-able then saving the object would throw an error in this scenario. If you wanted to get fancy, you can fetch the default values for a column using

DESC tableName;

That will return information about the table, there will be a column NULL which will be YES or NO (describing if the column is null-able). And a column Default which will be the default value (or NULL if there is none). You could then populate null fields in your class based on the default values from the database. You would want to be careful here as there are likely some columns that should be NULL. Ideally, you would make any fields that can't accept null non-nullable and then key your logic for handling defaults only fire when the Null column is NO.

2 of 2
0

When inserting a new row, the default value for a column with an expression default can be inserted either by omitting the column name or by specifying the column as DEFAULT (just as for columns with literal defaults).
source: https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html

In case you specify NULL for the column on INSERT MySQL try to set the NULL for the column (and fails in case of NOT NULL). You have to ommit the column on INSERT or using DEFAULT as value on the INSERT statement.

See the following example:

CREATE TABLE test (
 col1 INT DEFAULT 0 NOT NULL,
 col2 INT DEFAULT 0 NULL,
 col3 INT NULL
);

-- doesn't work since col1 can't be NULL
INSERT INTO test VALUES (NULL, NULL, NULL)

-- is working: col1 is 0 after INSERT, col2 IS NULL
INSERT INTO test (col2, col3) VALUES (NULL, NULL)

-- is working: col1 is 0 after INSERT, col2 IS 0 - because using DEFAULT instead of NULL.
INSERT INTO test (col2, col3) VALUES (DEFAULT, NULL)
๐ŸŒ
Peachpit
peachpit.com โ€บ articles โ€บ article.aspx
NULL and Default Values | MySQL Database Design | Peachpit
Ideally, every record in a database should have value, but that is rarely the case in practicality. To enforce this limitation on a field, you add the NOT NULL description to its column type. For example, a primary key might now be described as client_id SMALLINT(3) UNSIGNED NOT NULL and Default Values NULL