I just discovered NOT NULL does not make a field required.
When creating a mysql table, how do I create a field that cannot contain null or blank (must have something in it)?
NOT NULL does make a field "required" in the sense that it needs to have a value stored. NULL means "no value". According to MySQL, a blank string is still a "value".
In the Navigation Pane, right-click the table and then click Design View. Select the field that you want to require always has a value. In the Field Properties pane, on the General tab, set the Required property to Yes.
Records and Fields in SQL Tables contain rows and columns, where the rows are known as records and the columns are known as fields. A column is a set of data values of a particular type (like numbers or alphabets), one value for each row of the database, for example, Age, Student_ID, or Student_Name.
Syntax. The syntax to add a column in a table in MySQL (using the ALTER TABLE statement) is: ALTER TABLE table_name ADD new_column_name column_definition [ FIRST | AFTER column_name ]; table_name.
By default, MySQL accepts invalid values. You can set MySQL to strict mode to force valid values. This will reject a query that does not provide a value for a NOT NULL column as well as enforce integrity on all types of columns.
Update: MySQL 5.7 and above now have strict mode on by default. So it would not accept invalid values by default like previous versions.
http://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sql-mode-important
http://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_strict_all_tables
Edit:
@Barranka and @RocketHazmat made good points in the comments. ''
is not the same as null, so MySQL will allow that in a NOT NULL column. In that instance, you would have to resort to your code or a trigger.
In the code (PHP for example), this could be easy enough, running something like:
if (!strlen($value)) {
// Exclude value or use NULL in query
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With