I was having a discussion with a developer at work on the issue of should a table use default values. Is there a hard and fast rule on this or is it a gray area in best practices?
Default values, in the context of databases, are preset values defined for a column type. Default values are used when many records hold similar data.
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).
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). You can add a default constraint either when creating a table or after the table already exists.
Defaults allow someone to use a thing without having to specify a value for a parameter - in code, or in configuration. They reduce friction between deciding to use something, and actually being able to do so.
My rule: if many records will use that default (at least initially) then I like to use it as a default. For example, an image table for products in an online store might have a default path of images/NoPictureYet.png
. Eventually, those will get replaced, but for batch loads of data where the pictures simply don't exist yet (and maybe most of them never will!), a default makes sense (to me, at least).
If there is no sensible default (such as "first name" in a customer database - I don't want MY name defaulted to "FirstName"), then I make it non-nullable and no default - it's the application's responsibility to ensure that a correct value gets entered.
But no hard and fast rules on this. It all varies a little ;)
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