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


  1. Create a function to get the id from the table users with email as an arg.

    CREATE OR REPLACE FUNCTION id_in_users(iemail varchar) RETURNS int LANGUAGE SQL AS
    $$ SELECT id FROM users WHERE email = iemail; $$;
    
  2. And alter the table

    ALTER TABLE runs ADD COLUMN userId bigint NOT NULL DEFAULT     
    id_in_users('[email protected]');
    

SQL FIDDLE(DEMO)

Tags:

Sql

Postgresql