Search code examples
mysqlperformanceoptimizationpdolastinsertid

Fastest way to insert, if not exist, then get id in MySQL


There's this table.

| id | domain |

id is the primary key. domain is a unique key.

I want to:

  1. Insert a new domain, if it doesn't exist already.
  2. Get the id for that domain.

Now I'm doing it like this:

INSERT INTO domains
SET domain = 'exemple.com'
ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)

Then PDO::lastInsertId() to get the id.

But it's critical that this is as fast as it could, so I though I'd ask: Can I do this in a better way?


Solution

  • Until someone says otherwise, I'm saying No, that's the best way.