ALTER
POSTGRESQL

PostgreSQL ADD COLUMN: Add One or More Columns to a Table

intro

Let’s take a look at the essentials of using the PostgreSQL ADD COLUMN statement to add columns to existing tables.

PostgreSQL allows modifying existing tables to adapt them to your growing data needs. One way to achieve this is by adding new columns. The PostgreSQL ADD COLUMN statement serves exactly that purpose, enabling you to incorporate additional data points into your tables.

In this article, you will learn what the ADD COLUMN statement is, how to use it, and explore some best practices.

Let’s get right into it!

What Is the ADD COLUMN Statement in PostgreSQL?

The ADD COLUMN statement in PostgreSQL adds a column to an existing table. In particular, it allows you to define the name, data type, default value, or other attributes of the newly added column.

Schema expansion plays an important role in the fruition of a database. As application requirements change over time, it becomes necessary to modify the database schema to accommodate new data structures, hence, the need for adding new columns.

ADD COLUMN in POSTGRESQL: Statement Syntax

The ADD COLUMN statement in Postgres follows a particular syntax, which involves several inputs and options. These include NULL or NOT NULL, default values, constraints, and PostgreSQL data types like integers, strings, dates, and more.

Copy
        
1 ALTER TABLE table_name 2 ADD COLUMN new_column_name data_type [constraint(s)];

To add multiple columns to an existing table, you use multiple ADD COLUMN clauses in the statement above. Now, let’s break down each line of the syntax:

  1. ALTER TABLE table_name: Specifies the name of the table after the ALTER TABLE clause. This gets the table you want to modify ready to be altered. The table_name should be replaced by the name of the table you want to modify.
  2. ADD COLUMN new_column_name: Defines the name of the new column you want to add after the ADD COLUMN clause.
  3. data_type: The data type that defines the kind of information the column will hold (e.g., VARCHAR for text, INT for integers, TIMESTAMP for timestamps).
  4. constraints (optional): Additional specifications for data integrity in PostgreSQL, such as NOT NULL or DEFAULT, etc.

Note that PostgreSQL automatically adds any newly added column to the end of the table and does not have the ability to define the position of the newly added column.

The next section will throw more light on some examples to better understand the practical implementation of the ADD COLUMN PostgreSQL statement. Time to dive deeper!

PostgreSQL ADD COLUMN: Examples

See some examples of PostgreSQL ADD COLUMN query. In this section, we’re going to use DbVisualizer as a PostgreSQL database client but any other client will do.

Example #1: Add a New Column to a Table

The CREATE TABLE statement below creates a new table named students with two columns: id and student_name:

Copy
        
1 CREATE TABLE students ( 2 id SERIAL PRIMARY KEY, 3 student_name VARCHAR(255) NOT NULL 4 );

First, add an address column to the table using the ALTER TABLE ... ADD COLUMN statement:

Copy
        
1 ALTER TABLE students 2 ADD COLUMN address VARCHAR(255);

Writing the query in DbVisualizer, this is what you’ll see:

Screenshot 2024-04-29 at 7.42.03 AM.png
Alter table and add column in DbVisualizer

Explore the students table, and you’ll now see the address column in the end:

Screenshot 2024-04-29 at 7.43.46 AM.png
Students table

Example #2: Add a Column With a Check Constraint

The PostgreSQL ADD COLUMN statement can be used to add a column with a CHECK constraint to enforce data validation rules. For example, consider a students table where you want to add a GPA column that should always be greater than or equal to zero:

Copy
        
1 ALTER TABLE students ADD COLUMN GPA INT CHECK (GPA >= 0);

With this constraint, any attempt to insert or update a row with a negative quantity will result in an error. To experiment with this, try to populate the GPA column with this data:

Copy
        
1 INSERT INTO students (student_name, address, GPA) 2 VALUES ('Asher Adams', '4700 Sabah hill', 3.5), -- Valid GPA value 3 ('Jordan Baker', 'BS 0010 SY', -1), -- Invalid GPA value (less than 0) 4 ('Leila Keaton', 'SE 1234', 4.0); -- Valid GPA valuev
Screenshot 2024-04-29 at 8.20.42 AM.png
PostgreSQL throws an error

Here, you can see that the query violates the rule set by the CHECK constraint. Thus, PostgreSQL throws an error as desired.

Example #3: Add a Column with a Generated Column

PostgreSQL supports generated columns, which are computed based on expressions or functions using other columns' values in the same table. This mechanism is useful when you want to have a calculated column without storing the calculated value physically. For instance, let's say you have an employees table and want to add a fullname column that concatenates the first_name and last_name columns.

Copy
        
1 ALTER TABLE employees ADD COLUMN fullname VARCHAR(100) GENERATED ALWAYS AS (first_name || ' ' || last_name) STORED;

In this example, the fullname column in this example is generated using the concatenation of the first_name and last_name columns and is stored as a computed value.

Best Practices for using the PostgreSQL ADD COLUMN Statement

Below are some of the best practices that should be taken into consideration when working with ADD COLUMN PostgreSQL statement:

  • Always specify appropriate constraints for the new column to ensure data integrity. Consider using appropriate constraints, such as NOT NULL, UNIQUE.
  • As your application evolves, periodically review and refactor the database schema. Remove any unused or obsolete columns, indexes, or constraints to maintain a lean and efficient database structure.
  • When adding a non-nullable column without a default value, ensure that you have the plan to populate or update the existing data with suitable values. If needed, specify an appropriate default value for the column to avoid null values.

It’s a wrap!

Conclusion

The PostgreSQL ADD COLUMN statement offers a precise tool for adding columns to existing tables. To better appreciate its capabilities, you need a tool that helps you manage databases and visually explore query results. This is where a full-featured database client like DbVisualizer comes in. In addition to being able to connect to several DBMSs, it offers advanced query optimization functionality, and full support for all database features, including ADD COLUMN operations. Download DbVisualizer for free now!

FAQ

How do I add a new column(s) to an existing table in PostgreSQL?

To add a new column to an existing table, do this:

Copy
        
1 ALTER TABLE table_name 2 ADD COLUMN new_column_name data_type [constraint(s)];

To add multiple columns, you use multiple ADD COLUMN clauses in the statement.

Can I add a PostgreSQL column with a foreign key constraint?

Assuming we have two tables: Orders and Customers. We want to add a new column named customer_id to the Orders table, which will be a foreign key referencing the id column in the Customers table. This is how we will do it:

Copy
        
1 ALTER TABLE Orders ADD COLUMN customer_id INT REFERENCES Customers (customer_id);

Here, the foreign key constraint is specified using the REFERENCES clause, where we reference the customer_id column in the Customers table.

Can I specify the position of a newly added column?

No, you cannot! PostgreSQL automatically adds any newly added column to the end of the table. There is no option to specify the position of the newly added column as you can do in MySQL.

Dbvis download link img
About the author
Leslie S. Gyamfi.
Leslie S. Gyamfi
Leslie Gyamfi is a mobile/web app developer with a passion for creating innovative solutions. He is dedicated to delivering high-quality products and technical articles. You can connect with him on LinkedIn
The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

SQL Upsert: Inserting a Record If It Does Not Exist

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-12-10
title

How to Find Elements In an Array: PostgreSQL Guide

author Antonello Zanini tags POSTGRESQL 3 min 2024-12-05
title

How and Why to Add an Index in SQL

author Lukas Vileikis tags MySQL POSTGRESQL Search SQL SQL SERVER 8 min 2024-11-28
title

Postgres Create Array of Numbers: Complete Guide

author Lukas Vileikis tags POSTGRESQL SQL 7 min 2024-11-21
title

List of SQL Reserved Words in All Major Databases

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 16 min 2024-11-20
title

SQL Variable: What It Is and How To Use It

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-11-18
title

Postgres DATEDIFF Equivalent Functions: Calculating Date and Time Differences

author Lukas Vileikis tags POSTGRESQL 6 min 2024-11-04
title

CREATE SCHEMA PostgreSQL Statement: What, Why & When to Use

author Lukas Vileikis tags POSTGRESQL 4 min 2024-10-30
title

SQL EXPLAIN: The Definitive Tool to Optimize Queries

author Antonello Zanini tags MySQL POSTGRESQL SQL 12 min 2024-10-29
title

SQL Not Equal Operator: Definitive Guide with Examples

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 6 min 2024-10-14

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.

Cookie policy

We use cookies to ensure that we give you the best experience on our website. However you can change your cookie settings at any time in your browser settings. Please find our cookie policy here ↗