Well, I think this is the question "Old, but Golden." Answer: "It depends!" Performances are such a delicate topic that it would be too stupid to say: "Never use subqueries, always join." In the following links you will find some basic recommendations that I thought were very useful: Here 1 Here 2 Here 3
I have a table with 50,000 elements, as a result I was looking for 739 elements.
At first, my request was as follows:
SELECT p.id, p.fixedId, p.azienda_id, p.categoria_id, p.linea, p.tipo, p.nome FROM prodotto p WHERE p.azienda_id = 2699 AND p.anno = ( SELECT MAX(p2.anno) FROM prodotto p2 WHERE p2.fixedId = p.fixedId )
and it took 7.9s to complete.
Finally, my request:
SELECT p.id, p.fixedId, p.azienda_id, p.categoria_id, p.linea, p.tipo, p.nome FROM prodotto p WHERE p.azienda_id = 2699 AND (p.fixedId, p.anno) IN ( SELECT p2.fixedId, MAX(p2.anno) FROM prodotto p2 WHERE p.azienda_id = p2.azienda_id GROUP BY p2.fixedId )
and it took 0.0256s
Good SQL, good.
linuxatico Jul 05 '13 at 13:42
source share