Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
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: 409 | Views in the last 30 days: 2
 
Related Articles
FORUM

Is always clustered index better than non-clustered index ?

Is always clustered index better than non-clustered index ?

FORUM

Partitioning key examples vs clustered index rules

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

FORUM

Index

index

FORUM

INDEX REBUILD

Rebuilding indexes for better performance.

ARTICLE

Contact us

Learn how to contact the staff at SQLServerCentral.com

Tags
miscellaneous    
t-sql    
 
Contribute

Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones
Editor, SQLServerCentral.com

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones