I have been given a query that takes about 1:30 to run. I was asked to optomize it as much as possible but am having issues making any headway on it.
SELECT DISTINCT B.PROV,
FACILITY=CASE B.FACILITY
WHEN '' THEN (SELECT FACILITY
FROM CLDOCTOR
WHERE DOCTOR = B.PROVCODE)
ELSE B.FACILITY
END,
C.PLNAME,
C.PFNAME,
C.PMNAME,
C.DOB,
C.SEX,
Cast(Cast(A.DATEBACK AS VARCHAR(12)) AS DATETIME) AS 'DATEBACK',
C.CITY,
C.STATE,
C.ZIP,
C.HPHONE,
C.WPHONE,
A.SSNO,
C.PTYPE,
B.ACCOUNT,
B.ORDERDATE
FROM CLLAB A,
CLORDER B,
CLMASTER C
WHERE A.COMPANY = B.COMPANY
AND A.ORDER_ID = B.ID
AND B.DEPT = 'LAB'
AND B.ACCOUNT = C.ACCOUNT
--AND DATEDIFF(MM, DATEBACK, GETDATE()) <=6
AND A.DATEBACK NOT IN (SELECT DISTINCT DATEBACK
FROM CLLAB
WHERE COMPANY = A.COMPANY
AND DEPT = 'LAB'
AND SSNO = A.SSNO
--AND DATEDIFF(MM, DATEBACK, GETDATE()) <= 6
AND OBSERVE_ID = 'REVIEWED'
)
CLLAB
contains 34,185,327 rows, CLORDER
contains 13,455,600 rows, and CLMASTER
contains 392,797 rows.
Do you see anything that jumps out as inherently wrong that could be cleaned up to help the query run quicker?
Edit 1:
There are indexes on CLLAB
's ORDERID
, SSNO
, and a few other unused columns.
There are indexes on CLORDERS
's PROV
, ORDERDATE
, and a few other unused columns.
The execution plan says Missing Index (Impace 48.1371): CREATE NONCLUSTERED INDEX [<Name of Missing Index, sysname,>] on [dbo].[CLORDER] ([DBO].[CLORDER][DEPT]) INCLUDE ([COMPANY],[ID],[PROV],[ORDERDATE],[ACCOUNT],[FACILITY],[PROVCODE])
which makes me think that there could be huge gains made by indexing CLLAB
's DEPT