Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL auto increment field on UPDATE (initially is NULL)

Tags:

mysql

Let's say I have a table Order with these fields:

  • ID (PK and with regular auto_increment)
  • payment_date
  • invoice_number

Initially Orders are created with payment_date and invoice_number with NULL values, so I could have these rows:

ID | payment_date | invoice_number
1  |     NULL     |     NULL
2  |   03/10/11   |      1
3  |   03/14/11   |      2
4  |     NULL     |     NULL
5  |     NULL     |     NULL

What I wanna do is when I update a row to fill the payment_date I need to update the invoice_number with the first available invoice_number. For instance, if I update the fifth row, the invoice_number would be '3'.

A first approach would be to SELECT the MAX() value for invoice_number and then add 1 to that value, but that would have concurrency problems, right?.

What do you think would be the best solution?

Thanks in advance!

like image 952
jävi Avatar asked Mar 14 '11 18:03

jävi


People also ask

Does auto increment need not NULL?

You don't have to specify NOT NULL on the column definition with AUTO_INCREMENT . You can leave it off, and MySQL will make the column NOT NULL . And if you specify NULL in place of NOT NULL , MySQL will accept the syntax, but it will ignore that, and make the column NOT NULL anyway.

Why am I getting NULL in MySQL?

In MySQL, a NULL value means unknown. A NULL value is different from zero ( 0 ) or an empty string '' . A NULL value is not equal to anything, even itself. If you compare a NULL value with another NULL value or any other value, the result is NULL because the value of each NULL value is unknown.

What will happen if you insert NULL in an auto increment column that is a NOT NULL primary key column?

When we insert NULL value to AUTO_INCREMENT column, MySQL will return sequence number.

How do you set a field as auto increment in MySQL?

In MySQL, the syntax to change the starting value for an AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = start_value; table_name.


1 Answers

If you want to avoid concurrency problems, you can do this in a transaction or a trigger.

And if you do something like this :

update table
set 
    column = 'something'
    column = (select max(id) + 1 from table)
where id = 123

You won't have concurrency problem either. When you're doing this update, the table is locked, so nobody else can update it while the query is running.

like image 87
krtek Avatar answered Sep 18 '22 22:09

krtek