PostgreSQL Create Table
PostgreSQL uses the CREATE TABLE statement to create database tables.
Syntax
CREATE TABLEThe syntax format is as follows:
CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype, ..... columnN datatype, PRIMARY KEY( 一个或多个列 ) );
CREATE TABLEis a keyword used to tell the database system that a data table will be created.
The table name must be unique among other tables, sequences, indexes, views, or foreign table names in the same schema.
CREATE TABLECreates a new empty table in the current database; the table will be owned by the user issuing this command.
Each field in the table defines a data type, as follows:
Example
The following creates a table with the table nameCOMPANYtable, with the primary key beingID,NOT NULLindicates that the field does not allowNULLvalue:
CREATE TABLE COMPANY( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL );
Next, let's create another table that 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\dcommand to check whether the table was created successfully:
exampledb=# \d
List of relations
Schema | Name | Type | Owner
--------+------------+-------+----------
public | company | table | postgres
public | department | table | postgres
(2 rows)
\d tablenameView table information:
exampledb=# \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)
Other extensions