25

Using Transact SQL is there a way to specify a default datetime on a column (in the create table statement) such that the datetime is the minimum possible value for datetime values?

create table atable
(
  atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  Modified datetime DEFAULT XXXXX??????
)

Perhaps I should just leave it null.

7 Answers 7

42

As far as I am aware no function exists to return this, you will have to hard set it.

Attempting to cast from values such as 0 to get a minimum date will default to 01-01-1900.

As suggested previously best left set to NULL (and use ISNULL when reading if you need to), or if you are worried about setting it correctly you could even set a trigger on the table to set your modified date on edits.

If you have your heart set on getting the minimum possible date then:

create table atable
(
  atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  Modified datetime DEFAULT '1753-01-01'
)

19

I agree with the sentiment in "don't use magic values". But I would like to point out that there are times when it's legit to resort to such solutions.

There is a price to pay for setting columns nullable: NULLs are not indexable. A query like "get all records that haven't been modified since the start of 2010" includes those that have never been modified. If we use a nullable column we're thus forced to use [modified] < @cutoffDate OR [modified] IS NULL, and this in turn forces the database engine to perform a table scan, since the nulls are not indexed. And this last can be a problem.

In practice, one should go with NULL if this does not introduce a practical, real-world performance penalty. But it can be difficult to know, unless you have some idea what realistic data volumes are today and will be in the so-called forseeable future. You also need to know if there will be a large proportion of the records that have the special value - if so, there's no point in indexing it anyway.

In short, by deafult/rule of thumb one should go for NULL. But if there's a huge number of records, the data is frequently queried, and only a small proportion of the records have the NULL/special value, there could be significant performance gain for locating records based on this information (provided of course one creates the index!) and IMHO this can at times justify the use of "magic" values.

1
  • I know this is an old question/answer but I feel strongly enough about this that I felt compelled to chime in. NULL is a wonderful thing. However as The Dag pointed out, bad performance wise plus it CAN be nuisance, IMO, to code for as in "WHERE foo IS NULL OR foo < '[a datetime value]'" (<, >, =, <=, >=, <>, BETWEEN take your pick). This is not always the case but often is. As always, it depends on your situation/requirements/data. You MUST know your data to develop a good schema and queries. May 9, 2018 at 15:21
10

"Perhaps I should leave it null"

Don't use magic numbers - it's bad practice - if you don't have a value leave it null

Otherwise if you really want a default date - use one of the other techniques posted to set a default date

4
  • 4
    I would tend to agree. As an aside, do you have an answer to the question?
    – user72491
    Mar 5, 2009 at 16:53
  • 4
    I hate when users attempt to redirect the user instead of answering and -then- trying to redirect.
    – TheTXI
    Mar 5, 2009 at 16:58
  • 1
    "Perhaps I should just leave it null." - I was answering that part
    – DJ.
    Mar 5, 2009 at 17:04
  • Q: has it been modified? A: no, you are inserting the value. I keep a CreatedDate and a ModifiedDate on my data. ModifiedDate is always NULL on insert. It's set by trigger on UPDATE.
    – Quango
    Aug 5, 2010 at 21:22
6

Unless you are doing a DB to track historical times more than a century ago, using

Modified datetime DEFAULT ((0)) 

is perfectly safe and sound and allows more elegant queries than '1753-01-01' and more efficient queries than NULL.

However, since first Modified datetime is the time at which the record was inserted, you can use:

Modified datetime NOT NULL DEFAULT (GETUTCDATE())

which avoids the whole issue and makes your inserts easier and safer - as in you don't insert it at all and SQL does the housework :-)

With that in place you can still have elegant and fast queries by using 0 as a practical minimum since it's guranteed to always be lower than any insert-generated GETUTCDATE().

4

Sometimes you inherit brittle code that is already expecting magic values in a lot of places. Everyone is correct, you should use NULL if possible. However, as a shortcut to make sure every reference to that value is the same, I like to put "constants" (for lack of a better name) in SQL in a scaler function and then call that function when I need the value. That way if I ever want to update them all to be something else, I can do so easily. Or if I want to change the default value moving forward, I only have one place to update it.

The following code creates the function and a table using it for the default DateTime value. Then inserts and select from the table without specifying the value for Modified. Then cleans up after itself. I hope this helps.

-- CREATE FUNCTION
CREATE FUNCTION dbo.DateTime_MinValue ( )
RETURNS DATETIME
AS 
    BEGIN
        DECLARE @dateTime_min DATETIME ;
        SET @dateTime_min = '1/1/1753 12:00:00 AM'
        RETURN @dateTime_min ;
    END ;
GO


-- CREATE TABLE USING FUNCTION FOR DEFAULT
CREATE TABLE TestTable
(
  TestTableId INT IDENTITY(1, 1)
                  PRIMARY KEY CLUSTERED ,
  Value VARCHAR(50) ,
  Modified DATETIME DEFAULT dbo.DateTime_MinValue()
) ;


-- INSERT VALUE INTO TABLE
INSERT  INTO TestTable
        ( Value )
VALUES  ( 'Value' ) ;


-- SELECT FROM TABLE
SELECT  TestTableId ,
        VALUE ,
        Modified
FROM    TestTable ;


-- CLEANUP YOUR DB
DROP TABLE TestTable ;
DROP FUNCTION dbo.DateTime_MinValue ;
0

I think your only option here is a constant. With that said - don't use it - stick with nulls instead of bogus dates.

create table atable
(
  atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  Modified datetime DEFAULT '1/1/1753'
)
0

I think this would work...

create table atable
(
  atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  Modified datetime DEFAULT ((0))
)

Edit: This is wrong...The minimum SQL DateTime Value is 1/1/1753. My solution provides a datetime = 1/1/1900 00:00:00. Other answers have the correct minimum date...

5
  • +1. Doing WHERE Modified = 0 is SARGable, WHERE Modified IS NULL isn't.
    – Tomalak
    Mar 5, 2009 at 17:05
  • 1
    this won't work - 0 is '1/1/1900'. -53690 would give you the value of '1/1/1753'.
    – Scott Ivey
    Mar 5, 2009 at 17:11
  • Hm. Maybe I don't get it, but what's '1/1/1753'? And why won't '1/1/1900' work?
    – Tomalak
    Mar 5, 2009 at 17:24
  • 2
    1/1/1900 would work, but is just not the minimum, which is what OP was after. 1/1/1753 is the last date before the calendar goes nuts (with diff calendars adopted). there are methods for storing dates, but not using DateTime. I think SQL08 introduced a new type (DateTime2?) that handles it
    – Chris
    Mar 5, 2009 at 21:06
  • @Tomalak: 1/1/1753 is the minimum value for the datetime type. For a column indicating when something was last modified NULL is the logical choice to represent "never". But if one does resort to "magic values" (i.e. using some values to mean something other than the normal meaning of the same value, here saying "1/1/1753 means NEVER") the minimum value is a logical choice here.
    – The Dag
    Mar 7, 2011 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.