Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I require a mysql field?

Tags:

mysql

field

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)?

like image 948
Xi Vix Avatar asked Jan 13 '15 16:01

Xi Vix


People also ask

How do I make a field required in MySQL?

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".

How do you make a field required in SQL?

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.

How do you define a field in SQL?

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.

How do I add a field to an existing table in MySQL?

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.


1 Answers

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
}
like image 137
Devon Avatar answered Sep 17 '22 15:09

Devon