PostgreSQL Create Table
PostgreSQL uses the CREATE TABLE statement to create database tables.
Syntax
The CREATE TABLE syntax 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 foreign tables in the same schema.
CREATE TABLE creates a new, empty table in the current database, which 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 named COMPANY with the primary key ID, and NOT NULL indicates that the field must not contain NULL values:
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 that will be used in later sections:
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 tables were created successfully:
tutorialprodb=# \d
List of relations
Schema | Name | Type | Owner
--------+------------+-------+----------
public | company | table | postgres
public | department | table | postgres
(2 rows)
To view table information, use \d tablename
:
tutorialprodb=# \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)