I have two MySQL tables like this:
User
Id (PK, auto-increment integer)
Subscriber
Id (PK, auto-increment integer)
OwnerId (FK to User.Id)
Name
Since I am making queries on the PK, is there a performance difference between these two:
UPDATE Subscriber SET Name = 'John' WHERE Id = 20;
UPDATE Subscriber SET Name = 'John' WHERE Id = 20 and OwnerId = 50;
Ideally I’d like to also pass the OwnerId as an extra precaution (it’s a multi-tenant application). Is this necessary?
In terms of performance (assuming I keep the WHERE conditions in order – with the PK first) how can I benchmark this, or see the execution plan on MySQL – are there any performance optimizations the engine makes that I should be aware of? Thanks!
While it is not necessary to add an additional filter, there is a difference.
Subscriber.Idis the primary key, therefore it has unique values and the clauseWHERE Id = 20can only ever select one single row.The only possible effect of the additional clause
AND OwnerId = 50in this example can be to prohibit the UPDATE, if50should not be the value ofSubscriber.OwnerIdin the same row.While this is hardly relevant for performance (primary key is indexed, index search will return a single row in either case), it also does not make an awful lot of sense for most use cases.
You can test the execution with EXPLAIN. More info in the manual.