Speed up MS SQL link server query time by using Openquery()


Very often, we will do SQL query like the below example and then we complaint link server is slow.
Example 1: Slow

SELECT TOP 10 *
FROM LINKED_SERVER.MYDB.dbo.TBL_A A
INNER JOIN 
LINKED_SERVER.MYDB.dbo.TBL_B B
ON A.KEY = B.KEY
WHERE A.TITLE = 'MANAGER'
AND B.DATE BETWEEN '2009-12-01' AND '2010-01-01'

It is slow, because the all rows of the 2 tables will be pulled from the remote server to local server's tempdb,  and then the filters are applied locally. Bad news for big tables.
How about the second example:


Example 2: Fast

SELECT * FROM OPENQUERY(LINKED_SERVER,
'SELECT TOP 10 *
FROM 
MYDB.dbo.TBL_A A
INNER JOIN 
MYDB.dbo.TBL_B B
ON 
A.KEY = B.KEY
WHERE 
A.TITLE = ''MANAGER''
AND 
B.DATE BETWEEN ''2009-12-01'' AND ''2010-01-01''')

OPENQUERY is a passthrough query which the select statement (or any other SQL statement) inside the OPENQUERY is executed on the remote machine. The returned result is retrieved into the local tempdb for the join statement to executed locally.

Please note the "single quotation" in the original SQL statement is "escaped" on the second SQL statement by double the single quote.

Speeding up SQL =/= buying expensive hardware.


Comments

Popular Posts