Home > Blockchain >  Postgres string formatting for record ID
Postgres string formatting for record ID

Time:06-23

I am trying to create a table to keep an archive of dad jokes in Postgres. For the title record, I would like the value to by-default be the joke ID, but formatted in a way where if the id is 7, the record's title is Joke #7. Here is my query to create the table:

CREATE TABLE public.jokes (
    id int NOT null primary KEY,
    user_id int NOT NULL DEFAULT 1,
    title varchar NULL DEFAULT FORMAT("Joke #%s", ), -- the title that I would like to be formatted
    body varchar NOT NULL,
    CONSTRAINT jokes_fk FOREIGN KEY (user_id) REFERENCES public."Users"(id)
);

CodePudding user response:

You need to create a trigger function that will change the title if it is not set

create function change_title() returns trigger as $$
  begin 
     if new.title is null then
         new.title := format('joke #%s', new.id);
     end if;     
     return new; 
  end; $$ language plpgsql; 

create trigger update_product_modified_time before insert on jokes for each row execute procedure change_title();

Demo in DBfiddle

  • Related