PostgreSQL Create Table

A table is actual storage object in PostgreSQL. CREATE TABLE is used to create table in PostgreSQL Server. CREATE TABLE will create a new, initially empty table in the current database.

Syntax to PostgreSQL Create Table:

CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name ( [ { column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | LIKE source_table [ like_option ... ] } [, ... ] ] )

A table creation command requires three things:

  • Name of the table(tbl_name)
  • Names of fields(column names)
  • Definitions for each field(DataTypes are int,varchar, date,…)

PostgreSQL Create Table Examples:

1. Create Table using command line:

CREATE TABLE emp(empno int, empname varchar(30), deptno int, doj date,salary int not null, PRIMARY KEY(empno));

To verify table created or not

Following command will all tables name created in current database with owner name.

\dt

To get PostgreSQL Structure

We can verify the table structure by running the meta command \d+ emp

\d+ emp

Visual representation:

2. PostgreSQL Create Table from pgAdmin

1. Connect pgAdmin. Then, expand the database in which we want to create table. Right click on tables and select Create Table.

2. Provide the name and list of columns.

3. Click on ok. Then, new table will be created as shown below.

So in this article, we have seen How create PostgreSLQ Create Table using command line and pgAdmin tool.