0

I want to create a code for a table in postgresql. The model could looks like: event {id, code, name, created_by} The code will start at E0001 and finish at E9999. The idea is to check at insert, if there's no code generate it, else insert the provided code. I assume I have to use a trigger, but I don't know how to generate that code with that sequence and check if exists or not. Help.

2
  • What happens when you insert the 10000th row? Commented Sep 13, 2021 at 2:27
  • Lets assume will never insert that, although the code could be E10000. The thing here is to maintain the format with zeros, at least until the 9999th row. Commented Sep 13, 2021 at 4:21

3 Answers 3

1

You can use lpad function to pad the number with zeroes.

select 'E' || lpad (45::text, 5, '0')
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a DEFAULT clause in your column definition that uses a sequence:

CREATE SEQUENCE seq;

ALTER TABLE mytab ALTER code SET DEFAULT 'E' || CAST(nextval('seq') TO text);

Comments

0

I finally solved by doing this:

Creating a sequence

CREATE SEQUENCE seq;

and setting the DEFAULT value of code with

('E'::text || lpad((nextval('seq'::regclass))::text, 4, '0'::text))

Thanks both of you since I used the two answers.

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.