Search code examples
postgresqlauto-increment

What's the PostgreSQL datatype equivalent to MySQL AUTO INCREMENT?


I'm switching from MySQL to PostgreSQL and I was wondering how can I have an INT column with AUTO INCREMENT. I saw in the PostgreSQL docs a datatype called SERIAL, but I get syntax errors when using it.


Solution

  • Yes, SERIAL is the equivalent function.

    CREATE TABLE foo (
        id SERIAL,
        bar varchar
    );
    
    INSERT INTO foo (bar) VALUES ('blah');
    INSERT INTO foo (bar) VALUES ('blah');
    
    SELECT * FROM foo;
    
    +----------+
    | 1 | blah |
    +----------+
    | 2 | blah |
    +----------+
    

    SERIAL is just a create table time macro around sequences. You can not alter SERIAL onto an existing column.