2

how is possible to insert values in a table except the id(which I've set as a PK) without specifying all the column names?

  • `insert into t values (default, 1, 2, 3 ...)`? – jarlh Jun 13 '18 at 14:23
  • 1
    Possible duplicate of [INSERT INTO ... SELECT without detailing all columns](https://stackoverflow.com/questions/8297484/insert-into-select-without-detailing-all-columns) – Nambu14 Jun 13 '18 at 14:24

1 Answers1

3

If your id is auto-incremented, MySQL will still auto-increment if you insert NULL. So, you can do the following:

create table t (
    id int auto_increment primary key,
    x int
);

insert into t
    select null, 2;

insert into t
    select null, 3;

That said, I recommend (almost) always including all the columns in an insert. So I strongly recommend:

insert into t (x)
    select 2;

insert into t (x)
    select 3;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • 1
    Thanks @Gordon Linoff. Just out of curiosity, why do you recommend, "always include all the columns in an `INSERT`"? – Deepam Gupta Oct 16 '21 at 07:37