Web Development

Web Development Tips & Tricks, the things that you don’t want to figure out.





Archive for the ‘SQL

MySQL INNER JOIN – A Real Time Saver

Wednesday, January 28th, 2009

MySQLOk, so the story behind this post is one of my sites, SendArticles.com. It is an article submission service, and one page, the reports page, was taking 10-15 second to load. I cannot stand waiting that long, it makes me not want to go to the page, yet I have to all the time. This is a dedicated server and it was nowhere near its max capacity, so I knew it had to be something else.

So, I decided to debug it. I removed a small piece of code, and BAM! Loaded in about half a second. I was confused, I put the code back in. 10-15 second delay was back. Ok, that was definitely it. So, it came down to a SQL (despite technically using MySQL, I’m just going to refer to it as the code is the same) query, which was essentially the following:

SQL

SELECT col FROM table WHERE col2 IN (SELECT col2 FROM table2 WHERE col3 = XX AND col4 = XX)

I apologize for the anonymity, but I do feel it’s necessary. Anyway, the main essence of the statement was that it was making a column (col2) match what another SELECT statement found. So, I decided to replace it with an INNER JOIN (I wasn’t in the practice of using them when I first wrote the code).

SQL

SELECT a.col FROM table AS a INNER JOIN table2 AS b ON (a.col2 = b.col2) WHERE b.col3 = XX AND b.col4 = XX

It produces the exact same results, but in about half a second. Almost no time at all, just instant results. So, I’ve resolved to go through every SQL statement in the hundreds of pages of files (luckily nearly all of them are contained in a handful of classes), and change any SQL IN statements to INNER JOIN.

Hope this helped,

Kerry