I\'ve searched around stackoverflow but everybody asks to optimize queries they\'ve already done.
I want to know, the basic stuff on what to do, what to avoid when creat
adding some tips to the list :
Using EXISTS/NOT EXISTS in place of IN/NOT IN for indexed columns
--instead of
SELECT * FROM table1
WHERE id1 NOT IN (SELECT id2 FROM table2)
--you better write
SELECT * FROM table1 WHERE NOT EXISTS (SELECT 1 FROM table2 WHERE id1=id2)
Avoid using UNION when its possible to use UNION ALL
when you dont need to exclude duplicated rows or you are sure it wont return duplicated rows
Avoid using HAVING when its possible to use WHERE
--instead of
SELECT col1, sum(col2)
FROM table1
GROUP BY col1
HAVING col1 > 0
--you better write :
SELECT col1, sum(col2)
FROM table1
WHERE col1 > 0
GROUP BY col1
Use EXISTS instead of DISTINCT when you have one-to-many table joins
--instead of
SELECT distinct a.col1, a.col2
FROM table1 a, table2 b
WHERE a.id = b.id
--you better write
SELECT a.col1, a.col2
FROM table1 a
WHERE EXISTS (SELECT 1 FROM table2 b where a.id = b.id)
I hope this few tips helps, looking forward more tips ;)