ALTER table - (PostgreSQL Table)
ALTER TABLE
is a command in PostgreSQL that allows you to modify an existing table. You can add or drop columns, change data types, and modify constraints. In this tutorial, we'll discuss the syntax, example, output, explanation, use, important points, and summary of ALTER TABLE
command in PostgreSQL.
Syntax
ALTER TABLE table_name
action;
table_name
: The name of the table to modify.action
: The modification you want to make to the table.
Example
Let's use the ALTER TABLE
command to add a new column to an existing table.
ALTER TABLE employees
ADD COLUMN email VARCHAR(255);
The output of this query would be:
ALTER TABLE
Explanation
In this example, we added a new column named email
to the employees
table with a data type of VARCHAR(255)
.
Use
The ALTER TABLE
command is used when you need to modify an existing table. Some common use cases include adding or removing columns, changing data types, and adding or modifying constraints.
Important Points
- When adding a new column, you should specify a default value using the
DEFAULT
keyword. - You can use the
DROP COLUMN
keyword to remove columns from a table. - If a column has a
NOT NULL
constraint, you must specify a default value when adding a new column, or alter the table to remove theNOT NULL
constraint before adding a new column. - When changing the data type of a column, be aware of the potential for data loss.
- Some modifications, such as changing the name of a column, may require a complete table rewrite, which can be slow on large tables.
Summary
In this tutorial, we discussed the ALTER TABLE
command in PostgreSQL. We covered the syntax, example, output, explanation, use, important points, and summary of the ALTER TABLE
command. With this knowledge, you can now modify existing tables in PostgreSQL to better suit your needs.