I have tables that use UUIDs. I want to be able to insert a new row with or without a UUID as sometimes the client will generate the UUID other times it won't.
Each table has this at it's core:
CREATE TABLE IF NOT EXISTS person (
id UUID PRIMARY KEY DEFAULT gen_random_uuid()
);
I'm trying to use a function to insert rows. I'd like to be able to hand a NULL id and get a default value (a generated UUID). I have something like this:
CREATE OR REPLACE FUNCTION create_person(
id UUID
) RETURNS BOOLEAN LANGUAGE plpgsql SECURITY DEFINER AS $$
BEGIN
INSERT INTO person( id )
VALUES (
COALESCE(id,default)
);
RETURN FOUND;
END;
$$;
I've tried this:
INSERT INTO person ( id ) VALUES (
COALESCE(id, default),
);
and this:
INSERT INTO person ( id ) VALUES (
CASE WHEN id IS NULL THEN default ELSE id END
);
This works, but it repeats the gen_random_uuid() code:
INSERT INTO person ( id ) VALUES (
COALESCE(id, gen_random_uuid()),
);
similarly this works too but has the same problems:
INSERT INTO person ( id ) VALUES (
CASE WHEN id IS NULL THEN gen_random_uuid() ELSE id END
);
Is there a way to do this where I don't have to repeat the gen_random_uuid() code?
Would this be better done with plpgsql?
if id is not null then insert .. values (id) else insert ... values (default)- a_horse_with_no_namedefault? I cannot see where it's defined. Is that visible? Can you print it? Another angle is: I would try to name thisdefaultsomething else that's not an SQL keyword, likedefault_value. - Tamas Revdefaultkeyword that I want. I would like Postgres to insert a default value there (as defined in the CREATE TABLE). - Sambeaubefore insertfor you. I can't test it because I don't have postgres on my machine. However, this page is a good place to start. - Tamas RevBEFORE INSERTTriggers let you change the values of any insert and swap out nulls for a new value. - Philip Couling