Page Content

Tutorials

What Are ALTER TABLE Command In PostgreSQL With Example

ALTER TABLE Command

Standard PostgreSQL command ALTER TABLE defines or updates tables. Database administrators and developers need this crucial Data Definition Language functionality to alter table Command schemas to fit application needs without losing data. This is important when a table is referenced by other database objects or includes data, making DROP TABLE and CREATE TABLE troublesome. ALTER TABLE operations frequently acquire explicit, table-based locks to maintain data integrity. The many features of the ALTER TABLE command can be broadly divided into table-level changes and column operations.

ALTER TABLE Command
ALTER TABLE Command

Column Operations

Adding Columns (ADD COLUMN): This sentence adds new table columns. You can optionally include a DEFAULT value and specify the data type of a newly added column. NULL is first entered into the column if no DEFAULT is supplied.

Default Values: PostgreSQL 11 introduced a major performance boost by eliminating the need to update every record instantly when a column with a constant default value is added. Even for big tables, the ALTER TABLE operation is incredibly quick since the default is returned when the row is accessed and implemented only when the table is rewritten.

The ALTER TABLE statement will still update every existing row instantly for volatile default values (such as clock_timestamp()). Adding a column without a default, populating it with UPDATE, and then adding the required default if needed may be more efficient for columns that will mostly contain non-default values.

Constraints: In the ADD COLUMN statement, you can provide restrictions, such CHECK constraints, on newly added columns. The process will fail if any given default value does not meet these requirements.

Removing Columns (DROP COLUMN): This operation deletes a specified column and all of its contents permanently. Additionally eliminated are any table constraints pertaining to the omitted column. The dependant constraint will not be silently dropped by PostgreSQL if the column is referenced by a foreign key constraint in another table. You can utilise the CASCADE option to allow the removal of all dependant items. Column names can be included in brackets or dropped using a simpler syntax, according to DBeaver’s choices.

Modifying Column Properties (ALTER COLUMN):

Setting/Dropping Default Values: Use ALTER COLUMN column SET DEFAULT to change a column’s default value. All future INSERTs will utilise this default. ALTER COLUMN DROP DEFAULT deletes default values. This implicitly sets NULL as default.

Changing Data Types: The ALTER COLUMN column TYPE type [USING expression] command changes data types. This action succeeds only when all column data can be automatically cast to the new type. A USING clause can specify a calculation to convert old values to new types in more intricate conversions. Due to type conversion complexity and the possibility of unexpected failures or results, it is best to temporarily remove column constraints before altering its type and then re-add updated constraints. Changes to column data types are expensive, especially in fully loaded databases. This usually needs locking and recreating the table.

Setting/Dropping NOT NULL: ALTER COLUMN column SET NOT NULL easily validates data compliance. This constraint is removed using ALTER COLUMN DROP NOT NULL.

Setting Statistics and Storage: ALTER COLUMN optimises performance with storage choices (SET STORAGE {PLAIN | EXTERNAL | EXTENDED | MAIN}) and statistics settings (SET STATISTICS integer).

Renaming Columns (RENAME COLUMN): EDIT TABLE table_name RENAME COLUMN renames. Replace column old_name with new_name. The column’s name changes but not its data or type.

Code Example:

CREATE TABLE employees (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    department TEXT
);
ALTER TABLE employees ADD COLUMN joining_date DATE DEFAULT '2023-01-01';
ALTER TABLE employees ADD COLUMN salary NUMERIC;
ALTER TABLE employees ADD COLUMN bonus NUMERIC DEFAULT 0 CHECK (bonus >= 0);
INSERT INTO employees (name, department, salary, bonus)
VALUES ('Alice','HR',50000,5000),('Bob','Finance',60000,0);
ALTER TABLE employees ALTER COLUMN joining_date SET DEFAULT CURRENT_DATE;
ALTER TABLE employees ALTER COLUMN joining_date DROP DEFAULT;
ALTER TABLE employees ALTER COLUMN salary TYPE INTEGER USING salary::INTEGER;
ALTER TABLE employees ALTER COLUMN salary SET NOT NULL;
ALTER TABLE employees ALTER COLUMN salary DROP NOT NULL;
ALTER TABLE employees RENAME COLUMN bonus TO performance_bonus;
ALTER TABLE employees DROP COLUMN joining_date;
SELECT * FROM employees;

Output:

CREATE TABLE
ALTER TABLE
ALTER TABLE
ALTER TABLE
INSERT 0 2
ALTER TABLE
ALTER TABLE
ALTER TABLE
ALTER TABLE
ALTER TABLE
ALTER TABLE
ALTER TABLE
 id | name  | department | salary | performance_bonus 
----+-------+------------+--------+-------------------
  1 | Alice | HR         |  50000 |              5000
  2 | Bob   | Finance    |  60000 |                 0
(2 rows)

Table Operations

Renaming Tables (RENAME TO): RENAME TO ALTER TABLE old_name renames a table. Rename to new_name.

Adding Constraints (ADD table_constraint): ADD table_constraint adds CHECK, UNIQUE, FOREIGN KEY, and PRIMARY KEY constraints. Checking table data against these criteria is instant.

Dropping Constraints (DROP CONSTRAINT): DROP CONSTRAINT constraint_name is a function that allows you to remove existing constraints by name. Dependent objects can be automatically dropped by specifying the CASCADE option.

Transferring Ownership (OWNER TO): Utilising ALTER TABLE table_name OWNER TO new_owner, a table’s ownership can be moved to a new role. Regular roles need to be both the target new owning role and the present owner (or a member of the owning role), while superusers have the ability to transfer ownership worldwide.

Managing Tablespaces (SET TABLESPACE): ALTER TABLE table_name A table can be moved to a new tablespace with SET TABLESPACE tablespace_name, which aids in disc storage management. The default tablespace for upcoming partitions can also be configured for partitioned tables. The tablespace for a target table can be specified when transferring data using DBeaver.

Inheritance: ALTER TABLE allows you to change the inheritance relationships. With INHERIT parent_table, tables can be configured to inherit from a parent table; with NO INHERIT parent_table, inheritance can be stopped. When putting table partitioning ideas into practice, this is quite helpful.

Partitioning: ALTER TABLE’s ATTACH and DETACH PARTITION subcommands add or remove a table as a partition of a partitioned table. Before attaching a partition, add a CHECK constraint on the table to match its criteria. This lets the system validate without an ACCESS EXCLUSIVE lock and skip a full table scan.

DBeaver in Alter Table Command

With its easy UI and SQL generation capabilities, DBeaver supports the ALTER TABLE command and lets users change the structure and definition of database tables. This robust database administration tool allows column-level and table-level table schema evolution actions.

In particular, DBeaver allows adding new columns to a table and implementing constraints like CHECK, UNIQUE, FOREIGN KEY, and PRIMARY KEY. It can also be configured to explicitly add the COLUMN keyword in ALTER TABLE statements to clarify column removal and utilise brackets for column names. Besides column management, DBeaver may rename columns and tables, change data types, and establish or eliminate default values and NOT NULL restrictions.

Edit mode for Diagrams in DBeaver lets users graphically alter database objects, such as generating foreign keys by dragging columns between tables. These visual changes are translated into SQL scripts, including ALTER TABLE instructions, that may be executed to modify the database. on addition, DBeaver can generate ALTER TABLE statements to establish target table features like tablespace and partitioning, which can be reviewed on a “Target DDL” tab during data migration or table creation. DBeaver’s PostgreSQL support lets you manage constraints, indexes, foreign keys, partitions, and triggers using ALTER TABLE. Users can easily adjust their table schemas with visual aid and SQL code inspection using this integrated approach.

Conclusion

In conclusion, PostgreSQL’s ALTER TABLE command is critical for changing database schemas without losing data, allowing column-level and table-level operations to satisfy changing application needs. It can create, remove, and change columns with defaults, constraints, and data type conversions, rename columns and tables, transfer ownership, manage tablespaces, and handle inheritance or splitting.

These activities frequently require table-level locks to maintain data integrity, however PostgreSQL has optimised several actions, such as adding columns with fixed default values, to run efficiently on huge datasets. DBeaver’s intuitive interface lets users visually edit schemas, automatically generate SQL scripts, and manage advanced features like constraints, foreign keys, partitions, and storage settings, combining flexibility with precise control over table structure evolution.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index