English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Create a Table in PostgreSQL

PostgreSQL uses the CREATE TABLE statement to create a database table.

Syntax

CREATE TABLE The syntax format is as follows:

CREATE TABLE table_name(
   column1 datatype,
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype,
   PRIMARY KEY( one or more columns )
);

CREATE TABLE Is a keyword used to inform the database system that a data table will be created.

The table name must be unique among other tables, sequences, indexes, views, or external tables in the same schema.

CREATE TABLE Create a new empty table in the current database, which will be owned by the user who issued this command.

Each field in the table will define a data type, as follows:

Online Example

The following creates a table named COMPANY The table, the primary key is ID,NOT NULL Indicates that the field does not allow NULL Value:

CREATE TABLE COMPANY(
   ID INT PRIMARY KEY     NOT NULL,
   NAME           TEXT    NOT NULL,
   AGE            INT     NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);

Next, we will create another table, which will be used in the following chapters:

CREATE TABLE DEPARTMENT(
   ID INT PRIMARY KEY      NOT NULL,
   DEPT           CHAR(50) NOT NULL,
   EMP_ID         INT      NOT NULL
);

We can use the \d command to check if the table has been created successfully:

w3codeboxdb=# \d
           List of relations
 Schema |    Name    | Type  |  Owner   
--------+------------+-------+----------
 public | company    | table | postgres
 public | department | table | postgres
(2 rows)

\d tablename View table information:

w3codeboxdb=# \d company
                  Table "public.company"
 Column  |     Type      | Collation | Nullable | Default 
---------+---------------+-----------+----------+---------
 id      | integer       |           | not null | 
 name    | text          |           | not null | 
 age     | integer       |           | not null | 
 address | character(50) |           |          | 
 salary  | real          |            |          | 
Indexes:
    "company_pkey" PRIMARY KEY, btree (id)