The Wayback Machine - https://web.archive.org/web/20241006114449/https://www.geeksforgeeks.org/postgresql-create-table/
Open In App

PostgreSQL – CREATE TABLE

Last Updated : 11 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In PostgreSQL, the CREATE TABLE clause as the name suggests is used to create a new table. Creating tables is a fundamental aspect of database design in PostgreSQL.

Let us get a better understanding of the CREATE TABLE Clause in PostgreSQL.

Syntax

CREATE TABLE table_name (
column_name TYPE column_constraint,
table_constraint table_constraint
) INHERITS existing_table_name;

Let’s analyze the syntax above:

  • Table Name: Define the name of the new table after the CREATE TABLE clause. Use the TEMPORARY keyword if you’re creating a temporary table.
  • Column Definition: List the column name, data type, and constraint. Columns are separated by a comma (,). Column constraints include rules like NOT NULL.
  • Table-Level Constraints: Define rules for the data in the table at a broader level, such as primary and foreign keys.
  • Inheritance: Specify an existing table from which the new table inherits columns. This is a PostgreSQL extension to SQL, making table creation more flexible.

PostgreSQL CREATE TABLE Example

Now let us take a look at an example of the CREATE TABLE in PostgreSQL to better understand the concept.

1. Creating the ‘account' Table

In this example, we create a new table named account with the following columns and constraints:

  • ‘user_id’ – primary key
  • ‘username’ – unique and not null
  • ‘password’ – not null
  • ’email’ – unique and not null
  • ‘created_on’ – not null
  • ‘last_login’ – null

The following statement creates the account table:

CREATE TABLE account(
user_id serial PRIMARY KEY,
username VARCHAR (50) UNIQUE NOT NULL,
password VARCHAR (50) NOT NULL,
email VARCHAR (355) UNIQUE NOT NULL,
created_on TIMESTAMP NOT NULL,
last_login TIMESTAMP
);

2. Creating the ‘role' Table

Next, we create the role table with two columns: ‘role_id' and ‘role_name'.

CREATE TABLE role(
role_id serial PRIMARY KEY,
role_name VARCHAR (255) UNIQUE NOT NULL
);

3. Creating the account_role Table

Finally, we create the ‘account_role' table to manage the relationship between users and roles. This table has three columns: ‘user_id', ‘role_id', and ‘grant_date'.

CREATE TABLE account_role
(
user_id integer NOT NULL,
role_id integer NOT NULL,
grant_date timestamp without time zone,
PRIMARY KEY (user_id, role_id),
CONSTRAINT account_role_role_id_fkey FOREIGN KEY (role_id)
REFERENCES role (role_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT account_role_user_id_fkey FOREIGN KEY (user_id)
REFERENCES account (user_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);

Detailed Analysis

Primary Key Constraint

The primary key for the account_role table consists of two columns: ‘user_id' and ‘role_id'. The primary key constraint ensures that each combination of ‘user_id' and ‘role_id' is unique.

PRIMARY KEY (user_id, role_id)

Foreign Key Constraints

Foreign key constraints ensure referential integrity between tables. The ‘user_id' in ‘account_role' references the ‘user_id' in the ‘account' table, while ‘role_id' references the ‘role_id' in the role table.

CONSTRAINT account_role_user_id_fkey FOREIGN KEY (user_id)
REFERENCES account (user_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION

The ‘role_id’ column references to the ‘role_id' column in the role table, we also need to define a foreign key constraint for the ‘role_id' column:

CONSTRAINT account_role_role_id_fkey FOREIGN KEY (role_id)
REFERENCES role (role_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,

Output:

PostgreSQL CREATE TABLE Example

Important Points About CREATE TABLE Clause in PostgreSQL

  • The CREATE TABLE clause is used to define a new table in the database.
  • Use the ‘INHERITS' clause to create a table that inherits columns from an existing table.
  • Use the ‘TEMPORARY‘ or ‘TEMP' keyword to create tables that exist only for the duration of the session.
  • Specify a tablespace for storing the table using the ‘TABLESPACE' clause.
  • Use the PARTITION BY clause to define table partitioning, which helps manage large tables.
  • Tables can be created within specific schemas for better organization.



Previous Article
Next Article

Similar Reads

PostgreSQL - Export PostgreSQL Table to CSV file
In this article we will discuss the process of exporting a PostgreSQL Table to a CSV file. Here we will see how to export on the server and also on the client machine. For Server-Side Export: Use the below syntax to copy a PostgreSQL table from the server itself: Syntax: COPY Table_Name TO 'Path/filename.csv' CSV HEADER; Note: If you have permissio
2 min read
PostgreSQL - CREATE TABLE AS
The CREATE TABLE AS statement in PostgreSQL is a powerful tool used to create a new table and populate it with data returned by a query. This functionality allows you to generate tables on the fly based on query results, which can be very useful for reporting, analysis, and other tasks. Let us better understand the CREATE TABLE AS statement in Post
3 min read
PostgreSQL - Create table using Python
Creating tables in a PostgreSQL database using Python is a common task for developers working with databases. This process involves defining the structure of your data and ensuring that your database is optimized for efficient storage and retrieval. In this article, we will walk through the steps of creating tables in PostgreSQL using Python. Prere
3 min read
PostgreSQL - Connect To PostgreSQL Database Server in Python
The psycopg database adapter is used to connect with PostgreSQL database server through python. Installing psycopg: First, use the following command line from the terminal: pip install psycopg If you have downloaded the source package into your computer, you can use the setup.py as follows: python setup.py build sudo python setup.py installCreate a
4 min read
PostgreSQL - Installing PostgreSQL Without Admin Rights on Windows
If you are a part of a corporation, it is highly unlikely that you have the admin privileges to install any external software. But the curious souls that all software developers are, in this article, we will see the detailed process of installation of PostgreSQL without having administrator rights on our Windows machine. Installation: Follow the be
3 min read
PostgreSQL - Removing Temporary Table
In PostgreSQL, one can drop a temporary table by the use of the DROP TABLE statement. Syntax: DROP TABLE temp_table_name; Unlike the CREATE TABLE statement, the DROP TABLE statement does not have the TEMP or TEMPORARY keyword created specifically for temporary tables. To demonstrate the process of dropping a temporary table let's first create one b
2 min read
PostgreSQL - Insert Data Into a Table using Python
In this article we will look into the process of inserting data into a PostgreSQL Table using Python. To do so follow the below steps: Step 1: Connect to the PostgreSQL database using the connect() method of psycopg2 module.conn = psycopg2.connect(dsn) Step 2: Create a new cursor object by making a call to the cursor() methodcur = conn.cursor() Ste
2 min read
How to Insert Multiple Rows to a Table in PostgreSQL?
Inserting multiple rows into a table in PostgreSQL is a common operation that may enhance efficiency when managing large datasets. By executing a single SQL query, more than one row is inserted simultaneously, which reduces the overload of multiple individual inserts. This method not only helps in the insertion process but also enhances the databas
4 min read
How to Update Table Rows in PostgreSQL Using Subquery?
PostgreSQL is a general-purpose object-relational database management system and is open-source. It ensures data integrity features like constraints, transactions and foreign key support. In this article, We will understand How to update table rows in PostgreSQL using subquery using various methods, examples and so on. Introduction to Update Statem
5 min read
How to Select Rows that Don't Exist in Other Table in PostgreSQL?
In PostgreSQL, there are times when we need to find records in one table that do not exist in another table. This can be useful for various data manipulation tasks and ensuring data integrity. In this article, we will explore different approaches along with examples to achieve this using PostgreSQL. By the end, you will have a clear understanding o
5 min read
PostgreSQL - Common Table Expression (CTE)
Common Table Expressions (CTEs) in PostgreSQL are a powerful feature that allows you to define temporary result sets that can be referenced within another SQL statement, such as SELECT, INSERT, UPDATE, or DELETE. CTEs are temporary in the sense that they only exist during the execution of the query. They are typically used to simplify complex joins
3 min read
PostgreSQL - Copy Table
PostgreSQL allows copying an existing table, including the table structure and data, using various forms of the PostgreSQL COPY TABLE statement. This functionality is essential for tasks such as creating backups, migrating data, or experimenting with data transformations. In this article, we will cover different methods to copy a table in PostgreSQ
3 min read
PostgreSQL - Temporary table name
In PostgreSQL, it is possible, though not recommended, to create a temporary table with the same name as an existing permanent table. When a temporary table shares its name with a permanent table, the temporary table will take precedence, preventing access to the permanent table until the temporary table is removed. This behavior can lead to confus
2 min read
PostgreSQL - Function Returning A Table
Creating custom functions that return tables is handy for complex queries and dynamic data processing. In this article, we will look into developing functions that return a table in PostgreSQL. We will use the film table in the sample database for the demonstration. Creating a Function to Return Films Based on Title PatternThe following function re
3 min read
PostgreSQL - TRUNCATE TABLE
PostgreSQL supports the TRUNCATE TABLE statement to quickly remove all data from large tables. While the DELETE statement can also be used to remove all data from a table, TRUNCATE TABLE is significantly more efficient for large tables. Let us learn about the syntax and important tips of the TRUNCATE TABLE statement, providing examples to enhance y
3 min read
PostgreSQL - DROP TABLE
In PostgreSQL, the DROP TABLE statement is a powerful command used to permanently remove one or more tables from a database. This action cannot be reversed, so it's crucial to use it with caution. Let us better understand the DROP TABLE Statement in PostgreSQL from this article. SyntaxDROP TABLE [IF EXISTS] table_name [CASCADE | RESTRICT];Parameter
3 min read
PostgreSQL - Temporary Table
A temporary table in PostgreSQL is a short-lived table that exists only for the duration of a database session or a transaction. PostgreSQL automatically drops temporary tables at the end of a session or transaction, making them ideal for transient data that does not need to persist. Let us learn how to add a Temporary Table in PostgreSQL from this
2 min read
PostgreSQL - Rename Table
Renaming a table in PostgreSQL is a common task that can be quickly done using the RENAME clause in combination with the ALTER TABLE statement. This article will walk you through the process of renaming an existing table in PostgreSQL, explaining the syntax, and providing a detailed example. SyntaxALTER TABLE table_name RENAME TO new_table_name; In
2 min read
PostgreSQL - ALTER TABLE
In PostgreSQL, the ALTER TABLE statement is a powerful tool that allows you to modify the structure of an existing table to suit evolving database needs. The ALTER TABLE statement provides the flexibility to make these changes without disrupting your database operations. In this article, we’ll look into the various actions you can perform with the
4 min read
PostgreSQL - Describe Table
Unlike MySQL, PostgreSQL does not have a 'DESCRIBE' statement to view table column details. However, PostgreSQL provides several methods to access information about table columns. In this article, we'll learn two effective ways to Describe Tables in PostgreSQL. 1. Using the pSQL shellThe 'psql' command-line interface in PostgreSQL offers commands t
2 min read
PostgreSQL - Copy a Table
This article will focus on copying an existing table to a new table in PostgreSQL. This might come in handy while creating new tables that would either have the same data or data of the same table with certain operations performed on them. Ways to Copy a TableWe will discuss the following 3 cases to copy a table in PostgreSQL: Table of Content Copy
3 min read
PostgreSQL - Size of a Table
PostgreSQL provides a variety of functions to help you query the size of your tables. We'll focus on the 'pg_relation_size()' function to get the size of a table and enhance the readability of the output using the 'pg_size_pretty()' function. In this article, we will be using a sample database for reference which is described here and can be downlo
3 min read
PostgreSQL - TRUNCATE TABLE
When working with large datasets in PostgreSQL, you might find the need to clear all data from a table quickly. While the DELETE statement is a common option, it can be slow when dealing with a table containing large amounts of data. Instead, PostgreSQL provides the TRUNCATE TABLE statement, which is significantly faster and more efficient. Let us
2 min read
PostgreSQL - Import CSV File Into Table
Importing data from a CSV (Comma-Separated Values) file into a PostgreSQL database is a common task for database administrators and developers. PostgreSQL provides the COPY command, which is a powerful and efficient way to bulk load data directly from a CSV file into a table. In this article, we will discuss the process of importing a '.csv' file i
2 min read
How to Select the Nth Row in a PostgreSQL Database Table?
In PostgreSQL, selecting specific rows is a fundamental operation frequently required for tasks such as data analysis, pagination, and reporting. The "nth" row refers to the row in a table that holds a particular position or rank, where "n" represents that specific position or ranking number. This article explores various techniques to efficiently
5 min read
How to Create a New User With Full Privileges in PostgreSQL?
PostgreSQL provides a way to give a user full privileges to do anything with the database. The database objects like schema, table, function, and so on. The 'GRANT' command is used in PostgreSQL to provide a user with any specific privileges or to override the role of the user. In this article, we are going to learn how we can create a new user ass
6 min read
PostgreSQL - CREATE PROCEDURE
The CREATE PROCEDURE statement in PostgreSQL is used to create new stored procedures. Stored procedures are beneficial for encapsulating business logic, especially when you need to execute transactions. A drawback of user-defined functions is that they cannot execute transactions. In other words, inside a user-defined function, you cannot start a t
3 min read
PostgreSQL - CREATE SEQUENCE
A sequence in PostgreSQL is a user-defined schema-bound object that generates a sequence of integers based on specified parameters. The CREATE SEQUENCE statement is used to create sequences in PostgreSQL. Let us get a better understanding of the CREATE SEQUENCE Statement in PostgreSQL from this article. SyntaxCREATE SEQUENCE [ IF NOT EXISTS ] seque
4 min read
PostgreSQL - CREATE SCHEMA
PostgreSQL provides the CREATE SCHEMA statement to create a new schema in a database. Schemas in PostgreSQL help organize database objects such as tables, views, and functions, allowing for better data management and security. Let us get a better understanding of the syntax, options, and examples of using the CREATE SCHEMA statement in PostgreSQL.
3 min read
PostgreSQL - CREATE ROLE
PostgreSQL uses roles to represent user accounts. Unlike other database systems that use the concept of users, PostgreSQL treats roles as the primary means of access control. Roles that can log in are called login roles, which are equivalent to users in other systems. Roles that contain other roles are known as group roles. When you create a role,
4 min read