I’m adding a field to my table called “room_num”. Basically upon insert I’d like to set the default value of the room_num to be the max value of the last room_num + 1. Obviously I’d use auto-increment if this table applied to only one user but, it will apply to many so I have a running unique index as well as a unique field user_index.
I could run a query based on the user_index and return the max for “room_num” but, since I’m already here, is there a way to make the default value some sort of function?
So, for example my table looks like this:
+-------+-------------+---------+-------------+
| index | room_num | title | user_index |
+-------+-------------+---------+-------------+
| 0 | 0 | Patio | 10 |
+-------+-------------+---------+-------------+
| 1 + 1 | Dining | 10 |
+-------+-------------+---------+-------------+
| 2 + 0 | Bar | 15 |
+-------+-------------+---------+-------------+
| 3 + 2 | Dining | 10 |
+-------+-------------+---------+-------------+
So, now I want the default value for room_num of my next insert for user_index 15 to default to max room_num (0) + 1 (which in this case would be 1). But, I’d like to take care of this here:

Rather than querying for it in my application first and THEN inserting the record and in essence making two database connections.
Is this possible?
Well, you could do something like this:
Obviously, from your application you would just replace
'MyTitle'and the instances of10with your desired title and proper user_index.Note: Based on my five minutes with Google, I don’t think
INSERT...SELECTis an atomic operation. So, you’ll probably want to wrap this in a transaction or table lock/unlock to prevent race conditions.