Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Default values
How to auto-generate values in a database
11. SERIAL – explanation

Instruction

Good job! There are a couple of ways to automatically generate numerical values. The first one we're going to talk about is the serial data type, which is mainly used for generating primary key values. Here is how we'd use serial in a CREATE TABLE statement to set up a primary key column named id:

CREATE TABLE tab (
  id SERIAL PRIMARY KEY, 
  ...
);

SERIAL is an integer used to auto-increment. The values start from 1 and are increased by 1, so they will be 1, then 2, then 3, and so on.

For a non primary key column, the relevant column definition will look like this:

CREATE TABLE tab (
  seq SERIAL, 
  ...
);

In the seq column, we did not define this column as a primary key; this means it is an integer with auto-generated values. In this column, the database will generate a value that starts from 1 and increases by 1 (i.e., 1, 2, 3, 4, ...).

Exercise

Click Next exercise to continue.