How do auto increment in Mysql without declaring columns in INSERT?

Asked

Viewed 1,137 times

2

I noticed that when I have a column with auto_increment, I have to declare the columns on INSERT.

For example, I created this test table:

create table teste(
id int auto_increment,
nome varchar(100) not null,
valor decimal(5,2),
constraint id_pk primary key (id));

I wanted to be able to enter the data without declaring the columns, as in this example:

insert into teste values ('Danilo',333.33)

But he does not understand, and in the end I have to declare so:

insert into teste (nome,valor) values ('Danilo',333.33)

My question is whether I can make one INSERT without declaring all columns, like using a reserved word or something that Mysql understands.

  • If you are adding values to all table columns, you do not need to specify column names in the query. However, make sure the order of the values is in the same order as the columns in the table.

  • Insert into test values (','Danilo',333.33)

1 answer

2


Since you are using a positional syntax with all columns you have to send values to all columns. And since you do not want to send to the first column, send a null. Since it has an automatic default value this value will be placed in place of the null.

insert into teste values (null, 'Danilo',333.33)

Behold working in the SQL Fiddle. Also put on the Github for future reference.

If you find it bad there the output is the one you already found, use the syntax of named arguments not to consider the position of each column.

  • You have to answer more difficult questions, these ticos-ticos have to leave for us rs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.