Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a database table have default values?

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?

like image 529
Todd Moses Avatar asked Feb 17 '10 21:02

Todd Moses


People also ask

What is a default value on a database table?

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.

Why would you use default values in column?

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

When would you want a default value SQL?

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.

Why are default values used?

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.


1 Answers

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

like image 70
FrustratedWithFormsDesigner Avatar answered Sep 18 '22 12:09

FrustratedWithFormsDesigner