Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for column postgres function with argument

Tags:

postgresql

I have a postgres function that takes one argument. I want to make this function the default value for a column, but I'm not sure how to pass the argument into the table definition.

This is what I mean, I have two columns in the table that look like this:

trade_id INTEGER NOT NULL
group_id INTEGER DEFAULT trade_id_f(argument_goes_here);

I want to make the DEFAULT value of group_id to be the return value of trade_id_f(trade_id) where trade_id is the trade_id of the record to be inserted.

I'm new to all things postgres functions, is this possible?

like image 801
Adam Avatar asked Aug 24 '15 13:08

Adam


People also ask

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

you can just type " \d table_name" command , then It will displays some information about the table, such as the default value of a column. \d will show the default values of a column .

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

Changing a Column's Default Value. To set a new default for a column, use a command like: ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77; Note that this doesn't affect any existing rows in the table, it just changes the default for future INSERT commands.

What is the default value of column?

A default value is the value that is inserted into a column when an explicit value is not specified in an INSERT statement. A default value can be a literal character string that you define or one of the following SQL constant expressions: USER. CURRENT.

What is $$ in PostgreSQL function?

It can be used to replace single quotes enclosing string literals (constants) anywhere in SQL scripts. The body of a function happens to be such a string literal. Dollar-quoting is a PostgreSQL-specific substitute for single quotes to avoid escaping of nested single quotes (recursively).


1 Answers

Unfortunately, you cannot do that, because of (for the documentation):

The value is any variable-free expression (subqueries and cross-references to other columns in the current table are not allowed).

You can use a trigger, e.g.:

create table the_table (
    trade_id int not null,
    group_id int);

create or replace function trade_id_trigger ()
returns trigger language plpgsql as $$
begin
    new.group_id:= new.trade_id+ 1;
    return new;
end $$;

create trigger trade_id_trigger
before insert or update on the_table
for each row execute procedure trade_id_trigger();

insert into the_table values (1,1);

select * from the_table;

 trade_id | group_id
----------+----------
        1 |        2
(1 row)
like image 169
klin Avatar answered Oct 22 '22 17:10

klin