Basics
- How to Insert
- How to Update
- How to Delete
- How to Trim Strings
- How to Use substring()
- How to Use substring() with RegEx to Extract a String
- How to Replace Substrings
- How to Modify Arrays
- How to Compare Arrays
- How to Concatenate Strings
- How to Convert the Case of a String
- How to Create an Array
- How to Insert Data Into an Array
- How to Query Arrays
- How to Use string_agg()
Database Management
- How to Create a Table
- How to Drop a Table
- How to Rename a Table
- How to Truncate a Table
- How to Duplicate a Table
- How to Add a Column
- How to Change a Column Name
- How to Add a Default Value
- How to Remove a Default Value From a Column
- How to Add a Not Null Constraint
- How to Remove a Not Null Constraint
- How to Add an Index
- How to Drop an Index
- How to Create a View
- How to Drop a View
- How to Reset Sequence
- How to Drop a Column
Dates and Times
Analysis
- How to Use nullif()
- How to Use Lateral Joins
- How to Calculate Percentiles
- How to Get the First Row per Group
- How to Use generate_series to Avoid Gaps in Data
- How to Do Type Casting
- How to Write a Common Table Expression
- How to Import a CSV using Copy
- How to Compare Two Values When One Is Null
- How to Use Coalesce
- How to Write a Case Statement
- How to Use Filter to Have Multiple Counts
- How to Calculate Cumulative Sum-Running Total
- How to Query a JSON Column
How to Add a Column in PostgreSQL
In this tutorial, you’ll learn how to add a new column to an existing PostgreSQL table using the ALTER TABLE
command. This is a fundamental skill when modifying database schemas without losing data.
Step 1: Understand the ALTER TABLE Command
The basic syntax to add a column in PostgreSQL is:
ALTER TABLE table_name ADD COLUMN column_name data_type;
For example, if you want to add a birthdate
column of type DATE
to a table called users
, you would write:
ALTER TABLE users ADD COLUMN birthdate DATE;
Step 2: Add a Column with a Default Value
If you want the new column to have a default value, use:
ALTER TABLE users ADD COLUMN active BOOLEAN DEFAULT TRUE;
Step 3: Add a Column with NOT NULL Constraint
To add a column that must always have a value (non-nullable), provide a default or set values after adding the column:
ALTER TABLE users ADD COLUMN country VARCHAR(50) NOT NULL DEFAULT 'USA';
Step 4: Verify Your Changes
You can check the table structure using the \d
command in psql
:
\d users
Or query the information_schema
:
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = 'users';
Best Practices
- Always back up your database before altering tables.
- Use transactions when applying multiple schema changes.
- Test on a staging environment before running on production.
Summary
Adding a column in PostgreSQL is simple with the ALTER TABLE ... ADD COLUMN
command. By understanding the syntax and options like default values and constraints, you can confidently evolve your database schema.