In this article, we will learn how to create a table in PostgreSQL. I am going to explain the following topics:
- The syntax of the CREATE TABLE statement and the options that we can use while creating it
- The column and table constraints are supported by PostgreSQL
- How to create a table with Primary key and foreign key
- Populate the list of the tables by querying the pg_admin schema and pgAdmin4 tool
Let us understand the CREATE TABLE statement.
The CREATE TABLE syntax and usage
We are using CREATE TABLE statement to create a table in the PostgreSQL database. Following is the syntax to create a new table.
1 2 3 4 5 6 7 |
CREATE TABLE [IF NOT EXISTS] table_name ( Col_name_1 datatype(length), Col_name_2 datatype(length), Col_name_3 datatype(length), table_constraint ) TABLESPACE=tablespace_name |
In the syntax of CREATE TABLE statement,
- table_name: Specify the name of the table after CREATE TABLE statement. The table name must be unique in the database. The query will return an error if the table with the same name exists on the database. We can use the IF NOT EXISTS to avoid such errors, this option allows us to create a table only when the table with the same name does not exist. If the table with the same name exists, it returns a notice and terminates the statement
- col_name data_type (length): Specify the list of columns and their datatype, length, and constraint that you want to add to a table. The column must be separated by a comma
- table_Constraint: Specify the table constraint that includes a primary key, foreign key, and CHECK constraint
- tablespace_name: Specify the name of the tablespace. If you do not specify the tablespace, the table will be created in pg_default tablespace
PostgreSQL supports the following column constraints:
- PRIMARY KEY: The primary key identifies a record from the table uniquely. A PostgreSQL table can have only one primary key. You can include multiple columns in one primary key
- FOREIGN KEY: A foreign key establishes a Parent-child relationship between the tables of the PostgreSQL database. A foreign key on any table refers to the primary key of another table. The table whose column refers to the primary key column of another table is called the parent table and the table whose primary key column is being referred to is known as a child table
- Not NULL: This constraint does not allow us to insert NULL value in the column on which it is created
- UNIQUE: The UNIQUE constraint does not allow duplicate values to be inserted in the column
- CHECK: This constraint checks the value being inserted in a table. The check constraint has expressions that evaluate against the data being inserted. If the condition evaluates TRUE, the data will be inserted in the column, or it will return an error
Example of CREATE TABLE statement
Let us understand how we can create a basic table. I am creating two tables named tblStudent, tblSchool and tblResult. The tblStudent table contains the following columns:
- Student_ID: This column is used to save the student_id. The data type is an integer, and it is the primary key of the table, and the name of the primary key is PK_Student_ID
- Student_Name: This column stores the name of the student. The data type is varchar, and the length is 500 characters. The column does not allow NULL values
- Grade: This column stores the grade of the student. The data type of the column is character
- recordAdded: This column stores the date and time when the record is inserted. A default value has been defined on the table. If the insert statement does not have a value of the recordAdded column, the query inserts the current date and time
The table is created in the pg_default tablespace, and the fill factor of the table is 70.
The following script is used to create a tblStudent table.
1 2 3 4 5 6 7 8 9 10 11 12 |
CREATE TABLE public."tblStudent" ( "Student_ID" integer NOT NULL, "Student_Name" character varying(500) NOT NULL, "Grade" character(1), "RecordAdded" date, CONSTRAINT "PK_Student_ID" PRIMARY KEY ("Student_ID") ) WITH ( FILLFACTOR = 70 ) TABLESPACE pg_default; |
Screenshot:
Now, let us create another table named tblSchool. This table is used to store the data of the school. The tblSchool table contains the following columns.
- School_id: This column stores the ID of the school. The datatype of the column is an integer. A primary key named pk_school_id has been created on the school_id
- School_name: This column stores the name of the school. The data type of the column is varchar, and the length of the column is 500
The tblSchool table is created in the pg_default table space in fill factor is 90.
The following script is used to create a tblSchool table.
1 2 3 4 5 6 7 8 9 10 |
CREATE TABLE public."tblSchool" ( "School_ID" integer NOT NULL, "School_Name" character varying(500) NOT NULL, CONSTRAINT "PK_School_ID" PRIMARY KEY ("School_ID") ) WITH ( FILLFACTOR = 90 ) TABLESPACE pg_default; |
Screenshot
Let us create a table named tblResult. This table is used to store the result of the student. The details of the columns are as following:
- Result_id: This column stores the ID for the result. The data type is an integer. This column is a primary key of the table
- Student_ID: This column stores the ID of the student. The datatype of the column is an integer. It acts as a foreign key. The student_id references the primary key of the tblStudent table, which is pk_student_id. The foreign key rule for the UPDATE operation is CASCADE which means the changes will be applied on associated records of child tables. The rule for DELETE operation is RESTRICT on the tblStudent table, which means we cannot delete any record from the parent table
- School_id: This column stores the ID of the school. The datatype of the column is an integer. This column acts as a foreign key. The school_id references the primary key of the tblSchool table, which is pk_school_id. The foreign key rule for the UPDATE operation is CASCADE, and the DELETE operation is RESTRICT
- Marks: This column stores the total marks scored by the student. The datatype is float
The tblResult table is created in the pg_default table space in fill factor is 90.
The following script is used to create a tblResult table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
CREATE TABLE public."tblResult" ( "Result_id" integer NOT NULL, "Student_id" integer, "School_ID" integer, "Marks" integer NOT NULL, PRIMARY KEY ("Result_id"), CONSTRAINT "FK_Student_ID" FOREIGN KEY ("Student_id") REFERENCES public."tblStudent" ("Student_ID") MATCH SIMPLE ON UPDATE CASCADE ON DELETE RESTRICT NOT VALID, CONSTRAINT "FK_School_ID" FOREIGN KEY ("School_ID") REFERENCES public."tblSchool" ("School_ID") MATCH SIMPLE ON UPDATE CASCADE ON DELETE RESTRICT NOT VALID ) WITH ( FILLFACTOR = 90 ) TABLESPACE pg_default; |
Screenshot
Once tables are created, let us view them.
View Tables in PostgreSQL
We can populate the list of tables created in the database by running the SELECT statement on the pg_tables. The pg_table is a system catalog view. It is in pg_catalog schema and provides the following information.
- Schemaname: The name of the schema in which the table is created
- TableName: Name of the table
- Table owner: The owner of the table
- Tablespace: The name of the tablespace in which the table is created
- hasIndexes: It’s a Boolean value. If the table has any has an index, then it returns TRUE
- Hasrules: It’s a Boolean value. If the table has any rules, then it returns TRUE
- HasTiggers: It’s a Boolean value. If the table has any triggers, then it returns TRUE
Now, let us run the SELECT query to view the tables that we have created.
1 |
select * from pg_tables where schemaname='public' |
Query Output
As you can see, the tables tblStudent, tblSchool, and tblResult have been created.
Alternatively, you can view it from the pgadmin4 tool. Pgadmin4 is a web-based tool that is used to manage the PostgreSQL database. To view the tables created in DemoDatabase, Connect to PostgreSQL server 🡪 Expand Databases 🡪 Expand Demo Database 🡪 Expand Public 🡪 Expand Tables.
As you can see, these PostgreSQL tables are created.
Summary
In this article, we will learn how to create a table in PostgreSQL. I have explained the following topics:
- The CREATE TABLE syntax and the options that we can use while creating it
- The column and table constraints are supported by PostgreSQL
- How to create a table with Primary key and foreign key
- Populate the list of the tables by querying the pg_admin schema and pgAdmin4 tool
In my next articles, we will learn how to manage the tables in PostgreSQL.
- Different ways to identify and change compatibility levels in SQL Server - July 22, 2024
- Copy SQL Databases between Windows 10 and CentOS using SQL Server data tools - October 19, 2022
- Changing the location of FILESTREAM data files in SQL Database - October 14, 2022