[Solved] How to find the repeat value in a mysql table with 30 million rows

EverSQL Database Performance Knowledge Base

How to find the repeat value in a mysql table with 30 million rows

Database type:

In Mysql, I have a table with two columns (id, uuid). Then I inserted 30 million values into it. (ps: the uuid can repeated)

Now, I want to find the repeat value in the table by using Mysql grammar, but the sql spent too much time.

I want to search all columns, but it takes much time, so I tried querying first million rows, the it spent 8 seconds.

Then I tried with 10 million rows, it spend 5mins, then with 20 million rows, the server seem died.

select count(uuid) as cnt
from uuid_test
where id between 1
and 1000000
group by uuid having cnt > 1;

Anyone can help me to optimized the sql, thanks

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.
  2. Explicitly ORDER BY After GROUP BY (modified query below): By default, the database sorts all 'GROUP BY col1, col2, ...' queries as if you specified 'ORDER BY col1, col2, ...' in the query as well. If a query includes a GROUP BY clause but you want to avoid the overhead of sorting the result, you can suppress sorting by specifying 'ORDER BY NULL'.
Optimal indexes for this query:
ALTER TABLE `uuid_test` ADD INDEX `uuid_test_idx_id` (`id`);
ALTER TABLE `uuid_test` ADD INDEX `uuid_test_idx_uuid` (`uuid`);
The optimized query:
SELECT
        count(uuid_test.uuid) AS cnt 
    FROM
        uuid_test 
    WHERE
        uuid_test.id BETWEEN 1 AND 1000000 
    GROUP BY
        uuid_test.uuid 
    HAVING
        cnt > 1 
    ORDER BY
        NULL

Related Articles



* original question posted on StackOverflow here.