Identical SQL Query Vastly Different Performance

I'll start by saying I'm not a DB guy, so I'm lost a bit. I've probably got a poorly designed schema to boot, but things have been working for the most part so far. Until now.

I've got a database of race results that I'm am crunching numbers on to compare performances between races. Now that I am pushing 40k results in the result table, performance has become highly variable.

From the MySQL prompt if I run the following query twice in a row, the first time it returns 1000 rows in less than a second. The second time the query times out after 30 seconds. (Yes I realize this example is "comparing" a race against itself)

Code:
SELECT Racer.FirstName, Racer.LastName, r1.TimeInSec as "Race 1 Time", r2.TimeInSec as "Race 2 Time" FROM Racer, Result r1, Result r2 WHERE r1.EventID=174 AND r2.EventID=174 AND r1.RacerID=r2.RacerID AND Racer.RacerID=r1.RacerID LIMIT 1000;

Googling has not helped me, perhaps because I'm just not familiar enough with how the database functions.

Any insight to push me down the right path would be appreciated.
 
@wallinbl

Result Table
Code:
+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| id        | int(11)      | NO   | PRI | NULL    | auto_increment |
| RacerID   | int(11)      | NO   |     | NULL    |                |
| EventID   | int(11)      | NO   |     | NULL    |                |
| TimeInSec | int(11)      | YES  |     | NULL    |                |
| Bib       | int(11)      | YES  |     | NULL    |                |
| RawData   | varchar(100) | YES  |     | NULL    |                |
| Overall   | int(11)      | YES  |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+

Racer Table
Code:
+----------------+-------------+------+-----+---------+----------------+
| Field          | Type        | Null | Key | Default | Extra          |
+----------------+-------------+------+-----+---------+----------------+
| RacerID        | int(11)     | NO   | PRI | NULL    | auto_increment |
| FirstName      | varchar(40) | YES  |     | NULL    |                |
| LastName       | varchar(40) | YES  |     | NULL    |                |
| BirthYear      | int(11)     | YES  |     | NULL    |                |
| HomeTown       | varchar(50) | YES  |     | NULL    |                |
| Gender         | varchar(1)  | YES  |     | NULL    |                |
| HomeState      | varchar(40) | YES  |     | NULL    |                |
| PrimaryRacerID | int(11)     | YES  |     | NULL    |                |
+----------------+-------------+------+-----+---------+----------------+

@MilleniX

Something like the following? I'm not sure I have it quite right... though it does seem to be working on the surface. Of course performance of the original query is better today too. :scared:

Code:
SELECT Racer.FirstName,
		Racer.LastName, 
		r1.TimeInSec as "Race 1 Time", 
		r2.TimeInSec as "Race 2 Time" 
	FROM ((Racer
		INNER JOIN Result r1 ON r1.EventID=174 AND r1.RacerID=Racer.RacerID)
		INNER JOIN Result r2 ON r2.EventID=174 AND r1.RacerID=r2.RacerID) 
	LIMIT 1000;
 

MilleniX

Ars Tribunus Angusticlavius
8,141
Subscriptor++
If you don't have any indexes defined, the obvious one to suggest would be on the pair of Result.EventID and Result.RacerID. An index on either one or each of those separately would probably help a whole bunch too, if it's currently doing table scans.

You should take a look at the query execution plan you're getting: https://dev.mysql.com/doc/refman/5.5/en ... ation.html
 

gregatron5

Ars Legatus Legionis
13,011
Subscriptor++
Obligatory don’t use MySQL post.

How can the primary key column be nullable? All sane DBs automatically put a unique index on a PK, so hopefully that is the case here. That said, it could also be a stats issue.

Also, I don’t know if it’s still the case, but MySQL used to have issues when doing multiple joins in subqueries. It could be that the query engine ran out of memory if it’s doing a bunch if Cartesian joins.
 
No Indexes, Implicit Join

Code:
+----+-------------+-------+--------+---------------+---------+---------+--------------------+-------+----------------------------------------------------+
| id | select_type | table | type   | possible_keys | key     | key_len | ref                | rows  | Extra                                              |
+----+-------------+-------+--------+---------------+---------+---------+--------------------+-------+----------------------------------------------------+
|  1 | SIMPLE      | r1    | ALL    | NULL          | NULL    | NULL    | NULL               | 39577 | Using where                                        |
|  1 | SIMPLE      | Racer | eq_ref | PRIMARY       | PRIMARY | 4       | nrat_db.r1.RacerID |     1 | NULL                                               |
|  1 | SIMPLE      | r2    | ALL    | NULL          | NULL    | NULL    | NULL               | 39577 | Using where; Using join buffer (Block Nested Loop) |
+----+-------------+-------+--------+---------------+---------+---------+--------------------+-------+----------------------------------------------------+

No Index, Explicit Inner Joins (as above)

Code:
+----+-------------+-------+--------+---------------+---------+---------+--------------------+-------+----------------------------------------------------+
| id | select_type | table | type   | possible_keys | key     | key_len | ref                | rows  | Extra                                              |
+----+-------------+-------+--------+---------------+---------+---------+--------------------+-------+----------------------------------------------------+
|  1 | SIMPLE      | r1    | ALL    | NULL          | NULL    | NULL    | NULL               | 39577 | Using where                                        |
|  1 | SIMPLE      | Racer | eq_ref | PRIMARY       | PRIMARY | 4       | nrat_db.r1.RacerID |     1 | NULL                                               |
|  1 | SIMPLE      | r2    | ALL    | NULL          | NULL    | NULL    | NULL               | 39577 | Using where; Using join buffer (Block Nested Loop) |
+----+-------------+-------+--------+---------------+---------+---------+--------------------+-------+----------------------------------------------------+

One Index of RacerID, Explicit Inner Join

Code:
+----+-------------+-------+--------+---------------+------------+---------+--------------------+-------+-------------+
| id | select_type | table | type   | possible_keys | key        | key_len | ref                | rows  | Extra       |
+----+-------------+-------+--------+---------------+------------+---------+--------------------+-------+-------------+
|  1 | SIMPLE      | r1    | ALL    | RacerIndex    | NULL       | NULL    | NULL               | 39577 | Using where |
|  1 | SIMPLE      | Racer | eq_ref | PRIMARY       | PRIMARY    | 4       | nrat_db.r1.RacerID |     1 | NULL        |
|  1 | SIMPLE      | r2    | ref    | RacerIndex    | RacerIndex | 4       | nrat_db.r1.RacerID |     3 | Using where |
+----+-------------+-------+--------+---------------+------------+---------+--------------------+-------+-------------+

Index on RacerID and on EventID, Explicit Inner Join

Code:
+----+-------------+-------+--------+-----------------------+------------+---------+--------------------+------+-------------+
| id | select_type | table | type   | possible_keys         | key        | key_len | ref                | rows | Extra       |
+----+-------------+-------+--------+-----------------------+------------+---------+--------------------+------+-------------+
|  1 | SIMPLE      | r1    | ref    | RacerIndex,EventIndex | EventIndex | 4       | const              | 3252 | NULL        |
|  1 | SIMPLE      | Racer | eq_ref | PRIMARY               | PRIMARY    | 4       | nrat_db.r1.RacerID |    1 | NULL        |
|  1 | SIMPLE      | r2    | ref    | RacerIndex,EventIndex | RacerIndex | 4       | nrat_db.r1.RacerID |    3 | Using where |
+----+-------------+-------+--------+-----------------------+------------+---------+--------------------+------+-------------+

Index on RacerID, EventID, and RacerID/EventID, Explicit Inner Join

Code:
+----+-------------+-------+--------+---------------------------------------+-----------------+---------+--------------------------+------+-------+
| id | select_type | table | type   | possible_keys                         | key             | key_len | ref                      | rows | Extra |
+----+-------------+-------+--------+---------------------------------------+-----------------+---------+--------------------------+------+-------+
|  1 | SIMPLE      | r1    | ref    | RacerIndex,EventIndex,EventRacerIndex | EventIndex      | 4       | const                    | 3252 | NULL  |
|  1 | SIMPLE      | r2    | ref    | RacerIndex,EventIndex,EventRacerIndex | EventRacerIndex | 8       | const,nrat_db.r1.RacerID |    1 | NULL  |
|  1 | SIMPLE      | Racer | eq_ref | PRIMARY                               | PRIMARY         | 4       | nrat_db.r1.RacerID       |    1 | NULL  |
+----+-------------+-------+--------+---------------------------------------+-----------------+---------+--------------------------+------+-------+
 
Code:
SELECT Racer.FirstName,
      Racer.LastName,
      r1.TimeInSec as "Race 1 Time",
      r2.TimeInSec as "Race 2 Time"
   FROM ((Racer
      INNER JOIN Result r1 ON r1.EventID=174 AND r1.RacerID=Racer.RacerID)
      INNER JOIN Result r2 ON r2.EventID=174 AND r1.RacerID=r2.RacerID)
   LIMIT 1000;
should probably have been
Code:
SELECT Racer.FirstName,
      Racer.LastName,
      r1.TimeInSec as "Race 1 Time",
      r2.TimeInSec as "Race 2 Time"
   FROM Racer
      INNER JOIN Result r1 ON r1.RacerID = Racer.RacerID
      INNER JOIN Result r2 ON r1.RacerID = r2.RacerID
   WHERE r1.EventID = 174
     AND r2.EventID = 174
   LIMIT 1000;
1. You don't really need the parenthesis.
2. The EventID match being on the INNER JOIN or on the WHERE clause have slightly different semantics; judging your query you probably want them on the where-clause.

Note that LIMIT without an ORDER BY clause is dangerous in general; there is no guarantee on what you get. If your data set is 10 rows only, you would not notice the difference, but if the result is 10k rows, you may be getting records 1-1000 one time, records 9001-10000 in another run.

For your original problem, the problem is usually query being slow the first time, then lightning fast on subsequent runs due to caching and so on. Your original problem, where first run is quick and second time slow, does not make much sense without more metrics, or indeed knowing the shape of your actual data.

Adding indices may aid in giving you more consistent performance, because the IO load shifts over to the indices, but without understanding what causes your original problem, you always have that thing lurking in the shadow waiting to hurt you.

edit: been writing too much markdown, using the wrong tags
 

wallinbl

Ars Legatus Legionis
14,339
Subscriptor
Obligatory don’t use MySQL post.

How can the primary key column be nullable? All sane DBs automatically put a unique index on a PK, so hopefully that is the case here. That said, it could also be a stats issue.

Also, I don’t know if it’s still the case, but MySQL used to have issues when doing multiple joins in subqueries. It could be that the query engine ran out of memory if it’s doing a bunch if Cartesian joins.
It's not nullable - the default value is NULL, but that's just going to get an exception on insert.

Code:
SELECT Racer.FirstName, Racer.LastName, r1.TimeInSec as "Race 1 Time", r2.TimeInSec as "Race 2 Time" 
FROM Racer, Result r1, Result r2 
WHERE r1.EventID=174 
AND r2.EventID=174 
AND r1.RacerID=r2.RacerID 
AND Racer.RacerID=r1.RacerID 
LIMIT 1000;
I'm going to rewrite this so I understand it (and, as others have said, don't do your joins like that - you're just asking for mistakes):
Code:
SELECT Racer.FirstName, Racer.LastName, r1.TimeInSec as "Race 1 Time", r2.TimeInSec as "Race 2 Time" 
FROM Racer
INNER JOIN Result r1 ON Racer.RacerID = r1.RacerID
INNER JOIN Result r2 ON r1.RacerID=r2.RacerID AND r2.EventID=174 -- Could go in the WHERE clause, but in case the optimizer gets stupid, safer here.
WHERE r1.EventID=174 ;

Ok, so you're getting rows from the Result table where Event ID is 174. What's unclear is why you're joining the Result table twice. The same Racer is in the same event more than once and you want both times? If so, you want something like this:
Code:
SELECT Racer.FirstName, Racer.LastName, r1.TimeInSec as "Race 1 Time", r2.TimeInSec as "Race 2 Time" 
FROM Racer
INNER JOIN Result r1 ON Racer.RacerID = r1.RacerID
INNER JOIN Result r2 ON r1.RacerID=r2.RacerID AND r2.EventID=174 [b]AND r1.ID < r2.ID[/b]
WHERE r1.EventID=174 ;
Now, that will only return rows where the same racer was in there at least twice. If you want the racer, even if they were only in the event once, change the second INNER to a LEFT. Note also that I used "<" rather than "<>". If you use "<>", you'll get two rows for each pair, with the times switched in each row.

I assume it's also possible that you didn't mean to use 174 for both event IDs?

In general, I'd suggest reordering the query a bit to look like this:
Code:
SELECT Racer.FirstName, Racer.LastName, r1.TimeInSec as "Race 1 Time", r2.TimeInSec as "Race 2 Time" 
FROM Result r1
INNER JOIN Racer ON r1.RacerID = Racer.RacerID 
INNER JOIN Result r2 ON r1.RacerID=r2.RacerID AND r2.EventID=174 [b]AND r1.ID < r2.ID[/b]
WHERE r1.EventID=174 ;
The difference is minor, but now you're selecting from results, in part because you're looking for output of results.


It's probably worth clarifying the goal of the query, as it's not entirely clear what you're trying to get with the query from what you wrote.
 
The EventID match being on the INNER JOIN or on the WHERE clause have slightly different semantics; judging your query you probably want them on the where-clause.
Respectfully, you have that backwards. There's no difference putting criteria for an INNER join in the JOIN vs WHERE. What you describe, applies to OUTER joins.
 
How can the primary key column be nullable? All sane DBs automatically put a unique index on a PK, so hopefully that is the case here. That said, it could also be a stats issue.
Because it isn't - the DEFAULT is NULL, as a primary key the column is definitely NOT NULL. You're misreading what is provided.

IIRC, MySQL indexes the primary key by default, like Oracle. MS SQL Server was the only product I remember when you can define the PK, but the index is actually on something else...
 

hanser

Ars Legatus Legionis
43,855
Subscriptor++
When you run SQL against a table on one machine, and then against the same table on another machine, and the performance is very different, the answer is almost* always "your indexes between the two aren't the same".

* I would say "always" but I'm leaving in the possibility that I don't know something about SQL. If your indexes are identical, you'd need huge data size differences between the environments to account for it, all other things being equal because that's how binary search trees work.

--

In the future, you can save time by doing what wallinbl asked for in the first reply: post the table create scripts along with indexes. Rows and columns are insufficient because they don't show the complete schema. This is database app dev 101. :eng101:
 
If your indexes are identical, you'd need huge data size differences between the environments to account for it, all other things being equal because that's how binary search trees work.
The declared index may be identical (along with host details - IO, CPU, memory & config), but things like index fragmentation, table statistics, system load at execution time... There's more to the topic than just identical indexes.
 

wallinbl

Ars Legatus Legionis
14,339
Subscriptor
If your indexes are identical, you'd need huge data size differences between the environments to account for it, all other things being equal because that's how binary search trees work.
The declared index may be identical (along with host details - IO, CPU, memory & config), but things like index fragmentation, table statistics, system load at execution time... There's more to the topic than just identical indexes.
Sure, but the OP is complaining the query performs vastly differently on subsequent runs, not on differing machines.

I still want to know what the query is supposed to do, because I don't think it's doing what it's supposed to do - the way it's written doesn't make a lot of sense.
 
If your indexes are identical, you'd need huge data size differences between the environments to account for it, all other things being equal because that's how binary search trees work.
The declared index may be identical (along with host details - IO, CPU, memory & config), but things like index fragmentation, table statistics, system load at execution time... There's more to the topic than just identical indexes.
Sure, but the OP is complaining the query performs vastly differently on subsequent runs, not on differing machines.
I don't have the MySQL experience to draw from, so need more than one grain of salt... IME, sounds like a bad query plan. But the performance tanking is consistent, at least after whatever query parameters that trigger the bad plan are used. Short term solution is to clear the query cache; long term plan is to refactor the query, if not the data model.
 
Following up.

The example query was misleading.

The query is supposed to, and does in fact, return racers who competed in both races. The example shown was with r1.RaceID and r2.RaceID identical. In that instance they should have all done both races... but it was a simple one to demonstrate the issue I was running into. In reality, the query is run with r1.RaceID != r2.RaceID.
 
Following up.

The example query was misleading.

The query is supposed to, and does in fact, return racers who competed in both races. The example shown was with r1.RaceID and r2.RaceID identical. In that instance they should have all done both races... but it was a simple one to demonstrate the issue I was running into. In reality, the query is run with r1.RaceID != r2.RaceID.
There's no RaceID in the table descriptions you provided. You made this typo more than once. Did you mean EventID?

Code:
SELECT r.FirstName
     , r.LastName
     , r1.TimeInSec as "Race 1 Time"
     , r2.TimeInSec as "Race 2 Time"
  FROM Racer r
  JOIN Result r1 ON r1.RacerID = r.RacerID
                AND r1.EventID = 174
  JOIN Result r2 ON r2.RacerID = r.RacerID
                AND r2.EventID <> r1.EventID
 LIMIT 1000;