366

I've got a table that collects forms submitted from our website, but for some reason, when they created the table, they didn't put a timestamp in the table. I want it to enter the exact date and time that the record was entered.

I know it's in there somewhere, but I can't seem to find how to set the default value (like in Access, you use getNow() or Now()) but I don't know where to put it.

1

12 Answers 12

436

For modifying an existing column in an existing table:

ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn
9
  • 2
    @TheQ - Thanks. I get that I change "YourTable" to my table name, but the part I don't understand is the Constraint. What is a constraint and would I modify your code to match the name of my table? Feb 3, 2011 at 15:59
  • @steph - TheQ's answer assumes you are altering an existing column which I don't believe to be the case? See my answer for the code to add a new column with this default constraint. Feb 3, 2011 at 16:02
  • 1
    In order for a column to have a default value, it needs a "default constraint", and this command will add that. You can name the constraint whatever you like, Management Studio usually names them DF_TableName.
    – TheQ
    Feb 3, 2011 at 16:03
  • 1
    @TheQ - That's perfect, I'll try it. You were right, I already have the field, but I wanted to apply the fix to it, not create a new one. Thanks for all your answers! Feb 3, 2011 at 16:06
  • 13
    If you want the UTC timestamp instead of local time, you can use GETUTCDATE() instead of GETDATE()
    – Cocowalla
    Jan 17, 2013 at 11:59
190

This can also be done through the SSMS GUI.

  1. Put your table in design view (Right click on table in object explorer->Design)
  2. Add a column to the table (or click on the column you want to update if it already exists)
  3. In Column Properties, enter (getdate()) in Default Value or Binding field as pictured below

Image of table in design view

3
  • Good question. I would try dateadd(minute, 10, GetDate()) to see if that works.
    – Tony L.
    Mar 8, 2019 at 17:20
  • In sql server design view i tried it, it say value must match one of the items in list! so i made it on back end side
    – shareef
    Mar 9, 2019 at 4:34
  • 3
    I tried this one but I get 0001-01-01T00:00:00 instead of the current date Aug 25, 2020 at 9:38
150

In that table in SQL Server, specify the default value of that column to be CURRENT_TIMESTAMP. The datatype of that column may be datetime or datetime2.

e.g.

Create Table Student
(
  Name varchar(50),
  DateOfAddmission datetime default CURRENT_TIMESTAMP
);
5
  • 1
    This fails with the error message "Unable to convert between [B and TIMESTAMP]". It seems CURRENT_TIMESTAMP is a binary value, not a datetime. Oct 18, 2013 at 12:37
  • TIMESTAMP will give you an input like this : yyyy-mm-dd 00:00:00 UTC; and that can make the DB be so large; i think he meant only the date yyyy-mm-dd; and the default value for it can be set by clicking on "As Defined as" in the normal view of phpmyadmin
    – user3423014
    Apr 21, 2016 at 9:32
  • @Amine, TIMESTAMP is a binary value, typically using 6-8 bytes. The string representation is just that, a representation, just like the database isn't storing integers as strings. (Unless you put the time into a VARCHAR column, and woe be those that try.) Aug 14, 2018 at 1:41
  • 5
    I note that CURRENT_TIMESTAMP returns a datetime value in the computer's local time zone. It should be avoided. Instead use SYSUTCDATETIME which returns a datetime2 in UTC.
    – Dai
    Jul 1, 2019 at 20:34
  • Just to add to the comment from @Dai : DateofAdmission datetime2(7) CONSTRAINT [DEFAULT_Student_DateOfAdmission] DEFAULT (SYSUTCDATETIME()) NOT NULL Aug 8, 2023 at 11:23
36

While the marked answer is correct with:

ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn

You should always be aware of timezones when adding default datetime values in to a column.

Say for example, this datetime value is designed to indicate when a member joined a website and you want it to be displayed back to the user, GETDATE() will give you the server time so could show discrepancies if the user is in a different locale to the server.

If you expect to deal with international users, it is better in some cases to use GETUTCDATE(), which:

Returns the current database system timestamp as a datetime value. The database time zone offset is not included. This value represents the current UTC time (Coordinated Universal Time). This value is derived from the operating system of the computer on which the instance of SQL Server is running.

ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETUTCDATE() FOR YourColumn

When retrieving the values, the front end application/website should transform this value from UTC time to the locale/culture of the user requesting it.

1
  • 1
    Good advice. To add to that, however, Microsoft recommends that you use DateTime2 over DateTime. As such you should use SYSUTCDATETIME to get the UTC date as it has better precision. If you need local server time then you should consider using SYSDATETIMEOFFSET to get the local time and store the offset. In this case use the DateTimeOffset type.
    – scottrudy
    Nov 23, 2020 at 18:14
24

Disallow Nulls on the column and set a default on the column of getdate()

/*Deal with any existing NULLs*/
UPDATE YourTable SET created_date=GETDATE() /*Or some sentinel value 
                                                '19000101' maybe?*/
WHERE created_date IS NULL


/*Disallow NULLs*/
ALTER TABLE YourTable ALTER COLUMN created_date DATE NOT NULL

/*Add default constraint*/
ALTER TABLE YourTable ADD CONSTRAINT
    DF_YourTable_created_date DEFAULT GETDATE() FOR created_date
3
  • How would you alter that to change the existing field "created_date"? Feb 3, 2011 at 16:04
  • @steph - See Edit. My previous answer supposed that this was a new column. You will need to disallow NULLs for the default to work so how do you want pre-existing rows to be treated? Feb 3, 2011 at 16:08
  • 1
    Does a DEFAULT GETDATE() guarantee that a multi-row INSERT will have the same DATE for all inserted rows, or might the GETDATE be evaluated per row? And similarly for SYSDATETIME()?
    – John Rees
    Oct 30, 2020 at 3:23
11

The syntax for this when creating a new table is:

CREATE TABLE MyTable
(
    MYTableID INT IDENTITY(1,1),

    CreateDate DATETIME NOT NULL CONSTRAINT DF_MyTable_CreateDate_GETDATE DEFAULT GETDATE()
)
1
  • It works equally well in an ALTER TABLE statement when adding a new column. Sep 7, 2016 at 8:14
11

This works for me...

ALTER TABLE [accounts] 
 ADD [user_registered] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ;
5

This also works:

CREATE TABLE Example(
...
created datetime default GETDATE()
);

Or:

ALTER TABLE EXAMPLE ADD created datetime default GETDATE();
4

This worked for me. I am using SQL Developer with Oracle DB:

ALTER TABLE YOUR_TABLE
  ADD Date_Created TIMESTAMP  DEFAULT CURRENT_TIMESTAMP NOT NULL;
1

Let's say you create a database table for a registration system.

IF OBJECT_ID('dbo.registration_demo', 'U') IS NOT NULL 
  DROP TABLE dbo.registration_demo; 

CREATE TABLE dbo.registration_demo (
    id INT IDENTITY PRIMARY KEY,
    name NVARCHAR(8)
);

Now a couple people register.

INSERT INTO dbo.registration_demo (name) VALUES
    ('John'),('Jane'),('Jeff');

Then you realize you need a timestamp for when they registered.

If this app is limited to a geographically localized region, then you can use the local server time with GETDATE(). Otherwise you should heed Tanner's consideration for the global audience with GETUTCDATE() for the default value.

Add the column with a default value in one statement like this answer.

ALTER TABLE dbo.registration_demo
ADD time_registered DATETIME DEFAULT GETUTCDATE();

Let's get another registrant and see what the data looks like.

INSERT INTO dbo.registration_demo (name) VALUES
    ('Julia');

SELECT * FROM dbo.registration_demo;
id    name    time_registered
1     John    NULL
2     Jane    NULL
3     Jeff    NULL
4     Julia   2016-06-21 14:32:57.767
1

To make it simpler to follow, I will summarize the above answers:

Let`s say the table is called Customer it has 4 columns/less or more...

you want to add a new column to the table where every time when there is insert... then that column keeps a record of the time the event happened.

Solution:

add a new column, let`s say timepurchase is the new column, to the table with data type datetime.

Then run the following alter:

ALTER TABLE Customer ADD CONSTRAINT DF_Customer DEFAULT GETDATE() FOR timePurchase
0

In SQLPlus while creating a table it is be like as

SQL> create table Test

 ( Test_ID number not null,
   Test_Date date default sysdate not null );

SQL> insert into Test(id) values (1);

 Test_ID Test_Date
       1 08-MAR-19

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