Link to home
Start Free TrialLog in
Avatar of pvsbandi
pvsbandiFlag for United States of America

asked on

How to create a sequence to append current date's year and month

Hi,

  We are on Postgres 9.7
I need to create a sequence which will be YYYYMM, followed by a number that gets incremented. YYYYMM will be the year and month of the current date.
Can someone help?
Avatar of slightwv (䄆 Netminder)
slightwv (䄆 Netminder)

Try this:
create sequence mysequence;

select  to_char(current_date,'YYYYMM') || nextval('mysequence');

Open in new window


https://dbfiddle.uk/?rdbms=postgres_9.6&fiddle=1d1e95c2bfc87a2e794622598c66400f

If you want the sequence to have a fixed format padded with 0: LPAD:
https://www.postgresql.org/docs/9.1/functions-string.html
Avatar of pvsbandi

ASKER

Thank you! This certainly helps.
  Also, is there a way to reset the 'mysequence' value every day?
As long as you can ensure it runs EXACTLY at midnight, down to the second, there is an alter sequence:
ALTER SEQUENCE serial RESTART WITH 105;

https://www.postgresql.org/docs/11/sql-altersequence.html


Question I have is what is the actual business need you are trying to solve by resetting the sequence?  I'm not really seeing a good reason to reset the sequence.
Actually, i wouldn't need to reset it.
The requirement was to create a primary key sequence, which shall have the format of YYYYMM, followed by a 5 digit random number.
So, this 5 digit number shouldn't repeat within that day, but can repeat the following day, as the YYYYMM number changes.
ASKER CERTIFIED SOLUTION
Avatar of slightwv (䄆 Netminder)
slightwv (䄆 Netminder)

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You have added great value! Thanks for answering my additional questions as well.
Have a great day!
Happy to help!