Technical Article

Improving performance on joins to large tables.

,

In your tenure as a DBA/developer, you've probably been asked to write dozens of stored procedures similar to this:

CREATE PROCEDURE ContactInfo
@ContactID int
AS
SELECT c.Name, a.Address, p.Phone
FROM Contact c
LEFT JOIN ContactAddress a
ON c.ContactID = a.ContactID
LEFT JOIN ContactPhone p
ON c.ContactID = p.ContactID
WHERE c.ContactID = @ContactID

But there is a more efficient way to write such a query.....particularly if you are joining onto very large tables.  It involves using derived tables with the stored procedure parameters imbedded within them, as the following script shows.  In my tests, I ran this query with STATISTICS TIME set on, and it reduced the CPU Time and Elapsed Time from 16 ms to 0 ms, and 263 ms to 15 ms, respectively.

(Note: if you're running version 2000, you can improve this even more by rewriting the derived tables as UDFs accepting a @ContactID parameter.)

/* old inefficient query */
SELECT *
FROM Contact c
LEFT JOIN CONAddress a
ON c.ContactID = a.ContactID
LEFT JOIN CONPhoneEmail p
ON c.ContactID = p.ContactID
WHERE c.ContactID = @ContactID

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

/* new query; runs faster */
SELECT *
FROM (SELECT * FROM Contact WHERE ContactID = @ContactID) c
LEFT JOIN (SELECT * FROM CONAddress WHERE ContactID = @ContactID) a
ON c.ContactID = a.ContactID
LEFT JOIN (SELECT * FROM CONPhoneEmail WHERE ContactID = @ContactID) p
ON c.ContactID = p.ContactID

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

Rate

4 (1)

You rated this post out of 5. Change rating

Share

Share

Rate

4 (1)

You rated this post out of 5. Change rating