0

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)
);
1
  • 1
    From here CREATE TABLE: " DEFAULT default_expr ... The value is any variable-free expression (in particular, cross-references to other columns in the current table are not allowed). Subqueries are not allowed either. ... ". You will need a trigger to do this. Commented Jun 21, 2022 at 20:36

1 Answer 1

1

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 change_title_jokes before insert on jokes for each row execute procedure change_title();

Demo in sqldaddy.io

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.