Open In App

PostgreSQL – CREATE TABLE

In PostgreSQL, the CREATE TABLE clause as the name suggests is used to create new tables.

Syntax:
CREATE TABLE table_name (
    column_name TYPE column_constraint,
    table_constraint table_constraint
) INHERITS existing_table_name;

Let’s analyze the syntax above:



Now let’s jump into an example.

Example:
In this example we will create a new table named account that has the following columns with the corresponding constraints:



The following statement creates the account table:

CREATE TABLE account(
    user_id serial PRIMARY KEY,
    username VARCHAR (50) UNIQUE NOT NULL,
    password VARCHAR (50) NOT NULL,
    email VARCHAR (355) UNIQUE NOT NULL,
    created_on TIMESTAMP NOT NULL,
    last_login TIMESTAMP
);

The below statement creates the role table that consists of two columns: role_id and role_name:

CREATE TABLE role(
    role_id serial PRIMARY KEY,
    role_name VARCHAR (255) UNIQUE NOT NULL
);

The following statement creates the account_roles table that has three columns: user_id, role_id and grant_date:

CREATE TABLE account_role
(
  user_id integer NOT NULL,
  role_id integer NOT NULL,
  grant_date timestamp without time zone,
  PRIMARY KEY (user_id, role_id),
  CONSTRAINT account_role_role_id_fkey FOREIGN KEY (role_id)
      REFERENCES role (role_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT account_role_user_id_fkey FOREIGN KEY (user_id)
      REFERENCES account (user_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
);

Let’s examine the above statement in more detail.
The primary key of the account_role table consists of two columns: user_id and role_id, therefore we have to use the primary key table-level constraint to define the primary key as follows:

PRIMARY KEY (user_id, role_id)

Because the user_id column references to the user_id column in the account table, we need to define a foreign key constraint for the user_id column:

CONSTRAINT account_role_user_id_fkey FOREIGN KEY (user_id)
      REFERENCES account (user_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION

The role_idcolumn references to the role_id column in the role table, we also need to define a foreign key constraint for the role_id column:

CONSTRAINT account_role_role_id_fkey FOREIGN KEY (role_id)
      REFERENCES role (role_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION, 

Output:

Article Tags :