How to auto-increment in PostgreSQL? [duplicate]
I have a table Login. It has the fields rank, username and password.
I want the rank field value to be auto incremented with respect to addition of username and password.
How do I do this in PostgreSQL ?
You are looking for a column with datatype Serial
. See this page (bottom) for more information about that datatype.
So for example, your table definition could look like this:
CREATE TABLE yourtable (
rank SERIAL NOT NULL,
username VARCHAR(20) NOT NULL,
password VARCHAR(50) NOT NULL
);
A Sequence can be created which will auto increment the value of rank column.
CREATE SEQUENCE rank_id_seq;
CREATE TABLE yourtable (
rank INTEGER NOT NULL default nextval('rank_id_seq'),
username VARCHAR(20) NOT NULL,
password VARCHAR(50) NOT NULL
);
ALTER SEQUENCE rank_id_seq owned by yourtable.rank;
create table login (rank serial, username varchar(20), password varchar(20))
Serial datatype is what you want.
精彩评论