Postgresql Create Table
# PostgreSQL Create Table
PostgreSQL uses the CREATE TABLE statement to create a database table.
### 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 that tells the database system to create a new table.
The table name must be unique among other tables, sequences, indexes, views, or foreign tables within the same schema.
**CREATE TABLE** creates a new empty table in the current database. The table will be owned by the user who issues this command.
Each field in the table is defined with a data type, as shown below:
### Example
The following creates a table named **COMPANY** with **ID** as the primary key. **NOT NULL** indicates that the field cannot 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 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 was created successfully:
tutorialdb=# d List of relations Schema | Name | Type | Owner --------+------------+-------+---------- public | company | table | postgres public | department | table | postgres (2 rows)
Use d tablename to view table information:
tutorialdb=# 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)
YouTip