I have to extract quite big chunk of data from database (MYSQL MariaDB) and hereby I decided to take it by small chunks (limit = 1000 rows ). In total I need to extract ~9228 rows (it sounds not much but fetch time reach 100 - 120 seconds when I try to get all 9228 lines at once with one query).
When I fetch first 8 data chunks (1000 rows each), everything is good ~0.4 seconds per query. But when I try to extract the last 228 lines everything goes really slow - 80 seconds if I use LIMIT 1000 OFFSET 9000
or 50 seconds when I use the exact number of rows for LIMIT LIMIT 228 OFFSET 9000
. But the query which is used to get total number of lines takes 30 seconds, so the two queries in total 80 seconds again.
My sql query to get data looks the following:
SELECT events.eventid, functions.triggerid FROM events
INNER JOIN functions ON events.objectid = functions.triggerid
WHERE
events.name LIKE 'DISCONNECT MSK-AP%'
OR events.name LIKE 'AP MSK-AP%' # '%MSK-AP%' is much slower than OR
AND events.value = 1
AND events.clock >= '1588280400'
AND events.clock <= '1590958799'
GROUP BY events.eventid
ORDER BY events.eventid DESC
LIMIT 1000 OFFSET 0; # SO OFFSET COULD BE 0, 1000, 2000, ... 8000, 9000
My sql query to get total number of lines (it is slow 30 seconds!) is as follows:
SELECT COUNT(distinct(events.eventid)) FROM events
INNER JOIN functions ON events.objectid = functions.triggerid
WHERE
events.name LIKE 'DISCONNECT MSK-AP%'
OR events.name LIKE 'AP MSK-AP%'
AND events.value = 1
AND events.clock >= '1588280400'
AND events.clock <= '1590958799';
My Database version:
protocol_version 10
slave_type_conversions
version 5.5.60-MariaDB
version_comment MariaDB Server
version_compile_machine x86_64
version_compile_os Linux
Why the last query to get the last chunk is so slow in comparison with other and what can I do to solve the issue? Can temporary database table help in the case?
Why I am not sure that the answer to question fits my case: Why does MYSQL higher LIMIT offset slow the query down?
Because the problems does not correlate with OFFSET SIZE, e.g. :
LIMIT 100 OFFSET 9100;
- 0.25 seconds BUT
LIMIT 100 OFFSET 9200;
- 114 seconds!
So the problem appears when offset + limit is close or larger than total lines number (9228) !