1

I have the following query:

select * 
 from products as p
 left join files as f on f.contentid = p.productid
   where 
     p.state = 'active' AND 
     p.price > 0 order by p.created DESC 
   LIMIT 2200

Currently, this query takes about 1.7 seconds for 2200 rows. What I don't understand is, why does this time not decrease when I change the limit from 2200 to 10, and more importantly, what I can do to speed it up?

8
  • 1
    Are your ID fields indexed (contentid, productid)? Mar 12, 2012 at 12:52
  • Do you need all fields of table products? Mar 12, 2012 at 12:53
  • 3
    Time to order the data is the same for 10, 200, 2200 and all the rows. First data will be ordered then limit will be applied.
    – botzko
    Mar 12, 2012 at 12:54
  • SELECT p.field1, p.field2, p.fieldn FROM products p, files f WHERE f.contentid = p.productid AND p.state = 'active' AND p.price > 0 ORDER BY p.created DESC LIMIT 2200 Mar 12, 2012 at 12:55
  • 1
    If you don't need every field from the two tables, you may also want to consider selecting the specific fields (instead of *) to reduce the size of the returned rows. That's helped me in situations in the past (especilly text fields).
    – Kory Sharp
    Mar 12, 2012 at 12:55

3 Answers 3

5

By adding INDEX on files [contentid] and products [productid], it can speed up your query.

0
1

Try :

EXPLAIN select * 
 from products p
 left join files f on f.contentid = p.productid
   where 
     p.state = 'active' AND 
     p.price > 0 order by p.created DESC 
   LIMIT 2200

to see what indexes you need

4
  • + Options id select_type table type possible_keys key key_len ref rows Extra 1 SIMPLE p ALL NULL NULL NULL NULL 1577 Using where; Using temporary; Using filesort 1 SIMPLE f ALL NULL NULL NULL NULL 1595 Mar 12, 2012 at 13:03
  • As I see possible_keys column is null, so you got no possible keys for the query to use. Try to add indexes for files contentid and for products productid
    – dotoree
    Mar 12, 2012 at 13:45
  • I did that, it fixed the problem, but I'm unsure as to how to use explain. It ended up not giving me the answer... or at least, I don't know how to make sense of it... Mar 12, 2012 at 14:08
  • @RD Here is a tutorial about explain eecho.info/Echo/database/using-explain
    – dotoree
    Mar 12, 2012 at 14:34
1

Usually I just play with the query to see what minimizes runtime the best. If necessary, work out the problem using Relational Algebra and look for places to optimize from there. Here's my suggestion:

 SELECT * 
 FROM products as p, files f
    WHERE f.contentid = p.productid 
    AND p.state = 'active'
    AND p.price > 0 
    ORDER BY p.created DESC
    LIMIT 2200

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.