Add new column in PostgreSQL with a subquery and set a NOT NULL constraint
✓ Published0🌍 Public
LLuisSevillano
Last edited Feb 28, 2019
Created on Feb 28, 2019
This example shows how to add a new column to an existing PostgreSQL table and populate it with values from another table using a subquery in an UPDATE statement. The SQL script begins by adding the `exp_id` column as type `text`, then updates it by joining `table1` with `table2` on the `gid` field to copy matching `exp_id` values. Finally, it alters the column to set a `NOT NULL` constraint and wraps all operations in a single transaction with `BEGIN` and `COMMIT` to ensure atomicity. The code relies on standard PostgreSQL DDL and DML commands without external APIs.
AI-generated description