How to create auto incremented alphanumeric id in postgres

Table of contents
Reading Time: < 1 minute

A few days ago, i got a condition where i need to create an alphanumeric auto incremented id in Postgres. I have created many auto incremented numeric ids before, but never got a use case like this. This was new for me.  Therefore, here i am going to share the solution for the same which can be useful for you as well.

First , we will create a sequence :

Then, if you want to start your id from a particular number, then do as follows :

Here, id will start from 101. If you will not use above line then it will start from 1.

Now define the column which you want to be alphanumeric auto incremented :

Here, id is the column name, while “RK” is the string which will be prefixed to auto incremented number.

Full code :

Now, run below command and see what happens :

A row will be inserted into employee table containing 2 as a id.

If you dont want to insert ids which does not have “RK” as prefix, then use the below line :

Full code for id condition check :

That’s all. Hope, it will help you guyz.

Cheers !!!

 

 

Written by 

Rishi is a tech enthusiast with having around 10 years of experience who loves to solve complex problems with pure quality. He is a functional programmer and loves to learn new trending technologies. His leadership skill is well prooven and has delivered multiple distributed applications with high scalability and availability by keeping the Reactive principles in mind. He is well versed with Scala, Akka, Akka HTTP, Akka Streams, Java8, Reactive principles, Microservice architecture, Async programming, functional programming, distributed systems, AWS, docker.

1 thought on “How to create auto incremented alphanumeric id in postgres2 min read

Comments are closed.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading