Is it best practice to always have default values on MySQL columns?
Does this improve performance?
I have set my columns to be NOT NULL
but have not specified a default value.
Is this bad practice?
A default value makes it a lot easier to insert new rows into a table - all columns with a default value do not need to be explicitly specified and provided with a value in the INSERT statement, if that default value is OK (like getdate() for a "LastChangeOn" date column).
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.
The default value is used for the column's value when one is not specified (for example, when you insert a row into the table without specifying a value for the column).
Explanation: NULL is the default value as it stands for “Absence of value”.
Is it best practice to always have default values on mysql columns?
NO
It really depends.
If you want to ensure that sensible data is input, then you should not set a default value for a not null
column.
Only set default values for columns that have a sensible default value.
If you can get away with null
just allow null
.
Does this improve performance?
It slows down your inserts ever so slightly.
But may it speed up your selects, because you don't have to test for null.
Of course the DB spends a small amount of time to setting the default values.
Unless you're inserting in bulk it's very unlikely you'll notice any delay.
Performance
Inserts Theoretically, it should be faster to use default values instead of sending every all values. In fact the performance difference is so small, you can not measure it.
In general: Using NOT NULL is faster than working with NULL values. Specially index structures work faster if they do not have to handle the Null values.
If you use NOT NULL use Default value
Best Practice
In real world you should do, what you desire to have as an outcome.
Use DEFAULT value, if you don't care if you know the real value, but you want to make sure that at least a default value is present.
If you use NOT NULL always use DEFAULT.
Examples
Birthday: Do use NULL values for those users, you don't know the birthday.
isDisabled: Do not use NULL, instead set default to 0; so if there is nothing set, the User is not disabled. You decide, so you don't need NULL.
If your specifying it as NOT NULL then yes you should have a default value unless your controlling what data is inputted. NOT NULL implies there will always be a value so having a default value is good practice. Do all of your columns need to be NOT NULL?
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