Get the latest inserted id in a trigger?

0 votes
asked Feb 15, 2010 by ajsie

I use a trigger to insert a row and want to use the last created id for using in the subsequent query.

How could I do this?

The code looks like:

BEGIN
IF (NEW.counter >= 100) THEN
INSERT INTO tagCategories (name, counter) VALUES ('unnamed', NEW.counter);
// here i want to have access to the above inserted id
UPDATE tagCategories2tagPairs SET tagCategoryId = <<ID_HERE>> WHERE tagPairId = OLD.id
END IF;
END

4 Answers

0 votes
answered Feb 15, 2010 by mitch-wheat

Have you looked at LAST_INSERT_ID()? But be aware:

If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only.

0 votes
answered Feb 4, 2013 by darkhan-zd

USE NEW.id

BEGIN
insert INTO test_questions (test_id, question, variant1, variant2, variant3, w1, type_id) 
SELECT NEW.id, t1.question, t1.v1, t1.v2, t1.v3, t1.answer, 1
FROM new_minitest_questions t1
WHERE t1.mt_id = NEW.old_id;
END
0 votes
answered Feb 13, 2013 by user2679455

I wanted to use a company initials like "AAA" and add the insert ID to it and use it as a internal company ID and this is how I picked up the last current insert ID

DELIMITER //
CREATE TRIGGER company_run_before_insert BEFORE INSERT ON ap_company 
FOR EACH ROW
BEGIN

SET @lastID = (SELECT id FROM ap_company ORDER BY id DESC LIMIT 1);
IF @lastID IS NULL OR @lastID = '' THEN
    SET @lastID = 0;
END IF;
SET @lastID = @lastID +1;
SET NEW.ap_company_id = concat(NEW.company_initials,'-', @lastID);
END;
0 votes
answered Jan 16, 2016 by user3785966

Following trigger will get the last Auto Increment value from the Information Schema. I had written this trigger to generate a slug.

For instances, if the column's name is "Name" and column has a value such as "Robin Shankar", the trigger would replace spaces with "-" and also append the Auto Increment Id to the end of the slug, hence making a unique slug.

robin_shankar_9071

DELIMITER //
CREATE TRIGGER insert_slug_sd
BEFORE INSERT ON `your_table_name`
FOR EACH ROW
BEGIN

DECLARE auto_increment_ INT(11);

SELECT 
    `auto_increment` 
INTO 
    auto_increment_
FROM INFORMATION_SCHEMA.TABLES
    WHERE 
table_name = 'your_table_name';

SET NEW.`Slug` = CONCAT(LOWER(REPLACE(NEW.`Name`,' ','-')),'-',auto_increment_);
END; //

DELIMITER;
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...