Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PostgreSQL Creating a Table

PostgreSQL Creating a Table

PostgreSQL uses the CREATE TABLE statement to create database tables.

Syntax

CREATE TABLE The syntax format is as follows:

CREATE TABLE table_name(

   column1 datatype,

   column2 datatype,

   column3 datatype,

   .....

   columnN datatype,

   PRIMARY KEY( 一个或多个列 )

);

CREATE TABLE is a keyword that tells the database system that a data table will be created.

A table name must be unique among the names of other tables, sequences, indexes, views, or foreign tables in the same schema.

CREATE TABLE Creates a new empty table in the current database, owned by the user who issued the command.

Each field in the table has a defined data type, as follows:

Example

The following creates a table named COMPANY table, with the primary key ID,NOT NULL indicates that the field is not allowed to contain 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 create another table, which will be used in later 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 whether the table was created successfully:

runoobdb=# \d

           List of relations

 Schema |    Name    | Type  |  Owner   

--------+------------+-------+----------

 public | company    | table | postgres

 public | department | table | postgres

(2 rows)

\d tablename to view table information:

runoobdb=# \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)