Search code examples
mysqlprimary-keyauto-increment

How to automatically create the primary key that has the following series A001000001 ... A001xxxxxx in SQL?


I want to create a primary key(auto-increment) which is start with A001000001. Here A001 would be constant and 000001 would be iterate.

I want rows like this:

enter image description here

How can I do it using SQL query?


Solution

  • For SQL Server (you didn't clearly specify which RDBMS you're using), my suggestion would be:

    • add a INT IDENTITY column to your table - and quite frankly, I would make that column the primary key
    • add a computed column to your table that does this "prefixing"

    Something like:

    CREATE TABLE dbo.YourTable
    ( ID INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
      EmpID AS 'A001' + RIGHT('0000000' + CAST(ID AS VARCHAR(10)), 7) PERSISTED
    )
    

    That way, if you insert a row, the ID gets set automatically, and the EmpID will also be set automatically to values like A0010000001, A0010000002, .... and so forth.

    If you want to put the primary key on the EmpID column, then you need to make sure to include the NOT NULL specification when creating it:

    CREATE TABLE dbo.YourTable
    ( ID INT IDENTITY(1,1),
      EmpID AS 'A001' + RIGHT('0000000' + CAST(ID AS VARCHAR(10)), 7) PERSISTED NOT NULL
    )
    

    and then you can put the primary key constraint on that column:

    ALTER TABLE dbo.YourTable
    ADD CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED (EmpID)