Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default value in PostrgreSQL table column to a value from a query

Tags:

sql

postgresql

I want to do the following

ALTER TABLE runs ADD COLUMN userId bigint NOT NULL DEFAULT (SELECT id FROM users WHERE email = '[email protected]');

but it keeps giving me syntax error. How could I do this guys? Any help is highly appreciated. ;)

like image 765
Mahir Zukic Avatar asked Aug 19 '14 08:08

Mahir Zukic


People also ask

How do I set default value in query?

Select the column for which you want to specify a default value. In the Column Properties tab, enter the new default value in the Default Value or Binding property. To enter a numeric default value, enter the number. For an object or function enter its name.

What statement can be used to change the default value of a column?

You can set the default value for columns when you create a new table. You use the CREATE TABLE DDL statement and add the DEFAULT keyword and default value expression after the column name and type.

How do I find the default value of a column in PostgreSQL?

In a table definition, default values are listed after the column data type. For example: CREATE TABLE products ( product_no integer, name text, price numeric DEFAULT 9.99 ); The default value can be an expression, which will be evaluated whenever the default value is inserted (not when the table is created).


1 Answers

  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)

like image 82
Vivek S. Avatar answered Sep 24 '22 02:09

Vivek S.