Basic Usage
The PostgreSQL ALTER query is pretty straightforward. It follows the simple syntax below:
In this case, the action includes the supported PostgreSQL operations. These include:
- ADD or DELETE a column
- MODIFY column data type
- RENAME a table
- RENAME a column
- ADD column constraint
- SET or DROP column DEFAULT value.
- DROP IDENTITY
- ADD table constraint
- ALTER CONSTRAINT
- ATTACHING PARTITIONS
- SET schema
And many more. Learn more about ALTER TABLE operations in the documentation.
Below are example operations you can perform on a table using the ALTER TABLE query.
Add or Drop Column
One of the most common use cases of the ALTER TABLE command is to add a new column to the table.
The syntax is as:
The query above will append the column with the specified column name, data type, and constraints to the table.
To drop a column, you can use the DROP COLUMN query as:
Modify Column Data type
Another use of the ALTER TABLE command is to change a column data type. An example query for that is:
In the above example, we use the ALTER commands (TABLE & COLUMN) to change the data type to a VARCHAR.
Rename a Table
We can also use the ALTER TABLE query to rename a table. The syntax for that is:
Rename a Column
We can also use ALTER to rename a column by expressing the query as:
Add/Remove Column Default Value
To add or remove a column constraint, we can use the query:
To drop a default value:
Add Table Constraint
To add a table constraint using the ALTER TABLE command, we can do:
In the above example, we specify the column name and column definition after the ADD constraint query.
Alter Constraint
To alter an existing table constraint, we can use the query:
Add Check Condition
To set a column that accepts only specific values, we can set a check condition with target values.
Here is an example query:
The above condition ensures that the specified column only contains the specified values.
Set Table Schema
To change the table schema, use the query:
Remove Not Null Constraint
You can also remove a not null constraint from a column using the query:
Rename Existing Constraint
You can also use the ALTER TABLE to rename an existing constraint. The general syntax for that is:
Closing
The above examples show how you can use the ALTER TABLE command to change a table’s structure. Although we have provided the syntax for the most common operations, there are more actions you can do.
I would recommend checking the official documentation for other actions.