How can I optimize the SQL query below? It takes too much time. This is used to select from a very large astronomical table (a few hundred million objects), and this query runs over 12 hours which is more than the maximum allow query time. It appears that adding more restrictions via additional conditions doesn't help at all.
Your help is much appreciated!
select AVG(o.zMeanPSFMagStd) into mydb.z1819
from MeanObject as o
join ObjectThin ot on ot.ObjID=o.ObjID
inner join StackObjectAttributes soa on soa.objID=o.objid
where o.zMeanPSFMag>=18
and o.zMeanPSFMag<19
and o.zQfPerfect > 0.85
and (ot.qualityFlag & 1) = 0
and (ot.qualityFlag & 2) = 0
and o.zMeanPSFMagErr <> -999
and o.zMeanPSFMagStd <> -999
and ot.nz > 10 and soa.zpsfMajorFWHM < 6
and soa.zpsfMinorFWHM/nullif(soa.zpsfMajorFWHM,0) > 0.65
and soa.zpsfFlux/nullif(soa.zpsfFluxErr,0)>5
and (ot.b>10 or ot.b<-10)
and (ot.raMean>0 and ot.raMean<180)
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `MeanObject` ADD INDEX `meanobject_idx_zmeanpsfmag` (`zMeanPSFMag`);
ALTER TABLE `ObjectThin` ADD INDEX `objectthin_idx_objid_nz` (`ObjID`,`nz`);
ALTER TABLE `StackObjectAttributes` ADD INDEX `stackobjectattribu_idx_objid_zpsfmajorfwhm` (`objID`,`zpsfMajorFWHM`);
SELECT
AVG(o.zMeanPSFMagStd) INTO mydb.z1819
FROM
MeanObject AS o
JOIN
ObjectThin ot
ON ot.ObjID = o.ObjID
INNER JOIN
StackObjectAttributes soa
ON soa.objID = o.objid
WHERE
o.zMeanPSFMag >= 18
AND o.zMeanPSFMag < 19
AND o.zQfPerfect > 0.85
AND (
ot.qualityFlag & 1
) = 0
AND (
ot.qualityFlag & 2
) = 0
AND o.zMeanPSFMagErr <> -999
AND o.zMeanPSFMagStd <> -999
AND ot.nz > 10
AND soa.zpsfMajorFWHM < 6
AND soa.zpsfMinorFWHM / nullif(soa.zpsfMajorFWHM, 0) > 0.65
AND soa.zpsfFlux / nullif(soa.zpsfFluxErr, 0) > 5
AND (
ot.b > 10
OR ot.b < -10
)
AND (
ot.raMean > 0
AND ot.raMean < 180
)