I have the sql query below that is running very slowly. I took a look at the execution plan and it is claiming that a sort on Files.OrderId is the highest cost operation (53%). Why would this be happening if I am not ordering by OrderId anywhere? Is my best bet to create an index on File.OrderId?
Execution plan if anyone is interested.
with custOrders as
(
SELECT c.firstName + ' ' + c.lastname as Customer, c.PartnerId , c.CustomerId,o.OrderId,o.CreateDate, c.IsPrimary
FROM Customers c
LEFT JOIN CustomerRelationships as cr
ON c.CustomerId = cr.PrimaryCustomerId
INNER JOIN Orders as o
ON c.customerid = o.customerid
OR (cr.secondarycustomerid IS NOT NULL AND o.customerid = cr.secondarycustomerid)
where c.createdate >= @FromDate + ' 00:00'
AND c.createdate <= @ToDate + ' 23:59'
),
temp as
(
SELECT Row_number()
OVER (
ORDER BY c.createdate DESC) AS 'row_number',
c.customerid as customerId,
c.partnerid as partnerId,
c.Customer,
c.orderid as OrderId,
c.createdate as CreateDate,
Count(f.orderid) AS FileCount,
dbo.Getparentcustomerid(c.isprimary, c.customerid) AS ParentCustomerId,
au.firstname + ' ' + au.lastname AS Admin,
'' as blank,
0 as zero
FROM custOrders c
INNER JOIN files f
ON c.orderid = f.orderid
INNER JOIN admincustomers ac
ON c.customerid = ac.customerid
INNER JOIN adminusers au
ON ac.adminuserid = au.id
INNER JOIN filestatuses s
ON f.statusid = s.statusid
WHERE ac.adminuserid IS NOT NULL
AND f.statusid NOT IN ( 5, 6 )
GROUP BY c.customerid,
c.partnerid,
c.Customer,
c.isprimary,
c.orderid,
c.createdate,
au.firstname,
au.lastname
)
OVER
imply a sort? – MonctonOVER
, but not by order id – Krugersdorp