[Solved] is there a defined order for processing SQL IN lists?

EverSQL Database Performance Knowledge Base

is there a defined order for processing SQL IN lists?

Everybody knows that if one process goes

  SELECT id FROM dead WHERE id = 'A' FOR UPDATE;
  SELECT id FROM dead WHERE id = 'B' FOR UPDATE;

and another goes

SELECT id FROM dead WHERE id = 'B' FOR UPDATE;
SELECT id FROM dead WHERE id = 'A' FOR UPDATE;

then you risk deadlock. I would rather assume that

SELECT id FROM dead WHERE id IN ('A', 'B') FOR UPDATE;

will deadlock against

SELECT id FROM dead WHERE id IN ('B', 'A') FOR UPDATE;

but is the order of locking the IN list defined -- which of those will deadlock against my single-select process?

More precisely, if I have an alphabetic locking order convention then can I safely merge lock A and lock B into one SQL statement (given that slow networks might make reducing the number of network trips to the database a good thing).

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `dead` ADD INDEX `dead_idx_id` (`id`);
The optimized query:
SELECT
        dead.id 
    FROM
        dead 
    WHERE
        dead.id IN (
            'A', 'B'
        ) FOR UPDATE

Related Articles



* original question posted on StackOverflow here.