Question: I have a script that inserts a new user into a table, and the user is defined by the id. I use the id in several other tables to relate certain aspects to that user. For example:

```
USER TABLE
id | phone number

CATEGORY TABLE
id | userID | cat1 | cat2

TRACKING TABLE
id | userID | track1

```

In the three tables above, I use the id from USER TABLE to relate that entry to the userID in the two other tables.

I am attempting to take the newest id (max(id)) from USER TABLE to input default values into the other two tables. For example, when user 3 (id=3, auto\_increment) is added to the USER TABLE through an onboarding process from my home page, and SQL script will take the id number and input it into userID in the other two tables as well as default values for cat1, cat2, and track1. Is there an efficient way to do this with one query or one block of queries that can be sent at once?

Answer: 
Use `last_insert_id()`:

```
insert into usertable ( phone ) values ( '12345' );

set @userid = last_insert_id();

insert into category ( userid, cat1, cat2 )
    values (@userid, 'cat1', 'cat2');

insert into tracking ( userid, track1 )
    values (@userid, 'track1');

```
```
insert into usertable ( phone ) values ( '12345' );
insert into category ( userid, cat1, cat2 ) select u.id , 'cat1', 'cat2' from usertable u where u.phone='12345';
insert into tracking ( userid, track1 ) select id, 'track1' from usertable u where u.phone='12345';

```

You should probably place a unique constraint on the phone field of usertable and wrap these query in a transaction so there is no duplication.