SQL Server Central is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
Search:  
 
 

An alternative to self-joins

By Cade Bryant, 2003/07/18

Total article views: 140 | Views in the last 30 days: 4

Oftentimes there is a need to retrieve different types of the same object (e.g. contacts).  For example, in a Contacts database, you might have a Contact table containing many different types of contacts (employees, customers, suppliers, etc).  Typically, a user might need to see a report of all different types of contacts for an order (e.g., the customer who placed the order, the employee who took the order, etc.).

Most SQL developers use self-joins to accomplish this, as example 1 in the script window demonstrates (note: I am only using a single table for illustration purposes).  Although this does the job, you should know that there is an alternate way to do this (using aggregates and CASE statements) that can often result far fewer scans and better performance, as example 2 below shows.

During my testing while running the graphical showplan,  example 2 only required a Compute Scalar and a Clustered Index Scan (I probably could have gotten even better perormance if my company's database had been indexed better).  Example 1, however, required 6 Merge Join operations and 7 Index Scans.  In addition, example 2 requires far less coding.

While I can't guarantee that this method will result in improved performance in your environment, it's always helpful to now that there is more than one way to perform common programming operations.

By Cade Bryant, 2003/07/18

Total article views: 140 | Views in the last 30 days: 4
Your response
 
 
Related tags

Miscellaneous    
T-SQL Aids    
 
Already registered?  

Free registration required

To read the rest of this article, and access thousands of other articles, we ask you to register on the site and subscribe to our newsletters.

Register

E-mail address:
Password:
Password (confirm):

  

Subscriptions

We ask you to register on the site and subscribe to our newsletters. Subscribing to our newsletters gets you:

  • ALL of our content (thousands of articles, scripts, and forum postings)
  • A daily newsletter (example)
  • A weekly news round up (example)
  • The opportunity to ask and answer questions in our forums
  • A daily Question of the Day to test and help you increase your knowledge of SQL Server.

We ask that you give the newsletter a try for a week. Over 200,000 SQL Server Professionals a day find it entertaining and useful. If not, you are welcome to unsubscribe at anytime.

Steve Jones
Editor, SQLServerCentral.com