I have to generate encoding String for every item I placed in to the database. for instance:

x00001 for the first item
x00002 for the sencond item
x00003 for the third item

Generate an income chose to get this done is counting the rows. Before I place the 3rd item, I count from the database, I understand there are already 2 rows, therefore the next encoding is ended with 3. But there's an issue. Basically remove the 2nd item, the forth item won't be the x00004,but x00003.

I'm able to add more posts to table, to keep the following encoding, I'm not sure if there's other better solutions ?

Most databases support some kind of auto incrementing identity area. This area is generally also setup to become unique, so duplicate ids don't occur.

Talk to your database documentation to determine how it's completed in your database and employ that - don't reinvent the wheel if you have a great mechanism in position already.

What you would like is SELECT MAX(id) or SELECT MAX(some_function(id)) within the transaction.

As recommended in Oded's answer lots of databases get their own techniques of supplying sequences for efficient and with respect to the DBMS might support non number ids.

Also you might have id divided into Y and 00001 separate posts and getting both posts constitute primary key then most databases would have the ability to supply the sequence.

However this can lead to the question in case your primary key must have a meaning or otherwise Y claim that there's some meaning in negligence the important thing (otherwise you'd be quite happy with an ordinary integer id).