End of Summer - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Default values
How to auto-generate values in a database
15. INSERT using SEQUENCE

Instruction

Okay. Now let's practice using a sequence. Suppose we've created a database sequence called id_seq. We can use it to insert data into the post table, like this:

INSERT INTO post (id, author_id, title, text, modified_timestamp) VALUES
(NEXTVAL('id_seq'), 4, 'A celebrity''s vacation', 'Lucy, a celebrity, is going to spend lots of time on vacation in Japan.', DEFAULT);

In this query, we use the NEXTVAL function to get the next value generated by our sequence. We put that value in the id column. The start value has been set to 16, and the increment value has been set to 1.

It's your decision when and where to use a sequence. Just remember that it's available when you need to have unique identifiers for columns.

Exercise

The author table uses the same sequence (id_seq) to insert new values in the id column. Insert information for a new author, Lisa Thomas. She has an active account but no photo. Use id_seq to generate an ID number for her.

Stuck? Here's a hint!

Use the following expression:

NEXTVAL('id_seq')