End of Summer - 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

Instruction

DEFAULT is often used for date and time columns. A very common situation is to use the current date and time for the default value. In PostgreSQL, you use the function CURRENT_TIMESTAMP to get the current date and time.

The create_timestamp column of the author table has a default value of CURRENT_TIMESTAMP. This statement ...

INSERT INTO author (id, last_name, photo, create_timestamp) VALUES
(7, 'Smith', 'imgs/Smith2.jpg', DEFAULT);

... inserts a row where the create_timestamp column is given the current date and time – i.e. the date and time when the record was inserted. Here is the result:

id first_name last_name photo create_timestamp is_active
7 NULL Smith imgs/Smith2.jpg 2018-10-12 10:02:20.1237862 false

Notice that the first name is not given in this query. The value for first_name 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.