Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Performance Issue with slow running query

$
0
0

Hi all,
I have a performance issue that I need help with. The query is taking 40 seconds to run.
I tried creating indexes but it hasnt really helped. Please suggest indexes/other methods that might help with this quey.

There are 2 main tables: Table1 and Table2.
----------------------------------------------
create table Table1
(
 Num [nvarchar](255) NULL,
 Code [nvarchar](255) NULL,
 Amt [float] NULL,
 Description [nvarchar](255) NULL,
 -- And other fields ---
)

-- Sample data below. There are over 300,000 records in this table with 37,000 distinct [Num] field values.
--No indexes on this table.

-- sample data
Insert Table1 values ('00000000000011111', 'a',2.3,'test')
Insert Table1 values ('00000000000011111', 'a',2.4,'test2')
Insert Table1 values ('00000000000011111', 'b',2.5,'test3')

Insert Table1 values ('00000000000011112', 'c',2.7,'test11')
Insert Table1 values ('00000000000011112', 'a',2.8,'test12')
Insert Table1 values ('00000000000011112', 'b',2.9,'test13')
Insert Table1 values ('00000000000011112', 'c',2.9,'test14')

----------------------------------------------
--The second table has 19000 records with 3000 distinct [NUM]
--No indexes on this table.

create table Table2
(
 ID [int] IDENTITY(1,1) NOT NULL,
 NUM [nvarchar](255) NULL,
 -- And other fields ---
)

-- sample data
Insert Table2 values ('00000000000011111')
Insert Table2 values ('00000000000011113')
Insert Table2 values ('00000000000011114')
Insert Table2 values ('121213FM')
Insert Table2 values ('ABC000002821056')

----------------------------------------------

-- QUERY THAT IS TAKING 40 seconds to return data.
-- I need to find all data from table1 that does not have a matching [NUM] from table2
-- Rows Returned: 290,000 (which is almost all of the data from table1)

SELECT   T1.Amt, 
    T1.Code,
    T1.Description,
    T1.Num
  FROM Table1 T1 (NOLOCK)
  LEFT JOIN (SELECT DISTINCT NUM FROM TABLE2 (NOLOCK)) T2
   ON T1.Num = T2.NUM
  WHERE T2.Num IS NULL


---------------------------------------------- 


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>