Skip to content

Instantly share code, notes, and snippets.

@LuisSevillano
Created February 28, 2019 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LuisSevillano/4217e13debe2bdf6a93c65ea6e1fe91a to your computer and use it in GitHub Desktop.
Save LuisSevillano/4217e13debe2bdf6a93c65ea6e1fe91a to your computer and use it in GitHub Desktop.
Add new column in PostgreSQL with a subquery and set a NOT NULL constraint
BEGIN;
ALTER TABLE table1 ADD COLUMN exp_id text;
UPDATE table1
SET exp_id = temp_query.exp_id
FROM (
SELECT t2.exp_id FROM table2 t2 JOIN table1 t1 on t2.gid = t1.gid
) AS temp_query;
ALTER TABLE table1 ALTER COLUMN exp_id SET NOT NULL;
COMMIT;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment