Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column Nullability/Optionality: NULL vs NOT NULL

Is there a reason for or against setting some fields as NULL or NOT NULL in a mysql table, apart from primary/foreign key fields?

like image 269
Tom Avatar asked May 15 '26 14:05

Tom


2 Answers

That completely depends on your domain to be honest. Functionally it makes little difference to the database engine, but if you're looking to have a well defined domain it is often best to have both the database and application layer mirror the requirements you are placing on the user.

If it's moot to you whether or not the user enters their "Display Name", then by all means mark the column as nullable. On the other hand, if you are going to require a "Display Name" you should mark it non null in the database as well as enforcing the constraint in the application. By doubling the constraint, you ensure that should your front-end change, the domain is still fully qualified.

like image 136
Nathan Taylor Avatar answered May 18 '26 03:05

Nathan Taylor


MySQL has a NOT NULL condition on a field, but this will not stop you from inserting "empty" data. There is no way to flag a field as "required".

As Pekka mentioned, you should be doing some sort of validation to prevent this at a higher level in your application.

like image 35
pix0r Avatar answered May 18 '26 04:05

pix0r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!