G. Kathrotiya G. Kathrotiya - 5 months ago 12
MySQL Question

How can we create customize primary key having value with some character like EMP0001, EMP0002 in rails

How can we create customize primary key having value with some character like EMP0001, EMP0002 in rails?

Answer

You can use Sequence and default value for your column

postgres=# CREATE SEQUENCE 'xyz';

CREATE SEQUENCE 
postgres=# SELECT setval('xyz', 0001);

setval
-------
0001
postgres=# CREATE TABLE Employee(employee_id text PRIMARY KEY 

                                          CHECK (employee_id ~ '^EMP[0-9]+$')
                                          DEFAULT 'EMP' || nextval('xyz'),
Employee_Name text);

CREATE TABEL
postgres=# insert into Employee(Employee_Name) values('Peter');
INSERT 0 1

postgres=# insert into Employee(Employee_Name) values('Tom');
INSERT 0 1

postgres=# select * FROM Employee;

employee_id   |  Employee_Name
-----------+-------------
EMP0001    |  Peter
EMP0002    |  Tom
Comments