
Default values
How to auto-generate values in a database
10. Auto-generated values


Fantastic! In this section, we'll learn something new: how to auto-generate values in a database. There are a few ways PostgreSQL can auto-generate values. We'll talk about two of them: the serial data type and a sequence object.

But first, let's talk about how a database identifies rows. Each table in a database contains a special column (or group of columns) called the primary key. These columns are usually of the integer data type. Each primary key value must be unique, as it indicates each unique record in the table. Therefore, the primary key column (often named id) usually stores auto-generated numbers; you rarely have to insert values into a primary key column.

This statement ...

INSERT INTO author (first_name, last_name) VALUES
('Anne', 'Barry');

... inserts data into the author table. The id column is not on the list. Why not? Because the id column is automatically generated. When you omit it in the query, id will get a new value generated by the database.


Add a new author, John Summer, to the author table. Don't add the id column to the column list; its value will be automatically generated by the database.