MySQL innodb seeks vs. contiguous reads tradeoff - mysql

Would mysql (innodb) support a higher rate (queries per second) of queries like (A) or (B)?
(A) SELECT * FROM t1 WHERE pkey BETWEEN 2000 and 2001 AND x > 300
In (A), the primary key selects a range of 800 rows. "x" is unindexed. there's one range lookup and 1 contiguous read of length 200kb.
(B) (SELECT * FROM t1 WHERE pkey BETWEEN 2000 and 2001 AND x > 300) UNION ALL (SELECT * FROM t1 WHERE pkey BETWEEN 3000 and 3001 AND x > 300)
In (B), the primary key selects a range of 200 rows. "x" is unindexed. there are two range lookups and 2 contiguous reads of length 50kb.
So to sum up, (A) has 2x the disk seeks, but 1/2th as much contiguous reading. Conversely, (B) has half the disk seeks but 2x as much contiguous reading.
In general I assume seeks are slow and contiguous reads are fast, but I assume that one extra seek is preferable to reading through 10MB of extra data. Where's the tradeoff point, roughly?

The optimiser should make the decision about how to implement the query. Just write it how you want it.
Use EXPLAIN to see roughly what it's done. It may be that it does two range scans on the index on pkey.
In general reading fewer rows is better. You can also keep more of them in the buffer pool. Two range scans is better than one in the general case.
I am assuming that your table t1 will not fit in memory entirely, in which case it's mostly academic.

You really need to supplement your two options with the output from EXPLAIN... it doesn't just matter which is theoretically faster, it matters what optimizations MySQL is going to have available.
Let me guess for you:
a) The ranged pkey lookup is very efficient because it's on a clustered index. For everything that is in the range it reads "next, next next" to check if X matches.
b) This is a series of point lookups. But it creates a temporary table even though you think it could pipeline the results to you(!) http://www.facebook.com/note.php?note_id=276225210932
My vote is almost certainly (a).

Related

A SQL query searching for rows that satisfy Column1 <= X <= Column2 is very slow

I am using a MySQL DB, and have the following table:
CREATE TABLE SomeTable (
PrimaryKeyCol BIGINT(20) NOT NULL,
A BIGINT(20) NOT NULL,
FirstX INT(11) NOT NULL,
LastX INT(11) NOT NULL,
P INT(11) NOT NULL,
Y INT(11) NOT NULL,
Z INT(11) NOT NULL,
B BIGINT(20) DEFAULT NULL,
PRIMARY KEY (PrimaryKeyCol),
UNIQUE KEY FirstLastXPriority_Index (FirstX,LastX,P)
) ENGINE=InnoDB;
The table contains 4.3 million rows, and never changes once initialized.
The important columns of this table are FirstX, LastX, Y, Z and P.
As you can see, I have a unique index on the rows FirstX, LastX and P.
The columns FirstX and LastX define a range of integers.
The query I need to run on this table fetches for a given X all the rows having FirstX <= X <= LastX (i.e. all the rows whose range contains the input number X).
For example, if the table contains the rows (I'm including only the relevant columns):
FirstX
LastX
P
Y
Z
100000
500000
1
111
222
150000
220000
2
333
444
180000
190000
3
555
666
550000
660000
4
777
888
700000
900000
5
999
111
750000
850000
6
222
333
and I need, for example, the rows that contain the value 185000, the first 3 rows should be returned.
The query I tried, which should be using the index, is:
SELECT P, Y, Z FROM SomeTable WHERE FirstX <= ? AND LastX >= ? LIMIT 10;
Even without the LIMIT, this query should return a small number of records (less than 50) for any given X.
This query was executed by a Java application for 120000 values of X. To my surprise, it took over 10 hours (!) and the average time per query was 0.3 seconds.
This is not acceptable, not even near acceptable. It should be much faster.
I examined a single query that took 0.563 seconds to make sure the index was being used. The query I tried (the same as the query above with a specific integer value instead of ?) returned 2 rows.
I used EXPLAIN to find out what was happening:
id 1
select_type SIMPLE
table SomeTable
type range
possible_keys FirstLastXPriority_Index
key FirstLastXPriority_Index
key_len 4
ref NULL
rows 2104820
Extra Using index condition
As you can see, the execution involved 2104820 rows (nearly 50% of the rows of the table), even though only 2 rows satisfy the conditions, so half of the index is examined in order to return just 2 rows.
Is there something wrong with the query or the index? Can you suggest an improvement to the query or the index?
EDIT:
Some answers suggested that I run the query in batches for multiple values of X. I can't do that, since I run this query in real time, as inputs arrive to my application. Each time an input X arrives, I must execute the query for X and perform some processing on the output of the query.
I found a solution that relies on properties of the data in the table. I would rather have a more general solution that doesn't depend on the current data, but for the time being that's the best I have.
The problem with the original query:
SELECT P, Y, Z FROM SomeTable WHERE FirstX <= ? AND LastX >= ? LIMIT 10;
is that the execution may require scanning a large percentage of the entries in the FirstX,LastX,P index when the first condition FirstX <= ? is satisfied by a large percentage of the rows.
What I did to reduce the execution time is observe that LastX-FirstX is relatively small.
I ran the query:
SELECT MAX(LastX-FirstX) FROM SomeTable;
and got 4200000.
This means that FirstX >= LastX – 4200000 for all the rows in the table.
So in order to satisfy LastX >= ?, we must also satisfy FirstX >= ? – 4200000.
So we can add a condition to the query as follows:
SELECT P, Y, Z FROM SomeTable WHERE FirstX <= ? AND FirstX >= ? - 4200000 AND LastX >= ? LIMIT 10;
In the example I tested in the question, the number of index entries processed was reduced from 2104820 to 18 and the running time was reduced from 0.563 seconds to 0.0003 seconds.
I tested the new query with the same 120000 values of X. The output was identical to the old query. The time went down from over 10 hours to 5.5 minutes, which is over 100 times faster.
WHERE col1 < ... AND ... < col2 is virtually impossible to optimize.
Any useful query will involve a "range" on either col1 or col2. Two ranges (on two different columns) cannot be used in a single INDEX.
Therefore, any index you try has the risk of checking a lot of the table:
INDEX(col1, ...) will scan from the start to where col1 hits .... Similarly for col2 and scanning until the end.
To add to your woes, the ranges are overlapping. So, you can't pull a fast one and add ORDER BY ... LIMIT 1 to stop quickly. And if you say LIMIT 10, but there are only 9, it won't stop until the start/end of the table.
One simple thing you can do (but it won't speed things up by much) is to swap the PRIMARY KEY and the UNIQUE. This could help because InnoDB "clusters" the PK with the data.
If the ranges did not overlap, I would point you at http://mysql.rjweb.org/doc.php/ipranges .
So, what can be done?? How "even" and "small" are the ranges? If they are reasonably 'nice', then the following would take some code, but should be a lot faster. (In your example, 100000 500000 is pretty ugly, as you will see in a minute.)
Define buckets to be, say, floor(number/100). Then build a table that correlates buckets and ranges. Samples:
FirstX LastX Bucket
123411 123488 1234
222222 222444 2222
222222 222444 2223
222222 222444 2224
222411 222477 2224
Notice how some ranges 'belong' to multiple buckets.
Then, the search is first on the bucket(s) in the query, then on the details. Looking for X=222433 would find two rows with bucket=2224, then decide that both are OK. But for X=222466, two rows have the bucket, but only one matches with firstX and lastX.
WHERE bucket = FLOOR(X/100)
AND firstX <= X
AND X <= lastX
with
INDEX(bucket, firstX)
But... with 100000 500000, there would be 4001 rows because this range is in that many 'buckets'.
Plan B (to tackle the wide ranges)
Segregate the ranges into wide and narrow. Do the wide ranges by a simple table scan, do the narrow ranges via my bucket method. UNION ALL the results together. Hopefully the "wide" table would much smaller than the "narrow" table.
You need to add another index on LastX.
The unique index FirstLastXPriority_Index (FirstX,LastX,P) represents the concatenation of these values, so it will be useless with the 'AND LastX >= ?' part of your WHERE clause.
It seems that the only way to make the query fast is to reduce the number of fetched and compared fields. Here is the idea.
We can declare a new indexed field (for instance UNSIGNED BIGINT) and store both values FistX and LastX in it using an offset for one of the fields.
For example:
FirstX LastX CombinedX
100000 500000 100000500000
150000 220000 150000220000
180000 190000 180000190000
550000 660000 550000660000
70000 90000 070000090000
75 85 000075000085
an alternative is to declare the field as DECIMAL and store FirstX + LastX / MAX(LastX) in it.
Later look for the values satisfying the conditions comparing the values with a single field CombinedX.
APPENDED
And then you can fetch the rows checking only one field:
by something like where param1=160000
SELECT * FROM new_table
WHERE
(CombinedX <= 160000*1000000) AND
(CombinedX % 1000000 >= 160000);
Here I assume that for all FistX < LastX. Of course, you can calculate the param1*offset in advance and store it in a variable against which the further comparisons will be done. Of course, you can consider not decimal offsets but bitwise shifts instead. Decimal offsets were chosen as they are easier to read by a human to show in the sample.
Eran, I believe the solution you found youself is the best in terms of minimum costs. It is normal to take into account distribution properties of the data in the DB during optimization process. Moreover, in large systems, it is usually impossible to achieve satisfactory performance, if the nature of the data is not taken into account.
However, this solution also has drawbacks. And the need to change the configuration parameter with every data change is the least. More important may be the following. Let's suppose that one day a very large range appears in the table. For example, let its length cover half of all possible values. I do not know the nature of ​​your data, so I can not definitely know if such a range can ever appear or not, so this is just an assumption. From the point of view to the result, it's okay. It just means that about every second query will now return one more record. But even just one such interval will completely kill your optimization, because the condition FirstX <=? AND FirstX> =? - [MAX (LastX-FirstX)] will no longer effectively cut off enough records.
Therefore, if you do not have assurance if too long ranges will ever come, I would suggest you to keep the same idea, but take it from other side.
I propose, when loading new data to the table, break all long ranges into smaller with a length not exceeding a certain value. You wrote that The important columns of this table are FirstX, LastX, Y, Z and P. So you can once choose some number N, and every time loading data to the table, if found the range with LastX-FirstX > N, to replace it with several rows:
FirstX; FirstX + N
FirstX + N; FirstX + 2N
...
FirstX + kN; LastX
and for the each row, keep the same values ​​of Y, Z and P.
For the data prepared that way, your query will always be the same:
SELECT P, Y, Z FROM SomeTable WHERE FirstX <=? AND FirstX> =? - N AND LastX> =?
and will always be equally effective.
Now, how to choose the best value for N? I would take some experiments with different values and see what would be better. And it is possible for the optimum to be less than the current maximum length of the interval 4200000. At first it could surprise one, because the lessening of N is surely followed by growth of the table so it can become much larger than 4.3 million. But in fact, the huge size of the table is not a problem, when your query uses the index well enough. And in this case with lessening of N, the index will be used more and more efficiently.
Indexes will not help you in this scenario, except for a small percentage of all possible values of X.
Lets say for example that:
FirstX contains values from 1 to 1000 evenly distributed
LastX contains values from 1 to 1042 evenly distributed
And you have following indexes:
FirstX, LastX, <covering columns>
LastX, FirstX, <covering columns>
Now:
If X is 50 the clause FirstX <= 50 matches approximately 5% rows while LastX >= 50 matches approximately 95% rows. MySQL will use the first index.
If X is 990 the clause FirstX <= 990 matches approximately 99% rows while LastX >= 990 matches approximately 5% rows. MySQL will use the second index.
Any X between these two will cause MySQL to not use either index (I don't know the exact threshold but 5% worked in my tests). Even if MySQL uses the index, there are just too many matches and the index will most likely be used for covering instead of seeking.
Your solution is the best. What you are doing is defining upper and lower bound of "range" search:
WHERE FirstX <= 500 -- 500 is the middle (worst case) value
AND FirstX >= 500 - 42 -- range matches approximately 4.3% rows
AND ...
In theory, this should work even if you search FirstX for values in the middle. Having said that, you got lucky with 4200000 value; possibly because the maximum difference between first and last is a smaller percentage.
If it helps, you can do the following after loading the data:
ALTER TABLE testdata ADD COLUMN delta INT NOT NULL;
UPDATE testdata SET delta = LastX - FirstX;
ALTER TABLE testdata ADD INDEX delta (delta);
This makes selecting MAX(LastX - FirstX) easier.
I tested MySQL SPATIAL INDEXES which could be used in this scenario. Unfortunately I found that spatial indexes were slower and have many constraints.
Edit: Idea #2
Do you have control over the Java app? Because, honestly, 0.3 seconds for an index scan is not bad. Your problem is that you're trying to get a query, run 120,000 times, to have a reasonable end time.
If you do have control over the Java app, you could either have it submit all the X values at once - and let SQL not have to do an index scan 120k times. Or you could even just program the logic on the Java side, since it would be relatively easy to optimize.
Original Idea:
Have you tried creating a Multiple-Column index?
The problem with having multiple indexes is that each index is only going to narrow it down to ~50% of the records - it has to then match those ~2 million rows of Index A against ~2 million rows of Index B.
Instead, if you get both columns in the same index, the SQL engine can first do a Seek operation to get to the start of the records, and then do a single Index Scan to get the list of records it needs. No matching one index against another.
I'd suggest not making this the Clustered Index, though. The reason for that? You're not expecting many results, so matching the Index Scan's results against the table isn't going to be time consuming. Instead, you want to make the Index as small as possible, so that the Index Scan goes as fast as possible. Clustered Indexes are the table - so a Clustered Index is going to have the same Scan speed as the table itself. Along the same lines, you probably don't want any other fields other than FirstX and LastX in your index - make that Index as tiny as you can, so that the scan flies along.
Finally, like you're doing now, you're going to need to clue the engine in that you're not expecting a large set of data back from the search - you want to make sure it's using that compact Index for its scan (instead of it saying, "Eh, I'd be better off just doing a full table scan.)
One way might be to partition the table by different ranges then only querying stuff that fit into a range hence making the amount it needs to check much smaller. This might not work since the java may be slower. But it might put less stress on the database.
There might be a way also to not Query the database so many times and have a more inclusive SQL(you might be able to send a list of values and have the sql send it to a different table).
Suppose you got the execution time down to 0.1 seconds. Would the resulting 3 hours, twenty minutes be acceptable?
The simple fact is that thousands of calls to the same query is incredibly inefficient. Quite aside from what the database has to endure, there is network traffic to think of, disk seek times and all kinds of processing overhead.
Supposing that you don't already have the 120,000 values for x in a table, that's where I would start. I would insert them into a table in batches of 500 or so at a time:
insert into xvalues (x)
select 14 union all
select 18 union all
select 42 /* and so on */
Then, change your query to join to xvalues.
I reckon that optimisation alone will get your run-time down to minutes or seconds instead of hours (based on many such optimisations I have done through the years).
It also opens up the door for further optimisations. If the x values are likely to have at least some duplicates (say, at least 20% of values occur more than once) it may be worth investigating a solution where you only run the query for unique values and do the insert into SomeTable for every x with the matching value.
As a rule: anything you can do in bulk is likely to exponentially outperform anything you do row by row.
PS:
You referred to a query, but a stored procedure can also work with an input table. In some RDBMSs you can pass a table as parameter. I don't think that works in MySQL, but you can create a temporary table that the calling code fills in and the stored procedure joins to. Or a permanent table used in the same way. The major drawback of not using a temp table, is that you may need to concern yourself with session management or discarding stale data. Only you will know if that is applicable to your case.
So, I dont have enough data to be sure of the run time. This will only work if column P is unique? In order to get two indexes working, I created two indexes and the following query...
Index A - FirstX, P, Y, Z
Index B - P, LastX
This is the query
select A.P, A.Y, A.Z
from
(select P, Y, Z from asdf A where A.firstx <= 185000 ) A
join
(select P from asdf A where A.LastX >= 185000 ) B
ON A.P = B.P
For some reason this seemed faster than
select A.P, A.Y, A.Z
from asdf A join asdf B on A.P = B.P
where A.firstx <= 185000 and B.LastX >= 185000
To optimize this query:
SELECT P, Y, Z FROM SomeTable WHERE FirstX <= ? AND LastX >= ? LIMIT 10;
Here's 2 resources you can use:
descending indexes
spatial indexes
Descending indexes:
One option is to use an index that is descending on FirstX and ascending on LastX.
https://dev.mysql.com/doc/refman/8.0/en/descending-indexes.html
something like:
CREATE INDEX SomeIndex on SomeTable (FirstX DESC, LastX);
Conversely, you could create instead the index (LastX, FirstX DESC).
Spatial indexes:
Another option is to use a SPATIAL INDEX with (FirstX, LastX). If you think of FirstX and LastX as 2D spatial coordinates, then your search what it does is select the points in a contiguous geographic area delimited by the lines FirstX<=LastX, FirstX>=0, LastX>=X.
Here's a link on spatial indexes (not specific to MySQL, but with drawings):
https://learn.microsoft.com/en-us/sql/relational-databases/spatial/spatial-indexes-overview
Another approach is to precalculate the solutions, if that number isn't too big.
CREATE TABLE SomeTableLookUp (
X INT NOT NULL
PrimaryKeyCol BIGINT NOT NULL,
PRIMARY KEY(X, PrimaryKeyCol)
);
And now you just pre-populate your constant table.
INSERT INTO SomeTableLookUp
SELECT X, PrimaryKeyCol
FROM SomeTable
JOIN (
SELECT DISTINCT X FROM SomeTable
) XS
WHERE XS.X BETWEEN StartX AND EndX
And now you can SELECT your answers directly.
SELECT SomeTable.*
FROM SomeTableLookup
JOIN SomeTable
ON SomeTableLookup.PrimaryKeyCol = SomeTable.PrimaryKeyCol
WHERE SomeTableLookup = ?
LIMIT 10

Mysql Large Table Join Query very slow not Key indexes issue

SELECT t1.*
FROM
( SELECT key_a,key_b,MAX(date) as date
FROM large_table
WHERE date <= **20150126**
group by key_a,key_b
) AS t2
JOIN large_table AS t1 USING(key_a,key_b ,date)
large_table = 1,223,001,206 rows of data
Primary Key key_a,key_b,date
key on key_b
key on date
There are numerous empty dates between rows for a & b that I want the most recent behind or on the "Date" entered.
Is it the Mysql Join settings causing it to be slow ?
I can copy the entire set of a & b data with an INSERT to a temp table just by selecting all the rows and then run the same query on the temp table, but why do multi queries (insert selected, then select from) when only 1 is needed.
The query above only has 4,128,548 total results in the temp insert all dates table, and the date specific returns under 180,000 total.
Not table optimization, not keys, is it Max sort length, Join Buffer size , I have 128 gig ram, on a 32 core server running this, there is no reason for it to be slow, just never bulk insert this large of a single table to run Join queries on prior if anyone else has dealt with tables this size any info greatly appreciated.
Edited query, yes it's late long day had Distinct when it wasn't needed or in actual query
WHERE date <= **20150126**
group by key_a,key_b
needs an index starting with date. It's about doing what you can with the WHERE clause, not sparse or dense.
Then... Since the inner query references only 3 columns, building a 'covering' index may be useful. (Probably useful in your case.) So, tack on the other two fields, in either order. Such as
INDEX(`date`, key_a, key_b)
For MyISAM this step is critical. For InnoDB, this is redundant, since each secondary key (such as your INDEX(date)) implicitly includes the rest of the fields of the PK.
No, the PRIMARY KEY(key_a, key_b, date) cannot serve the purpose. It's in the wrong order. Also, it is (if you are using InnoDB) "clustered" with the index.
The query above only has 4,128,548 total results in the temp insert all dates table, and the date specific returns under 180,000 total.
Sorry, I had trouble parsing that. I assume you are saying 4M rows had 'date<...' and the subquery delivered only 180K rows. Hence, the outer query also returned 180K rows.
The first goal is to get through the 4M rows as efficiently as possible. With the index I propose, that might be about 20K blocks (#16KB each) of index scanning. That's 300MB.
Next the MAX and GROUP BY are performed. At 300MB, this will involve a disk tmp table. (See max_heap_size and max_tmp_table_size.)
Then comes the JOIN to fetch t1.*. You are using a good technique for fetching a bunch of rows from a huge table, where you need a GROUP BY (or LIMIT or ...) that is clumsy when done the obvious way. It goes like this: Write the subquery to find the PKs. Get the best index for it. Then JOIN on the PK.
Now for the JOIN. (Again, I assume InnoDB.) Since you are JOINing on the PK, each lookup into t1 will be efficient -- drill down the PK's BTree to find a row. Do that 180K times.
If those 180K lookups are scattered around the table, then this could be 180K disk hits.
Total effort: 20K + 180K = 200K disk hits, possibly less. On commodity spinning disks, this would take about 30 minutes (plus time for the tmp table). (No, only one core will be used. Anyway, I/O is probably the bottleneck.)
OPTIMIZE TABLE -- almost always useless.
I assume innodb_buffer_pool_size is about 90G? If things are going to be cached, that is where it would happen (for InnoDB). Since 200K blocks is 3GB, it could be easily cached. That is, if you run the query twice, the first might be 30 minutes, but the second might be less than 3 minutes.
To get more numbers, you could do:
FLUSH STATUS;
SELECT ...;
SHOW SESSION STATUS;
and look for 'Handler%', '%sort%', 'Innodb%' and maybe a few others.
What version are you running? Recent versions have a leapfrog technique that works better for max+groupby than what I described. I think it is called MRR. If so, your PK is actually optimal. (Hmmm... I should play around with that.)
PARTITIONing -- I don't see any benefit (for this query).

Function of deferred join in MySQL

I am reading High performance MySQL and I am a little confused about deferred join.
The book says that the following operation cannot be optimized by index(sex, rating) because the high offset requires them to spend most of their time scanning a lot of data that they will then throw away.
mysql> SELECT <cols> FROM profiles WHERE sex='M' ORDER BY rating LIMIT 100000, 10;
While a deferred join helps minimize the amount of work MySQL must do gathering data that it will only throw away.
SELECT <cols> FROM profiles INNER JOIN (
SELECT <primary key cols> FROM profiles
WHERE x.sex='M' ORDER BY rating LIMIT 100000, 10
) AS x USING(<primary key cols>);
Why a deferred join will minimize the amount of gathered data.
The example you presented assumes that InnoDB is used. Let's say that the PRIMARY KEY is just id.
INDEX(sex, rating)
is a "secondary key". Every secondary key (in InnoDB) includes the PK implicitly, so it is really an ordered list of (sex, rating, id) values. To get to the "data" (<cols>), it uses id to drill down the PK BTree (which contains the data, too) to find the record.
Fast Case: Hence,
SELECT id FROM profiles
WHERE x.sex='M' ORDER BY rating LIMIT 100000, 10
will do a "range scan" of 100010 'rows' in the index. This will be quite efficient for I/O, since all the information is consecutive, and nothing is wasted. (No, it is not smart enough to jump over 100000 rows; that would be quite messy, especially when you factor in the transaction_isolation_mode.) Those 100010 rows probably fit in about 1000 blocks of the index. Then it gets the 10 values of id.
With those 10 ids, it can do 10 joins ("NLJ" = "Nested Loop Join"). It is rather likely that the 10 rows are scattered around the table, possibly requiring 10 hits to the disk.
Let's "count the disk hits" (ignoring non-leaf nodes in the BTrees, which are likely to be cached anyway): 1000 + 10 = 1010. On ordinary disks, this might take 10 seconds.
Slow Case: Now let's look at the original query (SELECT <cols> FROM profiles WHERE sex='M' ORDER BY rating LIMIT 100000, 10;). Let's continue to assume INDEX(sex, rating) plus the implicit id on the end.
As before, it will index scan through the 100010 rows (est. 1000 disk hits). But as it goes, it is too dumb to do what was done above. It will reach over into the data to get the <cols>. This often (depending on caching) requires a random disk hit. This could be upwards of 100010 disk hits (if the table is huge and caching is not very useful).
Again, 100000 are tossed and 10 are delivered. Total 'cost': 100010 disk hits (worst case), which might take 17 minutes.
Keep in mind that there are 3 editions of High performance MySQL; they were written over the past 13 or so years. You are probably using a much newer version of MySQL than they covered. I do not happen to know if the optimizer has gotten any smarter in this area. These, if available to you, may give clues:
EXPLAIN FORMAT=JSON SELECT ...;
OPTIMIZER TRACE...
My favorite "Handler" trick for studying how things work may be helpful:
FLUSH STATUS;
SELECT ...
SHOW SESSION STATUS LIKE 'Handler%'.
You are likely to see numbers like 100000 and 10, or small multiples of such. But, keep in mind that a fast range scan of the index counts as 1 per row, and so does a slow random disk hit for a big set of <cols>.
Overview: To make this technique work, the subquery need a "covering" index, with the columns correctly ordered.
"Covering" means that (sex, rating, id) contains all the columns touched. (We are assuming that <cols> contains other columns, perhaps bulky ones that won't work in an INDEX.)
"Correct" ordering of the columns: The columns are in just the right order to get all the way through the query. (See also my cookbook.)
First come any WHERE columns compared with = to constants. (sex)
Then comes the entire ORDER BY, in order. (rating)
Finally it is 'covering'. (id)
From the description below from official (https://dev.mysql.com/doc/refman/5.7/en/limit-optimization.html):
If you combine LIMIT row_count with ORDER BY, MySQL stops sorting as soon as it has found the first row_count rows of the sorted result, rather than sorting the entire result. If ordering is done by using an index, this is very fast. If a filesort must be done, all rows that match the query without the LIMIT clause are selected, and most or all of them are sorted, before the first row_count are found. After the initial rows have been found, MySQL does not sort any remainder of the result set.
We can see that they should have no difference.
But the percona suggest this, and give test data. But give no reason, I think there maybe exist some "bug" in mysql when deal with this kind of case. So we just regard this as a useful experience.

Find rows for interval in MySQL

SO,
The problem
I have a very simple - at first glance - problem. Assuming that I have data set with two meaningful columns: from and till. This data set isn't yet in DB. I need to search through this data set and for some X find rows where condition from < X < till is true. For example, I have rows (id added just for identifying rows, it doesn't mean that rows are in DB):
id from till
------------
1 100 200
2 120 200
3 1000 1050
4 1100 1500
and I want to find rows for X = 125. That will be rows # 1 and 2. I.e. intervals may intersect, but they are always correct (from is always lesser than till). Also, strict condition is that all three: from, till and X are unsigned integers. Besides, with high probability, intervals will not be nested too heavily - so, if intersection would be, it will not be a case, when, for example, some interval is nested to all others (practically that means that certain interval is a reliable condition which will not mean full table)
Moving to the deal. My data set could be huge (around ~500.000.000 rows) - and I need to store it somehow in DB. There is no restrictions for DB structure - it can be anything, I'm free to chose proper solution (that it why my data set is not in DB yet). So, problem is - how to store that in DB to make querying rows for given X as fast as possible?
My approach
At first glance - it's very simple. We just create columns for from and till, filling them with our data set and here we are. Really? Not. Why? Because such table structure will not allow to build any good index for using it in query. If we'll create index on two columns (from, till) it will have no sense in terms of our problem - and if we'll create two separate indexes on two columns from and till - they will both have low selectivity. Why? Imagine that we have row with from = 100.000.000 and till = 100.000.200. Then querying WHERE 100.000.000 < X AND X < 100.000.200 will not use index - because that condition with split indexes will produce near full scan for each index. And there's where tricky part is - obviously, that condition specifies very narrow part of table (i.e. logically, it is good) - but if we're speaking about separate conditions - it's crap, because each of them is near full scan.
My next though was to create some function which will take two arguments and create then bijective transition to some line set of numbers. Since my from and till are integers - and, what's important - positive integers, and also from < till always, sample of such function will be from^2 + till^2. So, ok, we'll translate our intervals to some numbers. But, unfortunately, to operate on this numbers and X we'll have to rely on original from and till - i.e. it seems that's not a case for such idea. But may be I'm missing something?
The question
Currently, I have no completed clear idea - how to implement this. So - again, I'm free to chose any architecture, but it should fit requirement of fast querying for needed rows by X. And the question is - what table structure (columns, indexes e t.c.) could be proposed here? We are also free to store additional tables (however, it will be good if their sizes will not be too high). Of course, since we're free to define table structure, we can change querying for X too (i.e. if some structure will need to add some condition to that query - it is ok, the only need is to achieve final goal).
You want to reduce the impact of the query over all rows running the comparison function to find out if that row matches the span of numbers X lies in or not.
As you have outlined, the effectiveness of some common index is not of much use because of the sheer amount of numbers / row ratio.
This is where I would start. Why not reduce the resolution and use that as an index?
Also how large do the spans get? You have so far 100, 80, 50, 400.
Assuming that the size of a span is not up to the superset of all values but instead normally a little fraction of it (e.g. max 1 000 by a superset of 500 000 000 values), why not index from but at lower resultion, e.g. divided by 1 000.
That will greatly reduce the index-space to 500 000 entries on such a low resolution helper-column. You then can use std. math in the WHERE part of the query to use that index, too to find a superset of possible matching rows. The more expensive comparisons (the exact BETWEEN) can then be deffered on only these possible matching rows.
This perhaps is not such an academic solution to the problem but might give you the performance you're looking for.
Edit: As #NikiC kindly pointed out and for the academic solution, there is a paper by Hans-Peter Kriegel, Marco Pötke and Thomas Seidl:
The Relational Interval Tree: Manage Interval Data Efficiently
in Your Relational Database (PDF)
One option here is to partition your table. Specifically using range partitioning. This coupled with indexes on your from and till columns should give you an acceptable level of performance.
Here is a basic example:
CREATE TABLE myTable (
`id` INT NOT NULL,
`from` bigint unsigned not null,
`till` bigint unsigned not null,
PRIMARY KEY (`from`,`till`),
INDEX myTableIdx1 (`from`),
INDEX myTableIdx2 (`till`)
)
PARTITION BY RANGE (`from`) (
PARTITION p0 VALUES LESS THAN (200000),
PARTITION p1 VALUES LESS THAN (400000),
PARTITION p2 VALUES LESS THAN (600000),
PARTITION p3 VALUES LESS THAN (800000),
PARTITION p4 VALUES LESS THAN (1000000),
PARTITION p5 VALUES LESS THAN (1200000),
PARTITION p6 VALUES LESS THAN (1400000),
PARTITION p7 VALUES LESS THAN (1600000),
PARTITION p8 VALUES LESS THAN (1800000),
PARTITION p9 VALUES LESS THAN (2000000),
-- etc etc
PARTITION pEnd VALUES LESS THAN MAXVALUE
);
This approach does make the assumption that your version of MySQL supports partitioning and that you can divide your table into meaningful partitions based on the data!
PS You may want to choose a different column name other than from....
Option 1
I think this is what you need.
But still an full index scan is needed for the 125 case, the 2001 will trigger an better range scan.
SELECT
data.id
, data.`from`
, data.`till`
FROM
data
WHERE
`from` < 125 and 125 < `till`
see demo http://sqlfiddle.com/#!2/208ca/20
Option 2
DERIVED table to filter out the non matches
SET #x = 125;
SELECT
data.id
, data.`from`
, data.`till`
FROM (
SELECT
id
, `till`
FROM
data
WHERE
`from` < #x -- from should always be smaller than #x
) from_filter
INNER JOIN
data
ON
from_filter.id = data.id
AND
#x < from_filter.`till` -- #x should always be smaller then till
;
see demo http://sqlfiddle.com/#!2/208ca/27
Option 3
R tree indexing may be the best option

Search next (bigger) key with SQL efficiently

I have a table with tuples where timestamps (time) are not consecutive but (we can assume for simplicity) unique.
time | value
------------
0 |4
3 |2
5 |6
8 |10
9 |5
13 |-1
15 |-3
... |...
I am faced with the problem of finding the "next tuple given some time T" ( <- next(T);), e.g. next(4) -> <5,6>, or next(5) -> <8,10>. Further, since this data is hold in a MySQL database I would prefer to realize this with SQL. However, time constraints require to find the respective tuple in O (log n).
At first glance, I tried the following SQL statement (I hope my Pseudo-code is understandable):
<time, value> = next(T) {
return (select * from table
where time = (select min(time) from table
where time > T))
}
However, this does not give the result in reasonable time. I guess that "select min(time) from table where time > find" takes O(n) time. Of course, I know performing a search in an ordered list takes only O(log n) time but I have no clue how to do that in SQL. Is this even possible? If so, how does it work?
Thanks!
For your information:
(1) At the moment my solution caches the respective data in memory and orders it initially. This way I can then find the next tuple in O(log n) time. However, this consumes lots of memory and I would prefer to do it kind of "in-line" in the DBMS which is surely highly optimized regarding caching etc.
(2) I could imagine a solution where data is hold ordered by time in the database, but I don't know how to ensure ordering or to implement a respective search algorithm in SQL. :-/
(3) I am aware of indexing etc. and that it improves performance if I declare time as primary key but I don't know how it could help to find next in O(log n).
You need to make sure that an index exists for the time column. You can check if an index exists by examining the results of this command:
show index from table;
If the time column is the primary key of the table, then the index almost certainly exists. The index is necessary for an efficient search in the time column. You will get O(log n) performance with the right index, if not constant time lookups (just read more about btrees).
MySQL uses B-tree indexes, which allow lookup and sequential traversing, both in logarithmic time. That means that finding the next higher time for a given time is done in logarithmic time, provided that MySQL utilizes the index correctly. This is not always the case and you have to try this. If it does not work, you have to give MySQL execution hints to make it utilizing the index correctly.
Order the results by time and then use the limit keyword for taking only the first result from the result set:
select * from table
where time > T
order by time
limit 1