Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally set a column to its default value in Postgres

Tags:

sql

postgresql

I've got a PostgreSQL 8.4 table with an auto-incrementing, but nullable, integer column. I want to update some column values and, if this column is NULL then set it to its default value (which would be an integer auto-generated from a sequence), but I want to return its value in either case. So I want something like this:

UPDATE mytable
SET incident_id = COALESCE(incident_id, DEFAULT), other = 'somethingelse'
WHERE ...
RETURNING incident_id

Unfortunately, this doesn't work - it seems that DEFAULT is special and cannot be part of an expression. What's the best way to do this?

like image 979
EMP Avatar asked Apr 20 '10 04:04

EMP


1 Answers

use this:

update mytable set a = 
    coalesce(incidentid, 
    (
     select column_default::int 
     from information_schema.columns 
     where table_schema = 'public' 
     and table_name = 'mytable' and column_name = 'incidentid')
    )

if your incidentid is integer type, put a typecast on column_default

[EDIT]

create or replace function get_default_value(_table_name text,_column_name text) 
returns text
as
$$
declare r record;
s text;
begin

    s = 'SELECT ' || coalesce(

    (select column_default 
    from information_schema.columns 
    where table_schema = 'public' 
    and table_name = _table_name and column_name = _column_name)

    , 'NULL') || ' as v';

    EXECUTE s into r;
    return r.v;
end;
$$
language 'plpgsql';

to use:

update mytable set a = 
    coalesce(incidentid, get_default_value('mytable','a')::int )
like image 95
Michael Buen Avatar answered Oct 01 '22 01:10

Michael Buen