Postgresql Create Table
Postgresql Create Table
A relational database consists of multiple related tables. A table consists of rows and columns.
Tables allow you to store structured data like customers, products, employees, etc.
To create a new table, you use the CREATE TABLE statement. The following illustrates the basic
syntax of the CREATE TABLE statement:
In this syntax:
First, specify the name of the table after the CREATE TABLE keywords.
Second, creating a table that already exists will result in a error. The IF NOT EXISTS option
allows you to create the new table only if it does not exist. When you use the IF NOT
EXISTS option and the table already exists, PostgreSQL issues a notice instead of the error and
skips creating the new table.
Third, specify a comma-separated list of table columns. Each column consists of the column
name, the kind of data that column stores, the length of data, and the column constraint. The
column constraints specify rules that data stored in the column must follow. For example, the
not-null constraint enforces the values in the column cannot be NULL. The column constraints
include not null, unique, primary key, check, foreign key constraints.
Finally, specify the table constraints including primary key, foreign key, and check constraints.
Note that some table constraints can be defined as column constraints like primary key, foreign
key, check, unique constraints.
Constraints
PostgreSQL includes the following column constraints:
The following statement creates the roles table that consists of two
columns: role_id and role_name :
The primary key of the account_roles table consists of two columns: user_id and role_id ,
therefore, we have to define the primary key constraint as a table constraint.
Because the user_id column references to the user_id column in the accounts table, we need to
define a foreign key constraintfor the user_id column:
The role_id column references the role_id column in the roles table, we also need to define a
foreign key constraint for the role_id column.
The following shows the relationship between the accounts , roles , and account_roles tables:
Summary
Use the CREATE TABLE statement to create a new table.
Use the IF NOT EXISTS option to create the new table only if it does not exist.
Apply the primary key, foreign key, not null, unique, and check constraints to columns of a
table.