36 Chambers – The Legendary Journeys: Execution to the max!

January 11, 2013

Parentheses Around Joins

Filed under: Database Administration — Kevin Feasel @ 7:00 pm

This is something that I just learned about recently.

Here’s the scenario:  we have four tables.  A User has separate OAuth authorization types (for example, Facebook, Google, and Twitter), which we track through the UserAuthorization table.   Finally, each user has a number of items that they have to offer, but not all items need to be tied to a user.

The question that the following query tries to answer is, which items are either not owned by a user at all, or are owned by a user who has linked their Twitter account to the application?  In this case, we only want to get the Username value for users who have Twitter; if they don’t have Twitter, we don’t want to see the username at all.  This is kind of a silly query, but bear with me.  It turns out that you can use parentheses to direct inner and outer joins, allowing us to answer exactly this question.

select
	i.ID,
	u.Username
from
	dbo.Item i
	LEFT OUTER JOIN
	(
		dbo.[User] u
		INNER JOIN dbo.UserAuthorization ua on ua.UserId = u.Id
		INNER JOIN Lookup.OAuthType ot
			on ua.OAuthTypeId = ot.id
			and ot.Name = 'Twitter'
	) on i.UserId = u.Id;

This nested join means that we only get records back from the User table if there is a Twitter handle, but we do not exclude any records from the Item table; neither do we include any users who do not have Twitter handles.

There are other ways of doing this, such as two queries using a UNION ALL.  This is a succinct way of doing that, however, and could potentially be better for performance, because it would not need to scan the Item table twice (once for each side of the UNION ALL).

About these ads

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 43 other followers

%d bloggers like this: