Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Default values
8. Using DEFAULT for the current date and time
How to auto-generate values in a database
Summary

Instruction

Okay. DEFAULT is often used for date and time columns, and a very common situation is to use the current date and time for the default value. In SQL Server, you use the function GETDATE() to get the current date and time.

The CreateDateTime column of the Author table has a default value of GETDATE(). This statement

INSERT INTO Author (Id, LastName, Photo, CreateDateTime)
VALUES (7, N'Smith', N'imgs/Smith2.jpg', DEFAULT);

inserts a row with the CreateDateTime column with the current date and time (i.e., the date and time of when the record was inserted). Here is the result:

Id FirstName LastName Photo CreateDateTime IsActive
7 NULL Smith imgs/Smith2.jpg 2018-10-12 10:02:20.1237862 true

Notice that the first name is not given in this query. The value for FirstName is NULL because there is no DEFAULT value for this column.

Exercise

The author with ID of 7 wrote his first short post:

'Our company sold about 23 percent more magazines this year than it did 2 years ago.'

The title is

'Increased magazine sales'

and the post ID is 5. Insert this data into the post table using the default date, which is the current date and time.

Stuck? Here's a hint!

You need to put a DEFAULT in the last VALUES argument.
Remember about the dot at the end of the short post.