Question

Here is my SQL command :

SELECT  
    ts.CHECK_NUMBER,
    ts.CUSTOMER_NAME,
    ts.COMPANY_NAME,
   ( SELECT COUNT(*) 
     FROM   TRANSACTION_ORDER too 
     WHERE  too.CHECK_NUMBER = ts.CHECK_NUMBER
    ) as NB_OF_ORDERS
FROM 
     TRANSACTION_SUMMARY ts
ORDER BY 
     ts.BUSINESS_DATE

It is taking so long to render data, we are talking about minimum 3000 transactions, for each one we have to count the orders.

Is there any better solution?

Was it helpful?

Solution

It is taking too long because when you have this sub-query in your select , it is executed for each row returned by the outer query, so if your outer query returns 50,000 rows this inner select query will be executed 50,000 times which is obviously a performance killer,

You should try something like this....

SELECT  
     ts.CHECK_NUMBER
    ,ts.CUSTOMER_NAME
    ,ts.COMPANY_NAME
    ,ISNULL(O.Total, 0) AS NB_OF_ORDERS
FROM  TRANSACTION_SUMMARY ts
LEFT JOIN    --<-- use inner join is you only want records with some orders
      ( SELECT CHECK_NUMBER, COUNT(*) AS Total 
        FROM   TRANSACTION_ORDER 
        GROUP BY CHECK_NUMBER
      ) as O
ON ts.CHECK_NUMBER = O.CHECK_NUMBER
ORDER BY  ts.BUSINESS_DATE
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top