SQL Clone
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

An alternative to self-joins

By Cade Bryant,

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.

Total article views: 423 | Views in the last 30 days: 1
Related Articles

Is always clustered index better than non-clustered index ?

Is always clustered index better than non-clustered index ?


Partitioning key examples vs clustered index rules

Examples about partitioning do not follow the rules für clustered indexes. can someone combine those...






Rebuilding indexes for better performance.


Targeted Index Performance Improvements

This article identifies which indexes are used when T-SQL code runs, and proposes ways of improving ...