Search code examples
sqldatabasepostgresqlauto-incrementpostgresql-serial

Insert statement asked me to insert for autoincrement column


I use PostgreSQL. I have created the following table:

CREATE TABLE "Task"
(
  "taskID" serial NOT NULL,
  "taskType" text NOT NULL,
  "taskComment" text NOT NULL,
  "taskDate" date NOT NULL,
  CONSTRAINT "Task_pkey" PRIMARY KEY ("taskID")
)

I put taskID as serial data-type to be incremented automatically. Now I'm confused how to use the INSERT statement, as the first column in the table is supposed to increment automatically but INSERT statement asked me to insert a value by myself! Any Idea?

Here is my insert statement:

INSERT INTO "Task" VALUES ('HomeWork', 'No Comment', '3/3/2013');

Solution

  • @mvp's answer covers this pretty much. Except for the case where you (have to) add the auto-incremented column in the column list for some reason. Then you can use the key word DEFAULT to default to the defined default value.

    INSERT INTO "Task"("taskID", "taskType", "taskComment", "taskDate")
    VALUES (DEFAULT, 'HomeWork', 'No Comment', '2013-03-03');
    

    Also, use ISO 8601 date format (YYYY-MM-DD), which works independent of locale settings. Your regionally valid format is prone to breakage.


    However, if you distance yourself from the folly of mixed case identifiers, living with Postgres becomes much easier:

    CREATE TABLE task (
      task_id serial NOT NULL PRIMARY KEY,
      task_type text NOT NULL,
      task_comment text NOT NULL,
      task_date date NOT NULL
    );
    
    INSERT INTO task
    VALUES (DEFAULT, 'HomeWork', 'No Comment', '2013-03-03');
    

    Or better:

    INSERT INTO task (task_type, task_comment, task_date)
    VALUES ('HomeWork', 'No Comment', '2013-03-03');