Set default value in PostrgreSQL table column to a value from a query
You can't do that on DEFAULT
. However you could use a trigger before insert checking if there is a NULL
value.
You can check the PostgreSQL Trigger Documentation here
Create a function to get the
id
from the tableusers
withemail
as an arg.CREATE OR REPLACE FUNCTION id_in_users(iemail varchar) RETURNS int LANGUAGE SQL AS $$ SELECT id FROM users WHERE email = iemail; $$;
And alter the table
ALTER TABLE runs ADD COLUMN userId bigint NOT NULL DEFAULT id_in_users('[email protected]');
SQL FIDDLE(DEMO)