<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tech News, Tech Resources, Technology Articles, Gadget News, Computer News &#187; SQL</title>
	<atom:link href="http://www.comteken.com/tag/sql/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.comteken.com</link>
	<description>IT news, software technology, IT resources, computer software, laptops, desktops,  information systems,  hardware technology, multimedia, Windows OS, linux clients, network solution, easy internet, essential guides, domains, webhosting, web program, database programming</description>
	<lastBuildDate>Fri, 27 Jan 2012 11:22:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>SQL Performance &#8211; Clustered Indexes</title>
		<link>http://www.comteken.com/database-programming/sql-performance-clustered-indexes/</link>
		<comments>http://www.comteken.com/database-programming/sql-performance-clustered-indexes/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 16:12:58 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Database Programming]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.comteken.com/?p=47</guid>
		<description><![CDATA[<a href="http://www.comteken.com/database-programming/sql-performance-clustered-indexes/"><img align="left" hspace="5" width="100" height="100" src="http://www.comteken.com/wp-content/plugins/thumbnail-for-excerpts/tfe_no_thumb.png" class="alignleft wp-post-image tfe" alt="" title="" /></a>Assumptions If you are reading this article, you should already have a working knowledge of SQL and are familiar with filtering your data with a WHERE clause, or limiting your result set from joining other tables with an ON clause. The part where this article comes in is when you start to see a significant [...]]]></description>
			<content:encoded><![CDATA[<h3>Assumptions</h3>
<p>If you are reading this article, you should already have a working knowledge of SQL and are familiar with filtering your data with a WHERE clause, or limiting your result set from joining other tables with an ON clause.</p>
<p>The part where this article comes in is when you start to see a significant amount of time passing while your once simple query is now hitting your production tables which are multitudes bigger than your test data.</p>
<p>This article is not just for those of you who are seeing your queries start to take 30 seconds or more, but everyone could probably benefit from this simple article.</p>
<h3>First of All &#8211; What is Slow?</h3>
<p>In my opinion, 98% of the queries you are running should fire in less than 1 second. That may sound bold (and perhaps to some even foolish) but in truth if you know what you are doing your queries themselves should be very fast and your slow down will be your network traffic if you are hitting a different server for your data.</p>
<p>I have created and worked with databases ranging from just a few thousand records to the hundreds of millions. And my &#8220;lookup&#8221; queries for finding records (whether customers or products or nearby store locations) all take sub-second. The key, is not just a good index&#8230; but rather, a good set of indexes. And more importantly the right index for the right job.</p>
<h3>They Clustered my What?</h3>
<p>If you are using Microsoft Enterprise Manager for SQL Server 2000 databases, or Microsoft SQL Server Management Studio for 2005 databases, or even just using Visual Studio for small SQL Express databases (such as the one used for this website) then you will likely notice the &#8220;Primary Key&#8221; button that sets your currently selected column into the primary key column for your table. A primary key is a &#8220;unique&#8221; index, but it also defaults to being a &#8220;clustered&#8221; index in the above mentioned IDE&#8217;s and probably more.</p>
<p>Why is that important to know? For starters, you only get one clustered index per table. Secondly, your clustered index will also determine the default sorting of your select statements. It also can be your biggest performance loss when you are inserting or updating data in that table.</p>
<p>If the data in your table will rarely change and you use it basically to join to get a friendly name, or to filter out records not in a certain group, then you would just leave the clustered primary key alone. Even if your table changes fairly often such as a &#8220;store locations&#8221; table where you might have a few thousand stores across the country and they change their phone numbers or address etc., you would still likely just leave the index alone.</p>
<h3>So When Do I Cluster?</h3>
<p>If you had a table filled with customer data, and you need to find a record based on &#8220;Last Name&#8221; and &#8220;Zip Code&#8221; then you might find yourself waiting a good while (or worse yet timing out) while your query is being processed. Now is the time to remove the &#8220;cluster&#8221; from your primary key field (remember you only get one cluster so you have to remove it from the primary key). Now that you have done that you can create a new index, and of course you are going to set it as a &#8220;clustered&#8221; index. The columns, in this order, that you will add is &#8220;LastName,FirstName&#8221;. Now you might be asking &#8220;why didn&#8217;t we cluster &#8216;LastName,ZipCode&#8217; since that is what we are searching on?&#8221;</p>
<p>That&#8217;s a great question, and the answer is this: You really only need to cluster &#8220;LastName&#8221; as that will be more than good enough to drop your search query down to sub second even if you have millions of records. Adding &#8220;Zip Code&#8221; to your search will simply help you limit the result set for someone searching for &#8216;Smith&#8217; which would return just too many records to look at. So, we know we don&#8217;t need to add &#8220;ZipCode&#8221; to the cluster, but why did we add &#8220;FirstName&#8221;? The answer to that is something I mentioned above. And I&#8217;ll explain now.</p>
<h3>Default Sort Benefits</h3>
<p>Your clustered index will tell SQL Server how to sort results given to you by default. So if you do a &#8220;SELECT * FROM dbo.MyTable&#8221; then you&#8217;d simply get all the records from that table as they were entered. But, if you had a clustered index on &#8220;LastName,FirstName&#8221; then you&#8217;d get all the records sorted by &#8220;LastName&#8221; then &#8220;FirstName&#8221;. So in our scenario above of the &#8216;Customer Search&#8217; we now get the benefit of displaying the results to the user for his search in alphabetical order which helps him to find the record he wanted a lot faster.</p>
<p>There are a lot of other benefits of clustered indexes, and there is so much to go over, but for now I&#8217;ll leave it at that. Remember your primary key column is probably defaulted as &#8220;clustered&#8221; which is fine for most scenarios, but you might want to change it one day. Also, keep in mind that you only get one clustered index per table, so use it wisely. Lastly, keep in mind that fiddling with clustered indexes could effect your INSERT or UPDATE code, so make sure to check the performance of these if it is a factor for you.</p>
<p>Source:singingeels.com</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;title=SQL%20Performance%20-%20Clustered%20Indexes&amp;bodytext=Assumptions%0D%0AIf%20you%20are%20reading%20this%20article%2C%20you%20should%20already%20have%20a%20working%20knowledge%20of%20SQL%20and%20are%20familiar%20with%20filtering%20your%20data%20with%20a%20WHERE%20clause%2C%20or%20limiting%20your%20result%20set%20from%20joining%20other%20tables%20with%20an%20ON%20clause.%0D%0A%0D%0AThe%20part%20where" title="Digg"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" /></a>
	<a rel="nofollow"  target="_blank" href="http://sphinn.com/index.php?c=post&amp;m=submit&amp;link=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F" title="Sphinn"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/sphinn.png" title="Sphinn" alt="Sphinn" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;title=SQL%20Performance%20-%20Clustered%20Indexes&amp;notes=Assumptions%0D%0AIf%20you%20are%20reading%20this%20article%2C%20you%20should%20already%20have%20a%20working%20knowledge%20of%20SQL%20and%20are%20familiar%20with%20filtering%20your%20data%20with%20a%20WHERE%20clause%2C%20or%20limiting%20your%20result%20set%20from%20joining%20other%20tables%20with%20an%20ON%20clause.%0D%0A%0D%0AThe%20part%20where" title="del.icio.us"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;t=SQL%20Performance%20-%20Clustered%20Indexes" title="Facebook"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.mixx.com/submit?page_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;title=SQL%20Performance%20-%20Clustered%20Indexes" title="Mixx"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/mixx.png" title="Mixx" alt="Mixx" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;title=SQL%20Performance%20-%20Clustered%20Indexes&amp;annotation=Assumptions%0D%0AIf%20you%20are%20reading%20this%20article%2C%20you%20should%20already%20have%20a%20working%20knowledge%20of%20SQL%20and%20are%20familiar%20with%20filtering%20your%20data%20with%20a%20WHERE%20clause%2C%20or%20limiting%20your%20result%20set%20from%20joining%20other%20tables%20with%20an%20ON%20clause.%0D%0A%0D%0AThe%20part%20where" title="Google Bookmarks"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/googlebookmark.png" title="Google Bookmarks" alt="Google Bookmarks" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&amp;Url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;Title=SQL%20Performance%20-%20Clustered%20Indexes" title="BlinkList"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/blinklist.png" title="BlinkList" alt="BlinkList" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.diigo.com/post?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;title=SQL%20Performance%20-%20Clustered%20Indexes" title="Diigo"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/diigo.png" title="Diigo" alt="Diigo" /></a>
	<a rel="nofollow"  target="_blank" href="http://cgi.fark.com/cgi/fark/farkit.pl?h=SQL%20Performance%20-%20Clustered%20Indexes&amp;u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F" title="Fark"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/fark.png" title="Fark" alt="Fark" /></a>
	<a rel="nofollow"  target="_blank" href="http://faves.com/Authoring.aspx?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;title=SQL%20Performance%20-%20Clustered%20Indexes" title="Faves"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/bluedot.png" title="Faves" alt="Faves" /></a>
	<a rel="nofollow"  target="_blank" href="http://laaik.it/NewStoryCompact.aspx?uri=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;headline=SQL%20Performance%20-%20Clustered%20Indexes&amp;cat=5e082fcc-8a3b-47e2-acec-fdf64ff19d12" title="laaik.it"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/laaikit.png" title="laaik.it" alt="laaik.it" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;title=SQL%20Performance%20-%20Clustered%20Indexes&amp;source=Tech+News%2C+Tech+Resources%2C+Technology+Articles%2C+Gadget+News%2C+Computer+News+IT+news%2C+software+technology%2C+IT+resources%2C+computer+software%2C+laptops%2C+desktops%2C++information+systems%2C++hardware+technology%2C+multimedia%2C+Windows+OS%2C+linux+clients%2C+network+solution%2C+easy+internet%2C+essential+guides%2C+domains%2C+webhosting%2C+web+program%2C+database+programming&amp;summary=Assumptions%0D%0AIf%20you%20are%20reading%20this%20article%2C%20you%20should%20already%20have%20a%20working%20knowledge%20of%20SQL%20and%20are%20familiar%20with%20filtering%20your%20data%20with%20a%20WHERE%20clause%2C%20or%20limiting%20your%20result%20set%20from%20joining%20other%20tables%20with%20an%20ON%20clause.%0D%0A%0D%0AThe%20part%20where" title="LinkedIn"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/linkedin.png" title="LinkedIn" alt="LinkedIn" /></a>
	<a rel="nofollow"  target="_blank" href="https://favorites.live.com/quickadd.aspx?marklet=1&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;title=SQL%20Performance%20-%20Clustered%20Indexes" title="Live"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/live.png" title="Live" alt="Live" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.mister-wong.com/addurl/?bm_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;bm_description=SQL%20Performance%20-%20Clustered%20Indexes&amp;plugin=soc" title="MisterWong"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/misterwong.png" title="MisterWong" alt="MisterWong" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.myspace.com/Modules/PostTo/Pages/?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;t=SQL%20Performance%20-%20Clustered%20Indexes" title="MySpace"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/myspace.png" title="MySpace" alt="MySpace" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.netvibes.com/share?title=SQL%20Performance%20-%20Clustered%20Indexes&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F" title="Netvibes"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/netvibes.png" title="Netvibes" alt="Netvibes" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.netvouz.com/action/submitBookmark?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;title=SQL%20Performance%20-%20Clustered%20Indexes&amp;popup=no" title="Netvouz"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/netvouz.png" title="Netvouz" alt="Netvouz" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.newsvine.com/_tools/seed&amp;save?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;h=SQL%20Performance%20-%20Clustered%20Indexes" title="NewsVine"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/newsvine.png" title="NewsVine" alt="NewsVine" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.propeller.com/submit/?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F" title="Propeller"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/propeller.png" title="Propeller" alt="Propeller" /></a>
	<a rel="nofollow"  target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;title=SQL%20Performance%20-%20Clustered%20Indexes" title="Reddit"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" /></a>
	<a rel="nofollow"  target="_blank" href="http://slashdot.org/bookmark.pl?title=SQL%20Performance%20-%20Clustered%20Indexes&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F" title="Slashdot"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/slashdot.png" title="Slashdot" alt="Slashdot" /></a>
	<a rel="nofollow"  target="_blank" href="http://socialogs.com/add_story.php?story_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;story_title=SQL%20Performance%20-%20Clustered%20Indexes" title="Socialogs"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/socialogs.png" title="Socialogs" alt="Socialogs" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;title=SQL%20Performance%20-%20Clustered%20Indexes" title="StumbleUpon"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" /></a>
	<a rel="nofollow"  target="_blank" href="http://technorati.com/faves?add=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F" title="Technorati"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/technorati.png" title="Technorati" alt="Technorati" /></a>
	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=SQL%20Performance%20-%20Clustered%20Indexes%20-%20http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F" title="Twitter"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" /></a>
	<a rel="nofollow"  target="_blank" href="http://buzz.yahoo.com/submit/?submitUrl=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fsql-performance-clustered-indexes%2F&amp;submitHeadline=SQL%20Performance%20-%20Clustered%20Indexes&amp;submitSummary=Assumptions%0D%0AIf%20you%20are%20reading%20this%20article%2C%20you%20should%20already%20have%20a%20working%20knowledge%20of%20SQL%20and%20are%20familiar%20with%20filtering%20your%20data%20with%20a%20WHERE%20clause%2C%20or%20limiting%20your%20result%20set%20from%20joining%20other%20tables%20with%20an%20ON%20clause.%0D%0A%0D%0AThe%20part%20where&amp;submitCategory=science&amp;submitAssetType=text" title="Yahoo! Buzz"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/yahoobuzz.png" title="Yahoo! Buzz" alt="Yahoo! Buzz" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.comteken.com/database-programming/sql-performance-clustered-indexes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How To: Maintain Customer Payment History</title>
		<link>http://www.comteken.com/database-programming/how-to-maintain-customer-payment-history/</link>
		<comments>http://www.comteken.com/database-programming/how-to-maintain-customer-payment-history/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 16:11:03 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Database Programming]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.comteken.com/?p=44</guid>
		<description><![CDATA[<a href="http://www.comteken.com/database-programming/how-to-maintain-customer-payment-history/"><img align="left" hspace="5" width="100" height="100" src="http://www.comteken.com/wp-content/plugins/thumbnail-for-excerpts/tfe_no_thumb.png" class="alignleft wp-post-image tfe" alt="" title="" /></a>Creating and maintaining &#8216;customer&#8217; data is a common task that most people handle by creating a single table that holds a customer&#8217;s FirstName, LastName, Address, City, State, Zip etc. But when it comes to tracking changes in a customer record this type of table fails to provide needed functionality. This article will show how to [...]]]></description>
			<content:encoded><![CDATA[<p>Creating and maintaining &#8216;customer&#8217; data is a common task that most people handle by creating a single table that holds a customer&#8217;s FirstName, LastName, Address, City, State, Zip etc. But when it comes to tracking changes in a customer record this type of table fails to provide needed functionality. This article will show how to maintain a customer&#8217;s basic data (name, address etc.) and also keep track of transient data such as an &#8216;IsActive&#8217; status that is derived from whether or not the customer has paid for service within the last 30 days.</p>
<p>Since we will also want to keep a complete history of the customer&#8217;s payments, we can&#8217;t just add a single column to our table called &#8216;IsActive&#8217;. (Also, as a side point, proper naming conventions will help you to understand that if a column or property name starts with the word &#8220;Is&#8221; then you know right away that this is a derived or calculated value.) In our case, we are going to create a VIEW that will include all of the customer&#8217;s basic data and also a field indicating that the customer has paid within the past 30 days. To accomplish this, we will need to simple TABLEs.</p>
<h3>First &#8211; The Customers TABLE</h3>
<p>To start off easy, we are going to create a table to hold all of our customer data. We will call this table &#8216;Customers&#8217;. This table will contain an ID field of our customer as well as his name and address information. Our ID field will be the PRIMARY KEY for this table, and for now it can also be the CLUSTERED INDEX as well. (This is the default behavior if you are using the SQL Server 2000 or SQL Server 2005 IDE and you click the &#8220;Primary Key&#8221; button.) Here is our Customers table definition:</p>
<div><span>CREATE</span> <span>TABLE</span> dbo.Customers<br />
(<br />
ID <span>INT</span> <span>NOT</span> <span>NULL</span> <span>IDENTITY</span> (1, 1),<br />
FirstName <span>VARCHAR</span>(50) <span>NULL</span>,<br />
LastName <span>VARCHAR</span>(50) <span>NULL</span>,<br />
Address <span>VARCHAR</span>(50) <span>NULL</span>,<br />
City <span>VARCHAR</span>(50) <span>NULL</span>,<br />
State CHAR(2) <span>NULL</span>,<br />
Zip CHAR(5) <span>NULL</span><br />
)</p>
<p><span>ALTER</span> <span>TABLE</span> dbo.Customers <span>ADD</span> <span>CONSTRAINT</span><br />
PK_Customers <span>PRIMARY</span> <span>KEY</span> <span>CLUSTERED</span> ( ID )</div>
<h3>Second &#8211; The PaymentHistory TABLE</h3>
<p>Now that we have our simple Customers table, we are going to create they PaymentHistory table. This will keep track of all payments for all customers. The fields we are going to need are an ID field for each PaymentHistory record, the CustomerID to tie back to the customer and a DateTime field to let us know when the payment was made. Here is the SQL statment to create the PaymentHistory table.</p>
<div><span>CREATE</span> <span>TABLE</span> dbo.PaymentHistory<br />
(<br />
ID <span>int</span> <span>NOT</span> <span>NULL</span> <span>IDENTITY</span> (1, 1),<br />
CustomerID <span>int</span> <span>NOT</span> <span>NULL</span>,<br />
PaymentDate <span>datetime</span> <span>NOT</span> <span>NULL</span> <span>DEFAULT</span> <span>GETDATE</span>()<br />
)</p>
<p><span>ALTER</span> <span>TABLE</span> dbo.PaymentHistory <span>ADD</span> <span>CONSTRAINT</span><br />
PK_PaymentHistory <span>PRIMARY</span> <span>KEY</span> <span>NONCLUSTERED</span> ( ID )</p>
<p><span>CREATE</span> <span>CLUSTERED</span> <span>INDEX</span> IX_PaymentHistory_CLUSTERED<br />
<span>ON</span> dbo.PaymentHistory ( CustomerID, ID )</div>
<h3>Joining The Tables Together</h3>
<p>This is the PaymentHistory table that will be used to track when a customer has payed his bill, and will therefore have another 30 days of service. Notice that we didn&#8217;t use the default clustered index on the pimary key column for this table. The reason for this is that we will be joining to this table using the CustomerID field. By clustering this table first on CustomerID then on ID we will gain significant performance boosts when running joining or running aggregates using CustomerID as a parameter. We also chose to add the ID column as the second part of the clustered index so that our events will sort in order of payment history by default. This technique is discussed in another article on SingingEels.com &#8211; <a rel="nofollow" href="http://www.singingeels.com/Articles/SQL_Performance__Clustered_Indexes.aspx">&#8220;SQL Performance &#8211; Clustered Indexes&#8221;</a>.</p>
<p>What remains is for us to create a view that ties the two tables together. Our goal is to have all the customer information plus we want to know if the customer has paid within the last 30 days which indicates his being &#8216;active&#8217;. There are a few good ways to do this; we will look at 2 options and discuss the differences.</p>
<p>Our first method of tying the data together won&#8217;t involve using a JOIN statement. What we are going to do is simply select all the Customer data and add one column that will be the most recent payment date for the particular client. This will be accomplished using the MAX function to get the latest date and using a reference to the &#8220;parent&#8221; table (which in this case would be the Customers table) to ensure we only get the latest record for the specific customer in each record.</p>
<div><span>SELECT</span><br />
*,<br />
(<span>SELECT</span> <span>MAX</span>(PaymentDate) <span>FROM</span> dbo.PaymentHistory<br />
<span>WHERE</span> CustomerID = Customers.ID) <span>AS</span> LastPaymentDate<br />
<span>FROM</span><br />
dbo.Customers</div>
<p>This method above is fast and easy to do. The problem here comes in when you want more than one piece of data from the PaymentHistory table. To do that, you wouldn&#8217;t want to do another sub-query to the same table as this is now adding needless processing on the SQL side. Instead, to pull back multiple fields from the PaymentHisotry table we are going to use a JOIN. Keep in mind though that we don&#8217;t want all the records for each customer, but rather all we want is the latest record. This slight modification to the code above will allow us to get the last payment date as well as the ID of the payment record.</p>
<div><span>SELECT</span><br />
Customers.*,<br />
LatestPayments.*<br />
<span>FROM</span><br />
dbo.Customers <span>LEFT</span> <span>OUTER</span> <span>JOIN</span><br />
(<span>SELECT</span> CustomerID, <span>MAX</span>(ID) <span>AS</span> LastPaymentID, <span>MAX</span>(PaymentDate) <span>AS</span> LastPaymentDate<br />
<span>FROM</span> dbo.PaymentHistory <span>GROUP</span> <span>BY</span> CustomerID) LatestPayments<br />
<span>ON</span> Customers.ID = LatestPayments.CustomerID</div>
<p>In order to get the latest payment data for each customer we made an inline sub-query inside of our JOIN clause. This subquery basically acts just like a VIEW. In fact, if you made that query into a VIEW and called it LatestPayments, then you would be doing the exact same thing that SQL Server is doing in the background. What remains now is to use this logic to make our &#8220;IsActive&#8221; column based on whether or not the customer has made a payment within the past 30 days. This will be done using a CASE statement.</p>
<div><span>SELECT</span><br />
*,<br />
<span>CASE</span> <span>WHEN</span> ((<span>SELECT</span> <span>MAX</span>(PaymentDate) <span>FROM</span> dbo.PaymentHistory<br />
<span>WHERE</span> CustomerID = Customers.ID) &gt;= (<span>GETDATE</span>() &#8211; 30))<br />
<span>THEN</span> 1 <span>ELSE</span> 0 <span>END</span> <span>AS</span> IsActive<br />
<span>FROM</span><br />
dbo.Customers</div>
<p>This query above reads this way in english: &#8220;Get all the records from the customers table, and when the latest payment for the customer is less than 30 days old, then the customer is active, otherwise he is inactive.&#8221; Now you can make this query into a view and display it on a customer management page on your web application. You could also use this view to dis-allow users from accessing certain pages due to no longer being an active member of your site.</p>
<p>This pattern is easy to follow and it gives much flexibility with minimal code. You could adapt this to work with a &#8220;case management&#8221; solution where you need to track case status changes, a customer payment system or many other scenarios.</p>
<p>Source:singingeels.com</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;title=How%20To%3A%20Maintain%20Customer%20Payment%20History&amp;bodytext=Creating%20and%20maintaining%20%27customer%27%20data%20is%20a%20common%20task%20that%20most%20people%20handle%20by%20creating%20a%20single%20table%20that%20holds%20a%20customer%27s%20FirstName%2C%20LastName%2C%20Address%2C%20City%2C%20State%2C%20Zip%20etc.%20But%20when%20it%20comes%20to%20tracking%20changes%20in%20a%20customer%20record%20this%20t" title="Digg"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" /></a>
	<a rel="nofollow"  target="_blank" href="http://sphinn.com/index.php?c=post&amp;m=submit&amp;link=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F" title="Sphinn"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/sphinn.png" title="Sphinn" alt="Sphinn" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;title=How%20To%3A%20Maintain%20Customer%20Payment%20History&amp;notes=Creating%20and%20maintaining%20%27customer%27%20data%20is%20a%20common%20task%20that%20most%20people%20handle%20by%20creating%20a%20single%20table%20that%20holds%20a%20customer%27s%20FirstName%2C%20LastName%2C%20Address%2C%20City%2C%20State%2C%20Zip%20etc.%20But%20when%20it%20comes%20to%20tracking%20changes%20in%20a%20customer%20record%20this%20t" title="del.icio.us"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;t=How%20To%3A%20Maintain%20Customer%20Payment%20History" title="Facebook"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.mixx.com/submit?page_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;title=How%20To%3A%20Maintain%20Customer%20Payment%20History" title="Mixx"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/mixx.png" title="Mixx" alt="Mixx" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;title=How%20To%3A%20Maintain%20Customer%20Payment%20History&amp;annotation=Creating%20and%20maintaining%20%27customer%27%20data%20is%20a%20common%20task%20that%20most%20people%20handle%20by%20creating%20a%20single%20table%20that%20holds%20a%20customer%27s%20FirstName%2C%20LastName%2C%20Address%2C%20City%2C%20State%2C%20Zip%20etc.%20But%20when%20it%20comes%20to%20tracking%20changes%20in%20a%20customer%20record%20this%20t" title="Google Bookmarks"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/googlebookmark.png" title="Google Bookmarks" alt="Google Bookmarks" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&amp;Url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;Title=How%20To%3A%20Maintain%20Customer%20Payment%20History" title="BlinkList"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/blinklist.png" title="BlinkList" alt="BlinkList" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.diigo.com/post?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;title=How%20To%3A%20Maintain%20Customer%20Payment%20History" title="Diigo"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/diigo.png" title="Diigo" alt="Diigo" /></a>
	<a rel="nofollow"  target="_blank" href="http://cgi.fark.com/cgi/fark/farkit.pl?h=How%20To%3A%20Maintain%20Customer%20Payment%20History&amp;u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F" title="Fark"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/fark.png" title="Fark" alt="Fark" /></a>
	<a rel="nofollow"  target="_blank" href="http://faves.com/Authoring.aspx?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;title=How%20To%3A%20Maintain%20Customer%20Payment%20History" title="Faves"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/bluedot.png" title="Faves" alt="Faves" /></a>
	<a rel="nofollow"  target="_blank" href="http://laaik.it/NewStoryCompact.aspx?uri=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;headline=How%20To%3A%20Maintain%20Customer%20Payment%20History&amp;cat=5e082fcc-8a3b-47e2-acec-fdf64ff19d12" title="laaik.it"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/laaikit.png" title="laaik.it" alt="laaik.it" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;title=How%20To%3A%20Maintain%20Customer%20Payment%20History&amp;source=Tech+News%2C+Tech+Resources%2C+Technology+Articles%2C+Gadget+News%2C+Computer+News+IT+news%2C+software+technology%2C+IT+resources%2C+computer+software%2C+laptops%2C+desktops%2C++information+systems%2C++hardware+technology%2C+multimedia%2C+Windows+OS%2C+linux+clients%2C+network+solution%2C+easy+internet%2C+essential+guides%2C+domains%2C+webhosting%2C+web+program%2C+database+programming&amp;summary=Creating%20and%20maintaining%20%27customer%27%20data%20is%20a%20common%20task%20that%20most%20people%20handle%20by%20creating%20a%20single%20table%20that%20holds%20a%20customer%27s%20FirstName%2C%20LastName%2C%20Address%2C%20City%2C%20State%2C%20Zip%20etc.%20But%20when%20it%20comes%20to%20tracking%20changes%20in%20a%20customer%20record%20this%20t" title="LinkedIn"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/linkedin.png" title="LinkedIn" alt="LinkedIn" /></a>
	<a rel="nofollow"  target="_blank" href="https://favorites.live.com/quickadd.aspx?marklet=1&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;title=How%20To%3A%20Maintain%20Customer%20Payment%20History" title="Live"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/live.png" title="Live" alt="Live" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.mister-wong.com/addurl/?bm_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;bm_description=How%20To%3A%20Maintain%20Customer%20Payment%20History&amp;plugin=soc" title="MisterWong"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/misterwong.png" title="MisterWong" alt="MisterWong" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.myspace.com/Modules/PostTo/Pages/?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;t=How%20To%3A%20Maintain%20Customer%20Payment%20History" title="MySpace"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/myspace.png" title="MySpace" alt="MySpace" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.netvibes.com/share?title=How%20To%3A%20Maintain%20Customer%20Payment%20History&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F" title="Netvibes"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/netvibes.png" title="Netvibes" alt="Netvibes" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.netvouz.com/action/submitBookmark?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;title=How%20To%3A%20Maintain%20Customer%20Payment%20History&amp;popup=no" title="Netvouz"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/netvouz.png" title="Netvouz" alt="Netvouz" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.newsvine.com/_tools/seed&amp;save?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;h=How%20To%3A%20Maintain%20Customer%20Payment%20History" title="NewsVine"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/newsvine.png" title="NewsVine" alt="NewsVine" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.propeller.com/submit/?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F" title="Propeller"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/propeller.png" title="Propeller" alt="Propeller" /></a>
	<a rel="nofollow"  target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;title=How%20To%3A%20Maintain%20Customer%20Payment%20History" title="Reddit"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" /></a>
	<a rel="nofollow"  target="_blank" href="http://slashdot.org/bookmark.pl?title=How%20To%3A%20Maintain%20Customer%20Payment%20History&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F" title="Slashdot"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/slashdot.png" title="Slashdot" alt="Slashdot" /></a>
	<a rel="nofollow"  target="_blank" href="http://socialogs.com/add_story.php?story_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;story_title=How%20To%3A%20Maintain%20Customer%20Payment%20History" title="Socialogs"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/socialogs.png" title="Socialogs" alt="Socialogs" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;title=How%20To%3A%20Maintain%20Customer%20Payment%20History" title="StumbleUpon"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" /></a>
	<a rel="nofollow"  target="_blank" href="http://technorati.com/faves?add=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F" title="Technorati"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/technorati.png" title="Technorati" alt="Technorati" /></a>
	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=How%20To%3A%20Maintain%20Customer%20Payment%20History%20-%20http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F" title="Twitter"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" /></a>
	<a rel="nofollow"  target="_blank" href="http://buzz.yahoo.com/submit/?submitUrl=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fhow-to-maintain-customer-payment-history%2F&amp;submitHeadline=How%20To%3A%20Maintain%20Customer%20Payment%20History&amp;submitSummary=Creating%20and%20maintaining%20%27customer%27%20data%20is%20a%20common%20task%20that%20most%20people%20handle%20by%20creating%20a%20single%20table%20that%20holds%20a%20customer%27s%20FirstName%2C%20LastName%2C%20Address%2C%20City%2C%20State%2C%20Zip%20etc.%20But%20when%20it%20comes%20to%20tracking%20changes%20in%20a%20customer%20record%20this%20t&amp;submitCategory=science&amp;submitAssetType=text" title="Yahoo! Buzz"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/yahoobuzz.png" title="Yahoo! Buzz" alt="Yahoo! Buzz" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.comteken.com/database-programming/how-to-maintain-customer-payment-history/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Get Identity Field and More From Inserts</title>
		<link>http://www.comteken.com/database-programming/get-identity-field-and-more-from-inserts/</link>
		<comments>http://www.comteken.com/database-programming/get-identity-field-and-more-from-inserts/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 16:09:41 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Database Programming]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.comteken.com/?p=42</guid>
		<description><![CDATA[<a href="http://www.comteken.com/database-programming/get-identity-field-and-more-from-inserts/"><img align="left" hspace="5" width="100" height="100" src="http://www.comteken.com/wp-content/plugins/thumbnail-for-excerpts/tfe_no_thumb.png" class="alignleft wp-post-image tfe" alt="" title="" /></a>Often times when inserting a new record into a table that has an auto-key field (an identity field that is set to auto increment), you may need to get that new ID back to use in other SQL statments. This can be done with @@IDENTITY or SCOPE_IDENTITY(), but those methods are very limited when compared [...]]]></description>
			<content:encoded><![CDATA[<p>Often times when inserting a new record into a table that has an auto-key field (an identity field that is set to auto increment), you may need to get that new ID back to use in other SQL statments. This can be done with @@IDENTITY or SCOPE_IDENTITY(), but those methods are very limited when compared to the new OUTPUT clause in SQL Server 2005. This article will show how and when to use these powerful TSQL features.</p>
<p>The reason why I say that the @@IDENTITY and SCOPE_IDENTITY() options are limited is because 1) they only return numeric fields (so &#8220;uniqueidentifier&#8221; fields won&#8217;t work), 2) they can only return the field marked as the table &#8216;identity&#8217; (so you can&#8217;t get a different field that you may be using as the ID), 3) they cannot give back any other auto-generated data such as a timestamp field. Another huge failing is in the case of multiple inserts in one statement. The @@IDENTITY and SCOPE_IDENTITY() options will only return the last record insereted. So if your insert statement added five records, you would only get the ID of the last one.</p>
<h3>Intruducing The OUTPUT Clause</h3>
<p>SQL Server 2005 intruduces a really amazing new clause that can be used in DELETE, UPDATE and INSERT statements called &#8216;OUTPUT&#8217;. The syntax is easy to follow as you basically just append it to the end of your statement and treat it like a SELECT. This small bit of SQL will show how to get the ID column back from an INSERT using SCOPE_IDENTITY() compared to the OUTPUT clause.</p>
<div><span>&#8211; Here <span>is</span> the sample <span>table</span> we are going <span>to</span> work <span>with</span>.</span><br />
<span>CREATE</span> <span>TABLE</span> dbo.MicrosoftProducts<br />
(<br />
ID <span>INT</span> <span>NOT</span> <span>NULL</span> <span>IDENTITY</span> (1, 1),<br />
ProductName <span>VARCHAR</span>(50) <span>NOT</span> <span>NULL</span>,<br />
ProductDescription <span>VARCHAR</span>(1000) <span>NOT</span> <span>NULL</span>,<br />
EntryDate <span>DATETIME</span> <span>DEFAULT</span> <span>GETDATE</span>() <span>NOT</span> <span>NULL</span><br />
)<span></p>
<p>&#8211; This will <span>insert</span> a row <span>and</span> retrieve the ID field using <span>@@IDENTITY</span>.</span><br />
<span>INSERT</span> <span>INTO</span> dbo.MicrosoftProducts (ProductName, ProductDescription)<br />
<span>VALUES</span> (<span>&#8216;SQL Server 2005&#8242;</span>, <span>&#8216;The best version <span>of</span> SQL ever!&#8217;</span>)<br />
<span>SELECT</span> <span>@@IDENTITY</span><span></p>
<p>&#8211; Now using the <span>OUTPUT</span> clause <span>to</span> get the <span>identity</span> field.</span><br />
<span>INSERT</span> <span>INTO</span> dbo.MicrosoftProducts (ProductName, ProductDescription)<br />
<span>OUTPUT</span> INSERTED.ID<br />
<span>VALUES</span> (<span>&#8216;SQL Server 2005&#8242;</span>, <span>&#8216;The best version <span>of</span> SQL ever!&#8217;</span>)</div>
<p>At first glance, these three examples above may all seem equal. They all take the same amount of code, and they all return the identity field of the record that was just inserted. However, if we change the desired results slightly we can see the major failings of the first two, and we&#8217;ll see why the OUTPUT clause is so powerful.</p>
<p>Let&#8217;s say instead of just wanting to return the new ID to the user, we want to add the EntryDate field to the results that we send back to the user. With the first two options you would have to store the ID in a variable and re-query the table causing much unneeded overhead and code. Whereas with the OUTPUT clause, getting these results are very simple.</p>
<h3>Using @@IDENTITY or SCOPE_IDENTITY()</h3>
<div><span>&#8211; This <span>is</span> the same <span>with</span> <span>@@IDENTITY</span> <span>or</span> <span>SCOPE_IDENTITY</span>().</span><span><br />
&#8211; We have <span>to</span> hold the new ID <span>in</span> a variable.</span><br />
<span>DECLARE</span> @NewID <span>INT</span></p>
<p><span>INSERT</span> <span>INTO</span> dbo.MicrosoftProducts (ProductName, ProductDescription)<br />
<span>VALUES</span> (<span>&#8216;SQL Server 2005&#8242;</span>, <span>&#8216;The best version <span>of</span> SQL ever!&#8217;</span>)<span></p>
<p>&#8211; Now we have <span>to</span> assign that variable <span>with</span> the new ID.</span><br />
<span>SELECT</span> @NewID = <span>SCOPE_IDENTITY</span>()<span></p>
<p>&#8211; Now we have <span>to</span> re-query the <span>table</span> just <span>to</span> get the two fields.</span><br />
<span>SELECT</span> ID, EntryDate <span>FROM</span> dbo.MicrosoftProducts <span>WHERE</span> ID = @NewID</div>
<h3>Using The OUTPUT Clause</h3>
<div><span>&#8211; <span>All</span> we do <span>is</span> <span>add</span> another field <span>to</span> our <span>OUTPUT</span> clause.</span><br />
<span>INSERT</span> <span>INTO</span> dbo.MicrosoftProducts (ProductName, ProductDescription)<br />
<span>OUTPUT</span> INSERTED.ID, INSERTED.EntryDate<br />
<span>VALUES</span> (<span>&#8216;SQL Server 2005&#8242;</span>, <span>&#8216;The best version <span>of</span> SQL ever!&#8217;</span>)</div>
<p>If that is all the OUTPUT clause could do, it would be worth using. But keep in mind that you can also use it to return multiple results if your insert was more than one record. Another great benefit of the OUTPUT clause is that you can use it for DELETEs and UPDATEs as well. So if you wanted to delete some records based on user input and then show them in a GridView what records have been removed, you could do it in one clean step.</p>
<div><span>DELETE</span> <span>FROM</span> dbo.MicrosoftProducts <span>OUTPUT</span> DELETED.*</div>
<p>The syntax for UPDATEs is a little different, but even more powerful. There is no &#8220;UPDATED&#8221; object, but rather you can use &#8220;DELETED&#8221; or &#8220;INSERTED&#8221; to represent the list of columns before the change and after the change respectively. Example:</p>
<div><span>UPDATE</span> dbo.MicrosoftProducts <span>SET</span> ProductName = <span>&#8216;Test&#8217;</span><br />
<span>OUTPUT</span> DELETED.ProductName <span>AS</span> TheBefore, INSERTED.ProductName <span>AS</span> TheAfter</div>
<div></div>
<div>Source:singingeels.com</div>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;title=Get%20Identity%20Field%20and%20More%20From%20Inserts&amp;bodytext=Often%20times%20when%20inserting%20a%20new%20record%20into%20a%20table%20that%20has%20an%20auto-key%20field%20%28an%20identity%20field%20that%20is%20set%20to%20auto%20increment%29%2C%20you%20may%20need%20to%20get%20that%20new%20ID%20back%20to%20use%20in%20other%20SQL%20statments.%20This%20can%20be%20done%20with%20%40%40IDENTITY%20or%20SCOPE_IDENTITY%28" title="Digg"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" /></a>
	<a rel="nofollow"  target="_blank" href="http://sphinn.com/index.php?c=post&amp;m=submit&amp;link=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F" title="Sphinn"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/sphinn.png" title="Sphinn" alt="Sphinn" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;title=Get%20Identity%20Field%20and%20More%20From%20Inserts&amp;notes=Often%20times%20when%20inserting%20a%20new%20record%20into%20a%20table%20that%20has%20an%20auto-key%20field%20%28an%20identity%20field%20that%20is%20set%20to%20auto%20increment%29%2C%20you%20may%20need%20to%20get%20that%20new%20ID%20back%20to%20use%20in%20other%20SQL%20statments.%20This%20can%20be%20done%20with%20%40%40IDENTITY%20or%20SCOPE_IDENTITY%28" title="del.icio.us"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;t=Get%20Identity%20Field%20and%20More%20From%20Inserts" title="Facebook"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.mixx.com/submit?page_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;title=Get%20Identity%20Field%20and%20More%20From%20Inserts" title="Mixx"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/mixx.png" title="Mixx" alt="Mixx" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;title=Get%20Identity%20Field%20and%20More%20From%20Inserts&amp;annotation=Often%20times%20when%20inserting%20a%20new%20record%20into%20a%20table%20that%20has%20an%20auto-key%20field%20%28an%20identity%20field%20that%20is%20set%20to%20auto%20increment%29%2C%20you%20may%20need%20to%20get%20that%20new%20ID%20back%20to%20use%20in%20other%20SQL%20statments.%20This%20can%20be%20done%20with%20%40%40IDENTITY%20or%20SCOPE_IDENTITY%28" title="Google Bookmarks"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/googlebookmark.png" title="Google Bookmarks" alt="Google Bookmarks" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&amp;Url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;Title=Get%20Identity%20Field%20and%20More%20From%20Inserts" title="BlinkList"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/blinklist.png" title="BlinkList" alt="BlinkList" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.diigo.com/post?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;title=Get%20Identity%20Field%20and%20More%20From%20Inserts" title="Diigo"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/diigo.png" title="Diigo" alt="Diigo" /></a>
	<a rel="nofollow"  target="_blank" href="http://cgi.fark.com/cgi/fark/farkit.pl?h=Get%20Identity%20Field%20and%20More%20From%20Inserts&amp;u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F" title="Fark"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/fark.png" title="Fark" alt="Fark" /></a>
	<a rel="nofollow"  target="_blank" href="http://faves.com/Authoring.aspx?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;title=Get%20Identity%20Field%20and%20More%20From%20Inserts" title="Faves"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/bluedot.png" title="Faves" alt="Faves" /></a>
	<a rel="nofollow"  target="_blank" href="http://laaik.it/NewStoryCompact.aspx?uri=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;headline=Get%20Identity%20Field%20and%20More%20From%20Inserts&amp;cat=5e082fcc-8a3b-47e2-acec-fdf64ff19d12" title="laaik.it"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/laaikit.png" title="laaik.it" alt="laaik.it" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;title=Get%20Identity%20Field%20and%20More%20From%20Inserts&amp;source=Tech+News%2C+Tech+Resources%2C+Technology+Articles%2C+Gadget+News%2C+Computer+News+IT+news%2C+software+technology%2C+IT+resources%2C+computer+software%2C+laptops%2C+desktops%2C++information+systems%2C++hardware+technology%2C+multimedia%2C+Windows+OS%2C+linux+clients%2C+network+solution%2C+easy+internet%2C+essential+guides%2C+domains%2C+webhosting%2C+web+program%2C+database+programming&amp;summary=Often%20times%20when%20inserting%20a%20new%20record%20into%20a%20table%20that%20has%20an%20auto-key%20field%20%28an%20identity%20field%20that%20is%20set%20to%20auto%20increment%29%2C%20you%20may%20need%20to%20get%20that%20new%20ID%20back%20to%20use%20in%20other%20SQL%20statments.%20This%20can%20be%20done%20with%20%40%40IDENTITY%20or%20SCOPE_IDENTITY%28" title="LinkedIn"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/linkedin.png" title="LinkedIn" alt="LinkedIn" /></a>
	<a rel="nofollow"  target="_blank" href="https://favorites.live.com/quickadd.aspx?marklet=1&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;title=Get%20Identity%20Field%20and%20More%20From%20Inserts" title="Live"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/live.png" title="Live" alt="Live" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.mister-wong.com/addurl/?bm_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;bm_description=Get%20Identity%20Field%20and%20More%20From%20Inserts&amp;plugin=soc" title="MisterWong"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/misterwong.png" title="MisterWong" alt="MisterWong" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.myspace.com/Modules/PostTo/Pages/?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;t=Get%20Identity%20Field%20and%20More%20From%20Inserts" title="MySpace"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/myspace.png" title="MySpace" alt="MySpace" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.netvibes.com/share?title=Get%20Identity%20Field%20and%20More%20From%20Inserts&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F" title="Netvibes"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/netvibes.png" title="Netvibes" alt="Netvibes" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.netvouz.com/action/submitBookmark?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;title=Get%20Identity%20Field%20and%20More%20From%20Inserts&amp;popup=no" title="Netvouz"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/netvouz.png" title="Netvouz" alt="Netvouz" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.newsvine.com/_tools/seed&amp;save?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;h=Get%20Identity%20Field%20and%20More%20From%20Inserts" title="NewsVine"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/newsvine.png" title="NewsVine" alt="NewsVine" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.propeller.com/submit/?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F" title="Propeller"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/propeller.png" title="Propeller" alt="Propeller" /></a>
	<a rel="nofollow"  target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;title=Get%20Identity%20Field%20and%20More%20From%20Inserts" title="Reddit"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" /></a>
	<a rel="nofollow"  target="_blank" href="http://slashdot.org/bookmark.pl?title=Get%20Identity%20Field%20and%20More%20From%20Inserts&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F" title="Slashdot"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/slashdot.png" title="Slashdot" alt="Slashdot" /></a>
	<a rel="nofollow"  target="_blank" href="http://socialogs.com/add_story.php?story_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;story_title=Get%20Identity%20Field%20and%20More%20From%20Inserts" title="Socialogs"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/socialogs.png" title="Socialogs" alt="Socialogs" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;title=Get%20Identity%20Field%20and%20More%20From%20Inserts" title="StumbleUpon"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" /></a>
	<a rel="nofollow"  target="_blank" href="http://technorati.com/faves?add=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F" title="Technorati"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/technorati.png" title="Technorati" alt="Technorati" /></a>
	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=Get%20Identity%20Field%20and%20More%20From%20Inserts%20-%20http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F" title="Twitter"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" /></a>
	<a rel="nofollow"  target="_blank" href="http://buzz.yahoo.com/submit/?submitUrl=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fget-identity-field-and-more-from-inserts%2F&amp;submitHeadline=Get%20Identity%20Field%20and%20More%20From%20Inserts&amp;submitSummary=Often%20times%20when%20inserting%20a%20new%20record%20into%20a%20table%20that%20has%20an%20auto-key%20field%20%28an%20identity%20field%20that%20is%20set%20to%20auto%20increment%29%2C%20you%20may%20need%20to%20get%20that%20new%20ID%20back%20to%20use%20in%20other%20SQL%20statments.%20This%20can%20be%20done%20with%20%40%40IDENTITY%20or%20SCOPE_IDENTITY%28&amp;submitCategory=science&amp;submitAssetType=text" title="Yahoo! Buzz"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/yahoobuzz.png" title="Yahoo! Buzz" alt="Yahoo! Buzz" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.comteken.com/database-programming/get-identity-field-and-more-from-inserts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pagination In SQL Server 2005</title>
		<link>http://www.comteken.com/database-programming/pagination-in-sql-server-2005/</link>
		<comments>http://www.comteken.com/database-programming/pagination-in-sql-server-2005/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 16:08:36 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Database Programming]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[SQL Server 2005]]></category>

		<guid isPermaLink="false">http://www.comteken.com/?p=40</guid>
		<description><![CDATA[<a href="http://www.comteken.com/database-programming/pagination-in-sql-server-2005/"><img align="left" hspace="5" width="100" src="http://www.singingeels.com/Articles/UserImage.aspx?ImageID=4ee676e0-26a2-487e-a8f0-daa2202944bb" class="alignleft wp-post-image tfe" alt="SQL results for " title="SQL results for " /></a>If you&#8217;ve used other flavors of SQL (such as MySQL or PostgreSQL) and now you have switched over to TSQL (Microsoft SQL Server) you may have noticed that there is no native way of doing pagination. In some SQL versions, pagination was as easy as &#8220;SELECT * FROM &#8216;myTable&#8217; LIMIT 0, 10&#8243; and that would [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve used other flavors of SQL (such as MySQL or PostgreSQL) and now you have switched over to TSQL (Microsoft SQL Server) you may have noticed that there is no native way of doing pagination. In some SQL versions, pagination was as easy as &#8220;SELECT * FROM &#8216;myTable&#8217; LIMIT 0, 10&#8243; and that would pull out the first 10 records from your table. SQL Server 2005 introduced a beautiful new world of &#8216;ranking functions&#8217;, one of which we can use to easily perform pagination directly in SQL.</p>
<p>While these other flavors of SQL implimented pagination only for the sake of pagination &#8211; meaning the absolutely only reason for the functions is to limit results sets into &#8216;pages&#8217; of data &#8211; SQL Server 2005&#8242;s ranking functions provide a lot of power and information. However, for this article, we are only going to demonstrate how to use these abilities for the sake of pagination.</p>
<h3>RowNumber In SQL</h3>
<p>First of all, we&#8217;ll need to get the &#8220;row number&#8221; from a result set. This is the basis of pagination because you need to know what row you are on to begin demanding only a subset from SQL. First we&#8217;ll do just a basic query and look at the results:</p>
<div><span>SELECT</span><br />
*<br />
<span>FROM</span><br />
dbo.Customers<br />
<span>ORDER</span> <span>BY</span><br />
LastName, FirstName</div>
<p>This query above will display the following results:</p>
<p><img title="SQL results for 'customer' table without pagination" src="http://www.singingeels.com/Articles/UserImage.aspx?ImageID=4ee676e0-26a2-487e-a8f0-daa2202944bb" alt="SQL results for 'customer' table without pagination" /></p>
<p>Now we&#8217;ll make a slight modification to add a &#8220;RowNumber&#8221; field.</p>
<div><span>SELECT</span><br />
ROW_NUMBER() <span>OVER</span> (<span>ORDER</span> <span>BY</span> LastName, FirstName) <span>AS</span> RowNumber,<br />
*<br />
<span>FROM</span><br />
dbo.Customers</div>
<p>This syntax may look a little odd, but it&#8217;s not that difficult. First of all, the ROW_NUMBER() function (just like all other &#8216;ranking functions&#8217; in SQL SERVER 2005) needs an OVER clause. Notice that we moved the ORDER BY clause inside the OVER clause. Basically what this is doing is telling SQL how we want the ROW_NUMBER() function to number each record. So we are telling SQL to number the records 1, 2, 3, 4 in the order of LastName then FirstName. Here are the results:</p>
<p><img title="SQL results for 'customer' table with pagination" src="http://www.singingeels.com/Articles/UserImage.aspx?ImageID=89cab536-9790-4edd-a3f0-9aa243104ddc" alt="SQL results for 'customer' table with pagination" /></p>
<p>So now that we have a &#8220;RowNumber&#8221; field, we can add a simple WHERE clause to get only a limited number of records. We will have to wrap query in another SELECT statment so that we can use all of our dynamic columns (such as our RowNumber column) by their names that we assigned them. Also, I&#8217;m going to use the TOP clause to limit the query to only return 2 records at a time. Lets see the query, and the results:</p>
<div><span>SELECT</span> <span>TOP</span> 2 * <span>FROM</span> (<span>SELECT</span><br />
ROW_NUMBER() <span>OVER</span> (<span>ORDER</span> <span>BY</span> LastName, FirstName) <span>AS</span> RowNumber,<br />
*<br />
<span>FROM</span><br />
dbo.Customers) _myResults<br />
<span>WHERE</span><br />
RowNumber &gt; 2</div>
<p>Notice I &#8216;aliased&#8217; the first query and called it &#8220;_myResults&#8221;. This basically treats that inner query as a VIEW so that I could pull out that first column by it&#8217;s name, RowNumber. Here are the results:</p>
<p><img title="Paginated SQL results for 'customer' table" src="http://www.singingeels.com/Articles/UserImage.aspx?ImageID=81d89626-1ba8-424d-965a-fea3eccf29be" alt="Paginated SQL results for 'customer' table" /></p>
<h3>Conclusion</h3>
<p>Though it may seem like you have to do a lot more work in order to get pagination in SQL Server 2005, the pay-off is that not only does the code make sense, but you gain a lot more power with the ranking functions TSQL. Try playing around with the parameters to see how they affect your queries and what you can do with them.</p>
<p>Source:singingeels.com</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;title=Pagination%20In%20SQL%20Server%202005&amp;bodytext=If%20you%27ve%20used%20other%20flavors%20of%20SQL%20%28such%20as%20MySQL%20or%20PostgreSQL%29%20and%20now%20you%20have%20switched%20over%20to%20TSQL%20%28Microsoft%20SQL%20Server%29%20you%20may%20have%20noticed%20that%20there%20is%20no%20native%20way%20of%20doing%20pagination.%20In%20some%20SQL%20versions%2C%20pagination%20was%20as%20easy%20as%20%22SEL" title="Digg"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" /></a>
	<a rel="nofollow"  target="_blank" href="http://sphinn.com/index.php?c=post&amp;m=submit&amp;link=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F" title="Sphinn"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/sphinn.png" title="Sphinn" alt="Sphinn" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;title=Pagination%20In%20SQL%20Server%202005&amp;notes=If%20you%27ve%20used%20other%20flavors%20of%20SQL%20%28such%20as%20MySQL%20or%20PostgreSQL%29%20and%20now%20you%20have%20switched%20over%20to%20TSQL%20%28Microsoft%20SQL%20Server%29%20you%20may%20have%20noticed%20that%20there%20is%20no%20native%20way%20of%20doing%20pagination.%20In%20some%20SQL%20versions%2C%20pagination%20was%20as%20easy%20as%20%22SEL" title="del.icio.us"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;t=Pagination%20In%20SQL%20Server%202005" title="Facebook"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.mixx.com/submit?page_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;title=Pagination%20In%20SQL%20Server%202005" title="Mixx"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/mixx.png" title="Mixx" alt="Mixx" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;title=Pagination%20In%20SQL%20Server%202005&amp;annotation=If%20you%27ve%20used%20other%20flavors%20of%20SQL%20%28such%20as%20MySQL%20or%20PostgreSQL%29%20and%20now%20you%20have%20switched%20over%20to%20TSQL%20%28Microsoft%20SQL%20Server%29%20you%20may%20have%20noticed%20that%20there%20is%20no%20native%20way%20of%20doing%20pagination.%20In%20some%20SQL%20versions%2C%20pagination%20was%20as%20easy%20as%20%22SEL" title="Google Bookmarks"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/googlebookmark.png" title="Google Bookmarks" alt="Google Bookmarks" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&amp;Url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;Title=Pagination%20In%20SQL%20Server%202005" title="BlinkList"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/blinklist.png" title="BlinkList" alt="BlinkList" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.diigo.com/post?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;title=Pagination%20In%20SQL%20Server%202005" title="Diigo"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/diigo.png" title="Diigo" alt="Diigo" /></a>
	<a rel="nofollow"  target="_blank" href="http://cgi.fark.com/cgi/fark/farkit.pl?h=Pagination%20In%20SQL%20Server%202005&amp;u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F" title="Fark"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/fark.png" title="Fark" alt="Fark" /></a>
	<a rel="nofollow"  target="_blank" href="http://faves.com/Authoring.aspx?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;title=Pagination%20In%20SQL%20Server%202005" title="Faves"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/bluedot.png" title="Faves" alt="Faves" /></a>
	<a rel="nofollow"  target="_blank" href="http://laaik.it/NewStoryCompact.aspx?uri=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;headline=Pagination%20In%20SQL%20Server%202005&amp;cat=5e082fcc-8a3b-47e2-acec-fdf64ff19d12" title="laaik.it"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/laaikit.png" title="laaik.it" alt="laaik.it" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;title=Pagination%20In%20SQL%20Server%202005&amp;source=Tech+News%2C+Tech+Resources%2C+Technology+Articles%2C+Gadget+News%2C+Computer+News+IT+news%2C+software+technology%2C+IT+resources%2C+computer+software%2C+laptops%2C+desktops%2C++information+systems%2C++hardware+technology%2C+multimedia%2C+Windows+OS%2C+linux+clients%2C+network+solution%2C+easy+internet%2C+essential+guides%2C+domains%2C+webhosting%2C+web+program%2C+database+programming&amp;summary=If%20you%27ve%20used%20other%20flavors%20of%20SQL%20%28such%20as%20MySQL%20or%20PostgreSQL%29%20and%20now%20you%20have%20switched%20over%20to%20TSQL%20%28Microsoft%20SQL%20Server%29%20you%20may%20have%20noticed%20that%20there%20is%20no%20native%20way%20of%20doing%20pagination.%20In%20some%20SQL%20versions%2C%20pagination%20was%20as%20easy%20as%20%22SEL" title="LinkedIn"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/linkedin.png" title="LinkedIn" alt="LinkedIn" /></a>
	<a rel="nofollow"  target="_blank" href="https://favorites.live.com/quickadd.aspx?marklet=1&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;title=Pagination%20In%20SQL%20Server%202005" title="Live"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/live.png" title="Live" alt="Live" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.mister-wong.com/addurl/?bm_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;bm_description=Pagination%20In%20SQL%20Server%202005&amp;plugin=soc" title="MisterWong"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/misterwong.png" title="MisterWong" alt="MisterWong" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.myspace.com/Modules/PostTo/Pages/?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;t=Pagination%20In%20SQL%20Server%202005" title="MySpace"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/myspace.png" title="MySpace" alt="MySpace" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.netvibes.com/share?title=Pagination%20In%20SQL%20Server%202005&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F" title="Netvibes"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/netvibes.png" title="Netvibes" alt="Netvibes" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.netvouz.com/action/submitBookmark?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;title=Pagination%20In%20SQL%20Server%202005&amp;popup=no" title="Netvouz"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/netvouz.png" title="Netvouz" alt="Netvouz" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.newsvine.com/_tools/seed&amp;save?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;h=Pagination%20In%20SQL%20Server%202005" title="NewsVine"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/newsvine.png" title="NewsVine" alt="NewsVine" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.propeller.com/submit/?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F" title="Propeller"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/propeller.png" title="Propeller" alt="Propeller" /></a>
	<a rel="nofollow"  target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;title=Pagination%20In%20SQL%20Server%202005" title="Reddit"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" /></a>
	<a rel="nofollow"  target="_blank" href="http://slashdot.org/bookmark.pl?title=Pagination%20In%20SQL%20Server%202005&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F" title="Slashdot"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/slashdot.png" title="Slashdot" alt="Slashdot" /></a>
	<a rel="nofollow"  target="_blank" href="http://socialogs.com/add_story.php?story_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;story_title=Pagination%20In%20SQL%20Server%202005" title="Socialogs"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/socialogs.png" title="Socialogs" alt="Socialogs" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;title=Pagination%20In%20SQL%20Server%202005" title="StumbleUpon"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" /></a>
	<a rel="nofollow"  target="_blank" href="http://technorati.com/faves?add=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F" title="Technorati"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/technorati.png" title="Technorati" alt="Technorati" /></a>
	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=Pagination%20In%20SQL%20Server%202005%20-%20http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F" title="Twitter"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" /></a>
	<a rel="nofollow"  target="_blank" href="http://buzz.yahoo.com/submit/?submitUrl=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fpagination-in-sql-server-2005%2F&amp;submitHeadline=Pagination%20In%20SQL%20Server%202005&amp;submitSummary=If%20you%27ve%20used%20other%20flavors%20of%20SQL%20%28such%20as%20MySQL%20or%20PostgreSQL%29%20and%20now%20you%20have%20switched%20over%20to%20TSQL%20%28Microsoft%20SQL%20Server%29%20you%20may%20have%20noticed%20that%20there%20is%20no%20native%20way%20of%20doing%20pagination.%20In%20some%20SQL%20versions%2C%20pagination%20was%20as%20easy%20as%20%22SEL&amp;submitCategory=science&amp;submitAssetType=text" title="Yahoo! Buzz"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/yahoobuzz.png" title="Yahoo! Buzz" alt="Yahoo! Buzz" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.comteken.com/database-programming/pagination-in-sql-server-2005/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Understanding SQL: SELECT The Data You Want</title>
		<link>http://www.comteken.com/database-programming/understanding-sql-select-the-data-you-want/</link>
		<comments>http://www.comteken.com/database-programming/understanding-sql-select-the-data-you-want/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 16:03:48 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Database Programming]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.comteken.com/?p=37</guid>
		<description><![CDATA[<a href="http://www.comteken.com/database-programming/understanding-sql-select-the-data-you-want/"><img align="left" hspace="5" width="100" src="http://www.singingeels.com/Articles/UserImage.aspx?ImageID=effc26d6-9e28-4e33-81ad-7dac1e8ef03e" class="alignleft wp-post-image tfe" alt="SQL results from joining the orders table to the orderitems table" title="SQL results from joining the orders table to the orderitems table" /></a>Many articles about SQL are spread too thin with &#8220;the basics&#8221; of a SELECT, INSERT, UPDATE and a DELETE. By the time your done, you know a little about everything, and nothing useful. This article will focus on the meat of SQL, getting the data you want. We&#8217;ll start off with the simple, and move [...]]]></description>
			<content:encoded><![CDATA[<p>Many articles about SQL are spread too thin with &#8220;the basics&#8221; of a SELECT, INSERT, UPDATE and a DELETE. By the time your done, you know a little about everything, and nothing useful. This article will focus on the meat of SQL, getting the data you want. We&#8217;ll start off with the simple, and move to the more advanced and creative.</p>
<p>The best way to learn how to use SQL properly is by using a real world problem and then solving it step by step. The scenario we&#8217;re going to work with is an ecommerce website. Let&#8217;s keep it simple and say that this site sells t-shirts, hats and mugs. They have a small customer base, and they want to try to learn more about their audience, so let&#8217;s build our reports.</p>
<h3>Our Example Schema</h3>
<p>We need to quickly define the schema (or design) of our database. This way you&#8217;ll be able to understand the queries below as we piece together our reports. We are going to have a few tables:</p>
<ul>
<li>Customers</li>
<li>Products</li>
<li>Orders</li>
<li>OrderItems</li>
</ul>
<p>Here is what each table will look like:</p>
<div><span>&#8211; A basic customer <span>table</span> <span>with</span> an ID <span>for</span> each customer <span>and</span></span><span><br />
&#8211; the typical &#8220;name <span>and</span> address&#8221; data.</span><br />
<span>CREATE</span> <span>TABLE</span> dbo.Customers<br />
(<br />
ID <span>INT</span> <span>IDENTITY</span>(1, 1) <span>NOT</span> <span>NULL</span>,<br />
FirstName <span>VARCHAR</span>(50) <span>NOT</span> <span>NULL</span>,<br />
LastName <span>VARCHAR</span>(50) <span>NOT</span> <span>NULL</span>,<br />
Address <span>VARCHAR</span>(100) <span>NOT</span> <span>NULL</span>,<br />
City <span>VARCHAR</span>(50) <span>NOT</span> <span>NULL</span>,<br />
State CHAR(2) <span>NOT</span> <span>NULL</span>,<br />
Zip CHAR(5) <span>NOT</span> <span>NULL</span><br />
)<span></p>
<p>&#8211; We will keep the products <span>table</span> simple <span>as</span> well.</span><br />
<span>CREATE</span> <span>TABLE</span> dbo.Products<br />
(<br />
ID <span>INT</span> <span>IDENTITY</span>(1, 1) <span>NOT</span> <span>NULL</span>,<br />
Name <span>VARCHAR</span>(50) <span>NOT</span> <span>NULL</span>,<br />
Price <span>DECIMAL</span>(8,2) <span>NOT</span> <span>NULL</span>,<br />
Description <span>VARCHAR</span>(1000) <span>NOT</span> <span>NULL</span><br />
)<span></p>
<p>&#8211; Because we want a customer <span>to</span> be able <span>to</span> <span>order</span> many items</span><span><br />
&#8211; at a time, we are going <span>to</span> need <span>to</span> know about the <span>order</span></span><span><br />
&#8211; itself, <span>and</span> each item that was ordered.</span><br />
<span>CREATE</span> <span>TABLE</span> dbo.Orders<br />
(<br />
ID <span>INT</span> <span>IDENTITY</span>(1, 1) <span>NOT</span> <span>NULL</span>,<br />
CustomerID <span>INT</span> <span>NOT</span> <span>NULL</span>,<br />
OrderTime <span>DATETIME</span> <span>NOT</span> <span>NULL</span> <span>DEFAULT</span> <span>GETDATE</span>()<br />
)</p>
<p><span>CREATE</span> <span>TABLE</span> dbo.OrderItems<br />
(<br />
ID <span>INT</span> <span>IDENTITY</span>(1, 1) <span>NOT</span> <span>NULL</span>,<br />
OrderID <span>INT</span> <span>NOT</span> <span>NULL</span>,<br />
ProductID <span>INT</span> <span>NOT</span> <span>NULL</span>,<br />
Quantity <span>INT</span> <span>NOT</span> <span>NULL</span><br />
)</div>
<p>I realize that&#8217;s a lot of SQL, and you might not be used to building tables from scratch, but it&#8217;s ok if you don&#8217;t understand that code above right now. Basically, the schema is there so that you can refer to it as you continue the article to see how / why we are doing things.</p>
<h3>SELECTing Basic Data</h3>
<p>Our first report is going to be a basic one: who are our customers. Lets examine the query that would give us a list of our customers:</p>
<div><span>SELECT</span> * <span>FROM</span> dbo.Customers<span></p>
<p>&#8211; That reads <span>as</span> &#8220;<span>SELECT</span> STAR <span>FROM</span> dee-bee-oh dot Customers&#8221;</span></div>
<p>There&#8217;s not much to this query. If you didn&#8217;t already know, the * (STAR or asterisk) tells SQL to return all of the columns in the table. Let&#8217;s change this up a bit by putting the columns in the order we want.</p>
<div><span>SELECT</span><br />
LastName,<br />
FirstName,<br />
Address,<br />
City,<br />
State,<br />
Zip<br />
<span>FROM</span><br />
dbo.Customers</div>
<p>So I&#8217;ve done two things here; 1) I put the LastName column in front of the FirstName column, and 2) I decided not to show the ID column. If you specify the columns manually, you have the power to move them around or leave them out all together. There is one problem though with this query above. Just because we put the LastName column first, doesn&#8217;t mean our results are going to be in ORDER we want. So let&#8217;s now change the query a bit to sort the results alphabetically by a customer&#8217;s last name, then first name.</p>
<div><span>SELECT</span><br />
LastName,<br />
FirstName,<br />
Address,<br />
City,<br />
State,<br />
Zip<br />
<span>FROM</span><br />
dbo.Customers<br />
<span>ORDER</span> <span>BY</span><br />
LastName,<br />
FirstName</div>
<h3>Getting Some Useful Data</h3>
<p>OK, so far this information isn&#8217;t very useful. In fact, you can&#8217;t really call it a report as it&#8217;s just a list of your customers. So we are going to step up our query a bit. We are going to add a column that will give you the number of all the orders that each customer has ever ordered. How you might ask? Just watch:</p>
<div><span>SELECT</span><br />
LastName,<br />
FirstName,<br />
Address,<br />
City,<br />
State,<br />
Zip,<br />
(<span>SELECT</span> <span>COUNT</span>(*) <span>FROM</span> dbo.Orders<br />
<span>WHERE</span> CustomerID = Customers.ID) <span>AS</span> OrderCount<br />
<span>FROM</span><br />
dbo.Customers<br />
<span>ORDER</span> <span>BY</span><br />
LastName,<br />
FirstName</div>
<p>Do you see how simple that was? We added a &#8220;subquery&#8221; right inside of our main query. We used the COUNT function which will do exactly as it sounds, count how ever many rows meet your criteria. The criteria in this case (our WHERE clause) said to count all the records in the Orders table where the CustomerID field matched the ID field in the Customers table in our main query.</p>
<p>If you are new to subqueries (or sub-selects), or if you&#8217;ve heard before that this is a performance nightmare, don&#8217;t worry. This is not hard to understand, and there is no performance problem. The performance questions belong in another article, but as for trying to understand what SQL is doing, here goes.</p>
<p>If you are a programmer, you can think of your query as a &#8220;for loop&#8221; and the sub-select is like a function that is being called inside the loop to get a piece of data from somewhere else. But if you&#8217;re not a programmer you can think of it like shopping for a car. As you look at each car you turn to the salesman next to you and ask &#8220;how much does this one cost?&#8221; SQL is basically doing the same thing. It&#8217;s looking through one table, but you told it to get a piece of information from another table for each record.</p>
<h3>JOINing Multiple Tables Together</h3>
<p>The last piece of the puzzle that we are going to cover is JOINing two (or more) tables together to get relational data. We want to see all of the sales that were made by a customer. We want to know when the order was made, and what items were bought. To do that, we are going to join the Orders table (which has the customer&#8217;s ID and the order date) and the OrderItems table (which has the actual products that were purchased).</p>
<div><span>SELECT</span><br />
Orders.CustomerID,<br />
Orders.OrderTime,<br />
OrderItems.ProductID,<br />
OrderItems.Quantity<br />
<span>FROM</span><br />
dbo.Orders <span>INNER</span> <span>JOIN</span> dbo.OrderItems<br />
<span>ON</span> Orders.ID = OrderItems.OrderID<br />
<span>WHERE</span><br />
Orders.CustomerID = 2</div>
<p>This is a simple query, but again, if you&#8217;re not familiar with JOINs then spend some time looking it over. Let&#8217;s examine the query backwards. What that query is doing is it&#8217;s finding all the orders for customer &#8220;2&#8243;. Then, it will find all the order items that belong to each of his orders. Finally, we tell SQL what columns to display (in our SELECT clause at the top).</p>
<p>The results will look something like this:</p>
<p><img title="SQL results from joining the orders table to the orderitems table" src="http://www.singingeels.com/Articles/UserImage.aspx?ImageID=effc26d6-9e28-4e33-81ad-7dac1e8ef03e" alt="SQL results from joining the orders table to the orderitems table" /></p>
<p>Let&#8217;s extend this query a little bit more to JOIN to another table, the Products table. This will give us the friendly name of the products that were ordered instead of just the ProductID. Watch how easy it is to get a little more information in our report:</p>
<div><span>SELECT</span><br />
Orders.CustomerID,<br />
Orders.OrderTime,<br />
OrderItems.Quantity,<span></p>
<p>&#8211; You will see below that we are going <span>to</span> <span>add</span> the Products</span><span><br />
&#8211; <span>table</span> <span>to</span> our <span>FROM</span> clause. This will give us the ability</span><span><br />
&#8211; <span>to</span> pull data <span>from</span> that <span>table</span> <span>in</span> our <span>SELECT</span> clause.</span></p>
<p>Products.Name <span>AS</span> ProductName,<br />
Products.Description <span>AS</span> ProductDescription<br />
<span>FROM</span><br />
dbo.Orders <span>INNER</span> <span>JOIN</span> dbo.OrderItems<br />
<span>ON</span> Orders.ID = OrderItems.OrderID<span></p>
<p>&#8211; We are going <span>to</span> <span>add</span> another <span>JOIN</span> <span>in</span> our <span>FROM</span> clause,</span><span><br />
&#8211; this time <span>to</span> <span>add</span> the Products <span>table</span>.</span><br />
<span>INNER</span> <span>JOIN</span> dbo.Products<br />
<span>ON</span> OrderItems.ProductID = Products.ID<br />
<span>WHERE</span><br />
Orders.CustomerID = 2</div>
<p>Before I show you the result, I want to touch on something I did above. I &#8220;aliased&#8221; (or renamed) the column &#8220;Name&#8221; and called it &#8220;ProductName&#8221;. This is because a column called &#8220;Name&#8221; in this report might be misleading, but ProductName let&#8217;s you know exactly what to find in that column.</p>
<p>Here is the result:</p>
<p><img title="SQL results of joining Orders, OrderItems and Products tables together" src="http://www.singingeels.com/Articles/UserImage.aspx?ImageID=eb3787b7-175d-4769-badc-8e6acd4b2d87" alt="SQL results of joining Orders, OrderItems and Products tables together" /></p>
<h3>The End &#8211; For Now</h3>
<p>This is the end of the first segment of the &#8220;Understanding SQL&#8221; series. You should have learned something if you are new to SQL, or even if you&#8217;ve been using it for a little while. This article (and the next few to follow in this series) is designed to help you think like a database, and not like a human.</p>
<p>There is still a lot left under the topic of SELECTing (or querying) data. There are more complex joins, nested subqueries, aggregated results and so much more. We&#8217;ll cover those topics in the next &#8220;Understanding SQL&#8221; article.</p>
<p>Source:singingeels.com</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;title=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want&amp;bodytext=Many%20articles%20about%20SQL%20are%20spread%20too%20thin%20with%20%22the%20basics%22%20of%20a%20SELECT%2C%20INSERT%2C%20UPDATE%20and%20a%20DELETE.%20By%20the%20time%20your%20done%2C%20you%20know%20a%20little%20about%20everything%2C%20and%20nothing%20useful.%20This%20article%20will%20focus%20on%20the%20meat%20of%20SQL%2C%20getting%20the%20data%20you%20wa" title="Digg"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" /></a>
	<a rel="nofollow"  target="_blank" href="http://sphinn.com/index.php?c=post&amp;m=submit&amp;link=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F" title="Sphinn"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/sphinn.png" title="Sphinn" alt="Sphinn" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;title=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want&amp;notes=Many%20articles%20about%20SQL%20are%20spread%20too%20thin%20with%20%22the%20basics%22%20of%20a%20SELECT%2C%20INSERT%2C%20UPDATE%20and%20a%20DELETE.%20By%20the%20time%20your%20done%2C%20you%20know%20a%20little%20about%20everything%2C%20and%20nothing%20useful.%20This%20article%20will%20focus%20on%20the%20meat%20of%20SQL%2C%20getting%20the%20data%20you%20wa" title="del.icio.us"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;t=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want" title="Facebook"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.mixx.com/submit?page_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;title=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want" title="Mixx"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/mixx.png" title="Mixx" alt="Mixx" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;title=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want&amp;annotation=Many%20articles%20about%20SQL%20are%20spread%20too%20thin%20with%20%22the%20basics%22%20of%20a%20SELECT%2C%20INSERT%2C%20UPDATE%20and%20a%20DELETE.%20By%20the%20time%20your%20done%2C%20you%20know%20a%20little%20about%20everything%2C%20and%20nothing%20useful.%20This%20article%20will%20focus%20on%20the%20meat%20of%20SQL%2C%20getting%20the%20data%20you%20wa" title="Google Bookmarks"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/googlebookmark.png" title="Google Bookmarks" alt="Google Bookmarks" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&amp;Url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;Title=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want" title="BlinkList"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/blinklist.png" title="BlinkList" alt="BlinkList" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.diigo.com/post?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;title=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want" title="Diigo"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/diigo.png" title="Diigo" alt="Diigo" /></a>
	<a rel="nofollow"  target="_blank" href="http://cgi.fark.com/cgi/fark/farkit.pl?h=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want&amp;u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F" title="Fark"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/fark.png" title="Fark" alt="Fark" /></a>
	<a rel="nofollow"  target="_blank" href="http://faves.com/Authoring.aspx?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;title=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want" title="Faves"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/bluedot.png" title="Faves" alt="Faves" /></a>
	<a rel="nofollow"  target="_blank" href="http://laaik.it/NewStoryCompact.aspx?uri=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;headline=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want&amp;cat=5e082fcc-8a3b-47e2-acec-fdf64ff19d12" title="laaik.it"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/laaikit.png" title="laaik.it" alt="laaik.it" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;title=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want&amp;source=Tech+News%2C+Tech+Resources%2C+Technology+Articles%2C+Gadget+News%2C+Computer+News+IT+news%2C+software+technology%2C+IT+resources%2C+computer+software%2C+laptops%2C+desktops%2C++information+systems%2C++hardware+technology%2C+multimedia%2C+Windows+OS%2C+linux+clients%2C+network+solution%2C+easy+internet%2C+essential+guides%2C+domains%2C+webhosting%2C+web+program%2C+database+programming&amp;summary=Many%20articles%20about%20SQL%20are%20spread%20too%20thin%20with%20%22the%20basics%22%20of%20a%20SELECT%2C%20INSERT%2C%20UPDATE%20and%20a%20DELETE.%20By%20the%20time%20your%20done%2C%20you%20know%20a%20little%20about%20everything%2C%20and%20nothing%20useful.%20This%20article%20will%20focus%20on%20the%20meat%20of%20SQL%2C%20getting%20the%20data%20you%20wa" title="LinkedIn"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/linkedin.png" title="LinkedIn" alt="LinkedIn" /></a>
	<a rel="nofollow"  target="_blank" href="https://favorites.live.com/quickadd.aspx?marklet=1&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;title=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want" title="Live"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/live.png" title="Live" alt="Live" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.mister-wong.com/addurl/?bm_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;bm_description=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want&amp;plugin=soc" title="MisterWong"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/misterwong.png" title="MisterWong" alt="MisterWong" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.myspace.com/Modules/PostTo/Pages/?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;t=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want" title="MySpace"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/myspace.png" title="MySpace" alt="MySpace" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.netvibes.com/share?title=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F" title="Netvibes"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/netvibes.png" title="Netvibes" alt="Netvibes" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.netvouz.com/action/submitBookmark?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;title=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want&amp;popup=no" title="Netvouz"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/netvouz.png" title="Netvouz" alt="Netvouz" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.newsvine.com/_tools/seed&amp;save?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;h=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want" title="NewsVine"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/newsvine.png" title="NewsVine" alt="NewsVine" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.propeller.com/submit/?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F" title="Propeller"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/propeller.png" title="Propeller" alt="Propeller" /></a>
	<a rel="nofollow"  target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;title=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want" title="Reddit"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" /></a>
	<a rel="nofollow"  target="_blank" href="http://slashdot.org/bookmark.pl?title=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F" title="Slashdot"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/slashdot.png" title="Slashdot" alt="Slashdot" /></a>
	<a rel="nofollow"  target="_blank" href="http://socialogs.com/add_story.php?story_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;story_title=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want" title="Socialogs"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/socialogs.png" title="Socialogs" alt="Socialogs" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;title=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want" title="StumbleUpon"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" /></a>
	<a rel="nofollow"  target="_blank" href="http://technorati.com/faves?add=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F" title="Technorati"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/technorati.png" title="Technorati" alt="Technorati" /></a>
	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want%20-%20http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F" title="Twitter"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" /></a>
	<a rel="nofollow"  target="_blank" href="http://buzz.yahoo.com/submit/?submitUrl=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-select-the-data-you-want%2F&amp;submitHeadline=Understanding%20SQL%3A%20SELECT%20The%20Data%20You%20Want&amp;submitSummary=Many%20articles%20about%20SQL%20are%20spread%20too%20thin%20with%20%22the%20basics%22%20of%20a%20SELECT%2C%20INSERT%2C%20UPDATE%20and%20a%20DELETE.%20By%20the%20time%20your%20done%2C%20you%20know%20a%20little%20about%20everything%2C%20and%20nothing%20useful.%20This%20article%20will%20focus%20on%20the%20meat%20of%20SQL%2C%20getting%20the%20data%20you%20wa&amp;submitCategory=science&amp;submitAssetType=text" title="Yahoo! Buzz"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/yahoobuzz.png" title="Yahoo! Buzz" alt="Yahoo! Buzz" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.comteken.com/database-programming/understanding-sql-select-the-data-you-want/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Understanding SQL: Complex Queries</title>
		<link>http://www.comteken.com/database-programming/understanding-sql-complex-queries/</link>
		<comments>http://www.comteken.com/database-programming/understanding-sql-complex-queries/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 16:02:21 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Database Programming]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.comteken.com/?p=35</guid>
		<description><![CDATA[<a href="http://www.comteken.com/database-programming/understanding-sql-complex-queries/"><img align="left" hspace="5" width="100" src="http://www.singingeels.com/Articles/UserImage.aspx?ImageID=30b36a6c-b240-4dad-a39c-ebd8cdd04e4b" class="alignleft wp-post-image tfe" alt="Latest order time and total items purchased per customer" title="Latest order time and total items purchased per customer" /></a>The previous article in the &#8220;Understanding SQL&#8221; series brought us from easy SELECT statements to more useful JOINs and subselects. This article will go into more advanced queries using Common Table Expressions (CTE) and aggregated results with the GROUP BY clause. The two don&#8217;t need to go hand in hand, but this article will utilize [...]]]></description>
			<content:encoded><![CDATA[<p>The previous article in the &#8220;Understanding SQL&#8221; series brought us from easy SELECT statements to more useful JOINs and subselects. This article will go into more advanced queries using Common Table Expressions (CTE) and aggregated results with the GROUP BY clause. The two don&#8217;t need to go hand in hand, but this article will utilize them both.</p>
<p>If you are not very familiar with SQL and you haven&#8217;t already done so, please read Understanding SQL: SELECT The Data You Want. It will give you a bit more than the basics and you should be able to understand where we take things in this article. Also, we are going to continue with the &#8220;ecommerce web site&#8221; example from that article.</p>
<h3>What is a GROUP BY</h3>
<p>Before we can go on, you need to know what a GROUP BY clause is. To put it simply, you can tell SQL how to &#8220;GROUP&#8221; records together. For example, if you wanted to know how many people had the same name, you could make a query:</p>
<div><span>SELECT</span> FirstName, <span>COUNT</span>(*) <span>FROM</span> dbo.Customers <span>GROUP</span> <span>BY</span> FirstName</div>
<p>That would return a result set of all unique names in your Customers table, and how many times each name is found. Let&#8217;s look at another query to help us understand what a GROUP BY is used for in SQL.</p>
<div><span>SELECT</span> FirstName, <span>MAX</span>(ID) <span>FROM</span> dbo.Customers <span>GROUP</span> <span>BY</span> FirstName</div>
<p>This query is telling SQL that you want to know the highest ID of all users if they were grouped together by their names. So all the Bobs would get together, and whoever had the highest ID would come forward in the result set. Likewise, all the Timothys and all the Jonathans would do the same thing. Now let&#8217;s continue on to more advanced queries.</p>
<h3>On The Fly Views</h3>
<p>Often times you may need to treat a small portion of a TABLE as if it were its own unique TABLE (or VIEW). But creating a VIEW for one query is a bit ridiculous. A good &#8220;for instance&#8221; would be if you wanted a report that displayed the latest purchase made by all customers. You wouldn&#8217;t want to simply JOIN the Customers table to the Orders table as you would get all orders for every customer, not just their latest.</p>
<p>You have a few options here: Full JOIN then aggregate subqueries in the WHERE clause or a CTE (Common Table Expression). But the solution we are going to choose is the CTE, and I&#8217;ll explain why in a bit. First of all, let&#8217;s look at the first option (which is the option likely to be taken by most people). Here is what most people would do:</p>
<div><span>&#8211; <span>With</span> the knowledge <span>of</span> a &#8220;<span>GROUP</span> <span>BY</span>&#8221; clause <span>as</span> explained above,</span><span><br />
&#8211; people go overboard <span>and</span> do something <span>like</span> this:</span></p>
<p><span>SELECT</span><br />
Customers.*,<br />
<span>MAX</span>(Orders.OrderTime) <span>AS</span> LatestOrderTime<br />
<span>FROM</span><br />
dbo.Customers <span>INNER</span> <span>JOIN</span> dbo.Orders<br />
<span>ON</span> Customers.ID = Orders.CustomerID<br />
<span>GROUP</span> <span>BY</span><br />
Customers.ID, Customers.FirstName, Customers.LastName, Customers.Address,<br />
Customers.City, Customers.State, Customers.Zip</div>
<p>What they don&#8217;t realize is that every column that they have to add to the GROUP BY clause is going to cause more and more strain on SQL. Think about it, as each record comes in, SQL has to check to see if their is already a record with that same ID, FirstName, LastName, Address, City, State and Zip. And imagine if there were more columns in the Customers table; you&#8217;d be killing SQL for no reason.</p>
<p>Now like I said above, a CTE can treat a part of a table as if it were it&#8217;s own unique table. Meaning, wouldn&#8217;t it be nice if we had a table of only the most recent orders for every customer? Lets see how we can make a CTE that has the data we need, and include it in our query so that we don&#8217;t have to GROUP BY so many fields.</p>
<div><span>&#8211; <span>Create</span> a CTE (fake <span>table</span> <span>or</span> <span>view</span>) <span>of</span> the latest <span>order</span> IDs</span><br />
<span>WITH</span> LatestOrders (ID) <span>AS</span> (<span>SELECT</span> <span>MAX</span>(ID) <span>FROM</span> dbo.Orders <span>GROUP</span> <span>BY</span> CustomerID)<span></p>
<p>&#8211; Only retrieve the records that are <span>in</span> the &#8220;LatestOrders&#8221; CTE</span><br />
<span>SELECT</span><br />
Customers.*,<br />
Orders.OrderTime <span>AS</span> LatestOrderTime<br />
<span>FROM</span><br />
dbo.Customers <span>INNER</span> <span>JOIN</span> dbo.Orders<br />
<span>ON</span> Customers.ID = Orders.CustomerID<br />
<span>WHERE</span><br />
Orders.ID <span>IN</span> (<span>SELECT</span> ID <span>FROM</span> LatestOrders)</div>
<p>You may think that this query is more expensive (harder on the processor) than the one above using the massive GROUP BY, but it&#8217;s not. In fact, it&#8217;s about 100% faster and less processor intensive. If I added more records and got to have a large table, the CTE approach could be hundreds of times faster.</p>
<p>Something to keep in mind though is that the CTE is only available in SQL Server 2005, so if you are using SQL Server 2000 you have to do this the old way. The query will actually &#8216;cost&#8217; the same to SQL (because it&#8217;s really the same thing), but it will look a little uglier. Here it is using a subquery in the WHERE clause.</p>
<div><span>SELECT</span><br />
Customers.*,<br />
Orders.OrderTime <span>AS</span> LatestOrderTime<br />
<span>FROM</span><br />
dbo.Customers <span>INNER</span> <span>JOIN</span> dbo.Orders<br />
<span>ON</span> Customers.ID = Orders.CustomerID<br />
<span>WHERE</span><br />
Orders.ID <span>IN</span> (<span>SELECT</span> <span>MAX</span>(ID) <span>FROM</span> dbo.Orders <span>GROUP</span> <span>BY</span> CustomerID)</div>
<p>While this may seem easier than the CTE, you should remember that I&#8217;m keeping the query simple for this article. The CTE is a lot cleaner for another developer to come behind because you define your &#8220;fake table&#8221; at the top of your query, so people know right away what you are trying to do. Also, you give it a name such as &#8220;LatestOrders&#8221; which explains what you are using it for. Lastly, you can put it in your JOIN clause just like a real table.</p>
<h3>Concluding Comments</h3>
<p>One thing of note is that a CTE can only be used once in your query. So you can&#8217;t declare your CTE at the top, then do multiple queries against it. However, you can make multiple CTE&#8217;s and then use them together in one query. Also, everything has it&#8217;s place, so if you find that you are building the same CTE multiple times for different reports / queries, then you might want to turn that into a VIEW instead.</p>
<p>If you&#8217;ve read the previous article mentioned above, and now this one, you should be able to make some useful queries (or reports). Try to build your queries logically, first explaining to yourself what you want the result to be. Then piece by piece add the code together until you reach the end result. If you find that by adding another JOIN or column to your output suddently breaks what was coming together nicely, then remove it and rethink what you did.</p>
<p>Here is a final example report that you should be able to build with the information in these articles. We&#8217;ll make a &#8220;Customer Activity Report&#8221; that will show the latest purchase date, and how many items have been purchased total for each customer. Here&#8217;s the code:</p>
<div><span>WITH</span> LatestOrders (ID) <span>AS</span> (<span>SELECT</span> <span>MAX</span>(ID) <span>FROM</span> dbo.Orders <span>GROUP</span> <span>BY</span> CustomerID)</p>
<p><span>SELECT</span><br />
Customers.*,<br />
Orders.OrderTime <span>AS</span> LatestOrderTime,<br />
(<span>SELECT</span> <span>COUNT</span>(*) <span>FROM</span> dbo.OrderItems <span>WHERE</span> OrderID <span>IN</span><br />
(<span>SELECT</span> ID <span>FROM</span> dbo.Orders <span>WHERE</span> CustomerID = Customers.ID))<br />
<span>AS</span> TotalItemsPurchased<br />
<span>FROM</span><br />
dbo.Customers <span>INNER</span> <span>JOIN</span> dbo.Orders<br />
<span>ON</span> Customers.ID = Orders.CustomerID<br />
<span>WHERE</span><br />
Orders.ID <span>IN</span> (<span>SELECT</span> ID <span>FROM</span> LatestOrders)</div>
<p>Your results should look something like this:</p>
<p><img title="Latest order time and total items purchased per customer" src="http://www.singingeels.com/Articles/UserImage.aspx?ImageID=30b36a6c-b240-4dad-a39c-ebd8cdd04e4b" alt="Latest order time and total items purchased per customer" /></p>
<p>Source:singingeels.com</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;title=Understanding%20SQL%3A%20Complex%20Queries&amp;bodytext=The%20previous%20article%20in%20the%20%22Understanding%20SQL%22%20series%20brought%20us%20from%20easy%20SELECT%20statements%20to%20more%20useful%20JOINs%20and%20subselects.%20This%20article%20will%20go%20into%20more%20advanced%20queries%20using%20Common%20Table%20Expressions%20%28CTE%29%20and%20aggregated%20results%20with%20the%20GR" title="Digg"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" /></a>
	<a rel="nofollow"  target="_blank" href="http://sphinn.com/index.php?c=post&amp;m=submit&amp;link=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F" title="Sphinn"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/sphinn.png" title="Sphinn" alt="Sphinn" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;title=Understanding%20SQL%3A%20Complex%20Queries&amp;notes=The%20previous%20article%20in%20the%20%22Understanding%20SQL%22%20series%20brought%20us%20from%20easy%20SELECT%20statements%20to%20more%20useful%20JOINs%20and%20subselects.%20This%20article%20will%20go%20into%20more%20advanced%20queries%20using%20Common%20Table%20Expressions%20%28CTE%29%20and%20aggregated%20results%20with%20the%20GR" title="del.icio.us"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;t=Understanding%20SQL%3A%20Complex%20Queries" title="Facebook"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.mixx.com/submit?page_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;title=Understanding%20SQL%3A%20Complex%20Queries" title="Mixx"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/mixx.png" title="Mixx" alt="Mixx" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;title=Understanding%20SQL%3A%20Complex%20Queries&amp;annotation=The%20previous%20article%20in%20the%20%22Understanding%20SQL%22%20series%20brought%20us%20from%20easy%20SELECT%20statements%20to%20more%20useful%20JOINs%20and%20subselects.%20This%20article%20will%20go%20into%20more%20advanced%20queries%20using%20Common%20Table%20Expressions%20%28CTE%29%20and%20aggregated%20results%20with%20the%20GR" title="Google Bookmarks"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/googlebookmark.png" title="Google Bookmarks" alt="Google Bookmarks" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&amp;Url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;Title=Understanding%20SQL%3A%20Complex%20Queries" title="BlinkList"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/blinklist.png" title="BlinkList" alt="BlinkList" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.diigo.com/post?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;title=Understanding%20SQL%3A%20Complex%20Queries" title="Diigo"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/diigo.png" title="Diigo" alt="Diigo" /></a>
	<a rel="nofollow"  target="_blank" href="http://cgi.fark.com/cgi/fark/farkit.pl?h=Understanding%20SQL%3A%20Complex%20Queries&amp;u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F" title="Fark"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/fark.png" title="Fark" alt="Fark" /></a>
	<a rel="nofollow"  target="_blank" href="http://faves.com/Authoring.aspx?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;title=Understanding%20SQL%3A%20Complex%20Queries" title="Faves"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/bluedot.png" title="Faves" alt="Faves" /></a>
	<a rel="nofollow"  target="_blank" href="http://laaik.it/NewStoryCompact.aspx?uri=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;headline=Understanding%20SQL%3A%20Complex%20Queries&amp;cat=5e082fcc-8a3b-47e2-acec-fdf64ff19d12" title="laaik.it"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/laaikit.png" title="laaik.it" alt="laaik.it" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;title=Understanding%20SQL%3A%20Complex%20Queries&amp;source=Tech+News%2C+Tech+Resources%2C+Technology+Articles%2C+Gadget+News%2C+Computer+News+IT+news%2C+software+technology%2C+IT+resources%2C+computer+software%2C+laptops%2C+desktops%2C++information+systems%2C++hardware+technology%2C+multimedia%2C+Windows+OS%2C+linux+clients%2C+network+solution%2C+easy+internet%2C+essential+guides%2C+domains%2C+webhosting%2C+web+program%2C+database+programming&amp;summary=The%20previous%20article%20in%20the%20%22Understanding%20SQL%22%20series%20brought%20us%20from%20easy%20SELECT%20statements%20to%20more%20useful%20JOINs%20and%20subselects.%20This%20article%20will%20go%20into%20more%20advanced%20queries%20using%20Common%20Table%20Expressions%20%28CTE%29%20and%20aggregated%20results%20with%20the%20GR" title="LinkedIn"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/linkedin.png" title="LinkedIn" alt="LinkedIn" /></a>
	<a rel="nofollow"  target="_blank" href="https://favorites.live.com/quickadd.aspx?marklet=1&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;title=Understanding%20SQL%3A%20Complex%20Queries" title="Live"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/live.png" title="Live" alt="Live" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.mister-wong.com/addurl/?bm_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;bm_description=Understanding%20SQL%3A%20Complex%20Queries&amp;plugin=soc" title="MisterWong"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/misterwong.png" title="MisterWong" alt="MisterWong" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.myspace.com/Modules/PostTo/Pages/?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;t=Understanding%20SQL%3A%20Complex%20Queries" title="MySpace"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/myspace.png" title="MySpace" alt="MySpace" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.netvibes.com/share?title=Understanding%20SQL%3A%20Complex%20Queries&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F" title="Netvibes"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/netvibes.png" title="Netvibes" alt="Netvibes" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.netvouz.com/action/submitBookmark?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;title=Understanding%20SQL%3A%20Complex%20Queries&amp;popup=no" title="Netvouz"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/netvouz.png" title="Netvouz" alt="Netvouz" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.newsvine.com/_tools/seed&amp;save?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;h=Understanding%20SQL%3A%20Complex%20Queries" title="NewsVine"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/newsvine.png" title="NewsVine" alt="NewsVine" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.propeller.com/submit/?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F" title="Propeller"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/propeller.png" title="Propeller" alt="Propeller" /></a>
	<a rel="nofollow"  target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;title=Understanding%20SQL%3A%20Complex%20Queries" title="Reddit"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" /></a>
	<a rel="nofollow"  target="_blank" href="http://slashdot.org/bookmark.pl?title=Understanding%20SQL%3A%20Complex%20Queries&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F" title="Slashdot"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/slashdot.png" title="Slashdot" alt="Slashdot" /></a>
	<a rel="nofollow"  target="_blank" href="http://socialogs.com/add_story.php?story_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;story_title=Understanding%20SQL%3A%20Complex%20Queries" title="Socialogs"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/socialogs.png" title="Socialogs" alt="Socialogs" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;title=Understanding%20SQL%3A%20Complex%20Queries" title="StumbleUpon"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" /></a>
	<a rel="nofollow"  target="_blank" href="http://technorati.com/faves?add=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F" title="Technorati"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/technorati.png" title="Technorati" alt="Technorati" /></a>
	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=Understanding%20SQL%3A%20Complex%20Queries%20-%20http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F" title="Twitter"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" /></a>
	<a rel="nofollow"  target="_blank" href="http://buzz.yahoo.com/submit/?submitUrl=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-complex-queries%2F&amp;submitHeadline=Understanding%20SQL%3A%20Complex%20Queries&amp;submitSummary=The%20previous%20article%20in%20the%20%22Understanding%20SQL%22%20series%20brought%20us%20from%20easy%20SELECT%20statements%20to%20more%20useful%20JOINs%20and%20subselects.%20This%20article%20will%20go%20into%20more%20advanced%20queries%20using%20Common%20Table%20Expressions%20%28CTE%29%20and%20aggregated%20results%20with%20the%20GR&amp;submitCategory=science&amp;submitAssetType=text" title="Yahoo! Buzz"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/yahoobuzz.png" title="Yahoo! Buzz" alt="Yahoo! Buzz" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.comteken.com/database-programming/understanding-sql-complex-queries/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Understanding SQL: Many to Many Relationships</title>
		<link>http://www.comteken.com/database-programming/understanding-sql-many-to-many-relationships/</link>
		<comments>http://www.comteken.com/database-programming/understanding-sql-many-to-many-relationships/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 16:01:15 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Database Programming]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.comteken.com/?p=33</guid>
		<description><![CDATA[<a href="http://www.comteken.com/database-programming/understanding-sql-many-to-many-relationships/"><img align="left" hspace="5" width="100" src="http://www.singingeels.com/Articles/Articles/UserImage.aspx?ImageID=baa46512-9d6a-43f1-ab4b-d4535278b608" class="alignleft wp-post-image tfe" alt="Perfect SQL indexes for a many-to-many linker table" title="Perfect SQL indexes for a many-to-many linker table" /></a>In the world of relational data, many-to-many relationships are one of the hardest concepts to understand and implement correctly. Quite likely the scenario will arise for a developer to decide whether to support a one-to-many or a many-to-many schema, and out of fear we crumble to an &#8220;easy&#8221; design. This article will use real world [...]]]></description>
			<content:encoded><![CDATA[<p>In the world of relational data, many-to-many relationships are one of the hardest concepts to understand and implement correctly. Quite likely the scenario will arise for a developer to decide whether to support a one-to-many or a many-to-many schema, and out of fear we crumble to an &#8220;easy&#8221; design. This article will use real world scenarios to show how and why to use a many-to-many relationship as well as how to achieve perfect performance.</p>
<p>There are many situations that would call for a many-to-many schema. You might have a table of &#8220;Stores&#8221; and a table of &#8220;Managers&#8221; and your company might to allow managers to switch between stores. This would require that a store could have more than one manger, and a manger could belong to more than one store (thus, many to many). Or you could consider this scenario:</p>
<p>You&#8217;re building an application for a customer support center that takes phone calls for a cable company. When a customer calls in to complain about their fuzzy T.V. reception and also they want to upgrade their high-speed internet access, the customer service representative will need to open up two &#8220;tickets&#8221;; one for the fuzzy reception problem, and one for the high-speed upgrade.</p>
<p>In this scenario we are dealing with two things: phone calls and support tickets. So when the customer calls back the next day about the internet upgrade, we will want to associate that phone call with the second ticket we opened. Likewise, when they call back again the next day about the fuzzy reception, we want to associate that phone call with the first ticket we opened. Let&#8217;s see how we can accomplish this many-to-many relationship in SQL. We&#8217;ll learn:</p>
<ul>
<li>How to create tables that support a many-to-many relationship.</li>
<li>What indexes should be created for the best performance.</li>
<li>How to report by phone calls or by tickets (either side of the relationship).</li>
</ul>
<h3>How to Make a Many-to-Many Schema</h3>
<p>The first piece in making our tables is to define the two entities (or tables) and then we can join them together by their IDs in a third &#8220;linker&#8221; table. For the example we are going to use we&#8217;ll need to very simple tables: PhoneCalls and Tickets. We&#8217;ll keep it simple so as not to get lost in the illustration, but instead to focus on the many-to-many relationship concept. Here is the schema of the two tables:</p>
<div><span>&#8211; This <span>table</span> will hold our phone calls.</span><br />
<span>CREATE</span> <span>TABLE</span> dbo.PhoneCalls<br />
(<br />
ID <span>INT</span> <span>IDENTITY</span>(1, 1) <span>NOT</span> <span>NULL</span>,<br />
CallTime <span>DATETIME</span> <span>NOT</span> <span>NULL</span> <span>DEFAULT</span> <span>GETDATE</span>(),<br />
CallerPhoneNumber CHAR(10) <span>NOT</span> <span>NULL</span><br />
)<span></p>
<p>&#8211; This <span>table</span> will hold our &#8220;tickets&#8221; (<span>or</span> cases).</span><br />
<span>CREATE</span> <span>TABLE</span> dbo.Tickets<br />
(<br />
ID <span>INT</span> <span>IDENTITY</span>(1, 1) <span>NOT</span> <span>NULL</span>,<br />
CreatedTime <span>DATETIME</span> <span>NOT</span> <span>NULL</span> <span>DEFAULT</span> <span>GETDATE</span>(),<br />
Subject <span>VARCHAR</span>(250) <span>NOT</span> <span>NULL</span>,<br />
Notes <span>VARCHAR</span>(8000) <span>NOT</span> <span>NULL</span>,<br />
Completed BIT <span>NOT</span> <span>NULL</span> <span>DEFAULT</span> 0<br />
)</div>
<p>If we only wanted to support one-to-one functionality we would simply put a &#8220;PhoneCallID&#8221; field in the Tickets table and make the rule that you can&#8217;t have a ticket without a phone call. But instead, we want to allow multiple tickets to be created on one phone call, and we want to allow many phone calls to be associated with a single ticket. To do that we&#8217;ll need to build this linker table:</p>
<div><span>&#8211; This <span>table</span> will link a phone call <span>with</span> a ticket.</span><br />
<span>CREATE</span> <span>TABLE</span> dbo.PhoneCalls_Tickets<br />
(<br />
PhoneCallID <span>INT</span> <span>NOT</span> <span>NULL</span>,<br />
TicketID <span>INT</span> <span>NOT</span> <span>NULL</span><br />
)</div>
<p>That&#8217;s all we need to make our many-to-many schema work. First we would insert a record into the PhoneCalls table. Then, when the caller explains the situation, the customer service rep would enter a record into the Tickets table and the system would insert a link (the ID of the phone call and the ID of the ticket) into the linker table. Eventually though this table is going to be big, and will begin to perform slowly in views and reports. Let’s now look at how to make the perfect indexes for performance on both sides of the relationship:</p>
<h3>Perfect Many-to-Many Indexes</h3>
<p>Without a proper understanding of SQL indexes, most people would either add an arbitrary column to the linker table and make that the primary key (which doesn&#8217;t help us at all), or they might make a composite primary key of PhoneCallID and TicketID. This index will help a lot; it makes sure that there are no duplicates and it gives us a lot of speed when searching or joining to the PhoneCalls table. But what if we wanted to query by the TicketID?</p>
<p>The problem with just one index when dealing with a many-to-many linker table is that you are only tuning performance for one side of the relationship (which makes sense: one index only helps one side). So how do we add an index that will give us the best performance possible? Well, a regular index is ok, but nothing beats a unique index in terms of speed. Here&#8217;s the trick!</p>
<p>A linker table (a table of IDs from two other tables for the purpose of a many-to-many relationship) is always unique whether you look at it from left to right or right to left. Meaning, PhoneCallID_TicketID is unique and TicketID_PhoneCallID is also unique, so we can add another unique index to the table!</p>
<p><img title="Perfect SQL indexes for a many-to-many linker table" src="http://www.singingeels.com/Articles/Articles/UserImage.aspx?ImageID=baa46512-9d6a-43f1-ab4b-d4535278b608" alt="Perfect SQL indexes for a many-to-many linker table" /> <img title="Another unique SQL index for a many-to-many linker table" src="http://www.singingeels.com/Articles/Articles/UserImage.aspx?ImageID=17ca51f3-36e0-4ebe-8e66-cf9f081aefff" alt="Another unique SQL index for a many-to-many linker table" /></p>
<div>
<p>You can add the PRIMARY KEY indexes right in the CREATE TABLE statement (meaning, you don&#8217;t have to use the designer). For simple cases where only one column is the primary key, you can just add the phrase &#8220;PRIMARY KEY&#8221; on the column definition line. Example:</p>
<div><span>CREATE</span> <span>TABLE</span> dbo.SomeTable<br />
(<br />
ID <span>INT</span> <span>IDENTITY</span>(1, 1) <span>PRIMARY</span> <span>KEY</span> <span>NOT</span> <span>NULL</span><br />
)</div>
<p>For more complex PRIMARY KEYS where you want multiple columns, or you want to specify the default sort order, you would use the &#8220;CONSTRAINT&#8221; keyword. Example:</p>
<div><span>CREATE</span> <span>TABLE</span> dbo.ComplexTable<br />
(<br />
FirstName <span>VARCHAR</span>(100) <span>NOT</span> <span>NULL</span>,<br />
LastName <span>VARCHAR</span>(100) <span>NOT</span> <span>NULL</span>,<br />
<span>CONSTRAINT</span> PK_ComplexTable <span>PRIMARY</span> <span>KEY</span> (LastName, FirstName <span>DESC</span>)<br />
)</div>
</div>
<h3>How Does Another Unique Index Help?</h3>
<p>Well, think about your table as if it was a library filled with thousands of books. How would you find a book called &#8220;SQL Performance Tips&#8221;? Well, you would use the library&#8217;s index and skip ahead to the letter &#8220;S&#8221; and continue in alphabetical order until you found your book. But what if you wanted to find a book by the author &#8220;Billy McGee&#8221;? You can&#8217;t use the index that you were just in because that is sorted by book title (which doesn&#8217;t help you because you only know the author&#8217;s name). So you would use the library&#8217;s other index, the one that is sorted by author&#8217;s name.</p>
<p>The same is true for SQL. If you do a query like this:</p>
<div><span>SELECT</span> * <span>FROM</span> dbo.PhoneCalls_Tickets <span>WHERE</span> PhoneCallID = 123</div>
<p>Then SQL will realize that it should use the PhoneCallID_TicketID index to find your results. But if you change the query only slightly to do this:</p>
<div><span>SELECT</span> * <span>FROM</span> dbo.PhoneCalls_Tickets <span>WHERE</span> TicketID = 123</div>
<p>Then SQL will understand that the first index doesn&#8217;t help, so it will use the TicketID_PhoneCallID index to find your results. That&#8217;s how to achieve the best performance with many-to-many relationships.</p>
<h3>How Do I JOIN These Tables Together?</h3>
<p>When you are dealing with JOINing more than two tables in a query it can sometimes get confusing. So when you&#8217;re dealing with a many-to-many query (which requires three tables), it helps to first break up your FROM/JOIN clauses and explain them out loud to yourself as you type. The JOINs should make sense to SQL and to you. Let&#8217;s look at a query that would JOIN both of our tables together with the help of the linker table.</p>
<div><span>&#8211; It doesn&#8217;t matter which <span>table</span> we start <span>with</span>, so I&#8217;ll just</span><span><br />
&#8211; pick the PhoneCalls <span>table</span>.</span></p>
<p><span>SELECT</span><br />
*<br />
<span>FROM</span><br />
dbo.PhoneCalls<span></p>
<p>&#8211; <span>If</span> I stop here, <span>then</span> <span>all</span> I have <span>is</span> the phone call data. Now</span><span><br />
&#8211; we can <span>JOIN</span> <span>to</span> the helper <span>table</span> <span>to</span> get the IDs <span>of</span> <span>all</span> tickets</span><span><br />
&#8211; associated <span>with</span> each phone call <span>in</span> the query above.</span></p>
<p><span>INNER</span> <span>JOIN</span> dbo.PhoneCalls_Tickets <span>ON</span><br />
PhoneCalls.ID = PhoneCalls_Tickets.PhoneCallID<span></p>
<p>&#8211; That&#8217;s simple enough. Now that we&#8217;ve joined <span>to</span> the linker</span><span><br />
&#8211; <span>table</span> we are able <span>to</span> <span>use</span> the PhoneCallID <span>or</span> the TicketID</span><span><br />
&#8211; fields <span>from</span> the linker <span>table</span>. Now let&#8217;s get the tickets!</span></p>
<p><span>INNER</span> <span>JOIN</span> dbo.Tickets <span>ON</span><br />
PhoneCalls_Tickets.TicketID = Tickets.ID</div>
<p>You can also use the linker table in your WHERE clause. An example of this would be if you wanted to see all calls associated with a ticket, or all tickets associated with a call. Here is how you would achieve those two queries:</p>
<div><span>&#8211; This will give you <span>all</span> calls <span>for</span> ticket number 123.</span><br />
<span>SELECT</span> * <span>FROM</span> dbo.PhoneCalls <span>WHERE</span> ID <span>IN</span><br />
(<span>SELECT</span> PhoneCallID <span>FROM</span> dbo.PhoneCalls_Tickets <span>WHERE</span> TicketID = 123)<span></p>
<p>&#8211; This will give you <span>all</span> tickets <span>for</span> phone call number 123.</span><br />
<span>SELECT</span> * <span>FROM</span> dbo.Tickets <span>WHERE</span> ID <span>IN</span><br />
(<span>SELECT</span> TicketID <span>FROM</span> dbo.PhoneCalls_Tickets <span>WHERE</span> PhoneCallID = 123)</div>
<h3>Closing Remarks</h3>
<p>Now that we have examined the facts we realize that many-to-many relationships are not difficult to build, and they can perform very well when indexed properly. Also, if you name your tables appropriately, then you&#8217;re queries will also be easy to read. So the next time you are designing a database schema for one of your projects, try to squeeze in some of this powerful functionality. Remember, you can easily support a one-to-many relationship with a many-to-many schema, but you can&#8217;t go the other way around. So if you think you might need it, why not support it from the ground up.</p>
<p>Source:singingeels.com</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;title=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships&amp;bodytext=In%20the%20world%20of%20relational%20data%2C%20many-to-many%20relationships%20are%20one%20of%20the%20hardest%20concepts%20to%20understand%20and%20implement%20correctly.%20Quite%20likely%20the%20scenario%20will%20arise%20for%20a%20developer%20to%20decide%20whether%20to%20support%20a%20one-to-many%20or%20a%20many-to-many%20schem" title="Digg"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" /></a>
	<a rel="nofollow"  target="_blank" href="http://sphinn.com/index.php?c=post&amp;m=submit&amp;link=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F" title="Sphinn"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/sphinn.png" title="Sphinn" alt="Sphinn" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;title=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships&amp;notes=In%20the%20world%20of%20relational%20data%2C%20many-to-many%20relationships%20are%20one%20of%20the%20hardest%20concepts%20to%20understand%20and%20implement%20correctly.%20Quite%20likely%20the%20scenario%20will%20arise%20for%20a%20developer%20to%20decide%20whether%20to%20support%20a%20one-to-many%20or%20a%20many-to-many%20schem" title="del.icio.us"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;t=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships" title="Facebook"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.mixx.com/submit?page_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;title=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships" title="Mixx"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/mixx.png" title="Mixx" alt="Mixx" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;title=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships&amp;annotation=In%20the%20world%20of%20relational%20data%2C%20many-to-many%20relationships%20are%20one%20of%20the%20hardest%20concepts%20to%20understand%20and%20implement%20correctly.%20Quite%20likely%20the%20scenario%20will%20arise%20for%20a%20developer%20to%20decide%20whether%20to%20support%20a%20one-to-many%20or%20a%20many-to-many%20schem" title="Google Bookmarks"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/googlebookmark.png" title="Google Bookmarks" alt="Google Bookmarks" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&amp;Url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;Title=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships" title="BlinkList"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/blinklist.png" title="BlinkList" alt="BlinkList" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.diigo.com/post?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;title=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships" title="Diigo"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/diigo.png" title="Diigo" alt="Diigo" /></a>
	<a rel="nofollow"  target="_blank" href="http://cgi.fark.com/cgi/fark/farkit.pl?h=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships&amp;u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F" title="Fark"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/fark.png" title="Fark" alt="Fark" /></a>
	<a rel="nofollow"  target="_blank" href="http://faves.com/Authoring.aspx?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;title=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships" title="Faves"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/bluedot.png" title="Faves" alt="Faves" /></a>
	<a rel="nofollow"  target="_blank" href="http://laaik.it/NewStoryCompact.aspx?uri=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;headline=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships&amp;cat=5e082fcc-8a3b-47e2-acec-fdf64ff19d12" title="laaik.it"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/laaikit.png" title="laaik.it" alt="laaik.it" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;title=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships&amp;source=Tech+News%2C+Tech+Resources%2C+Technology+Articles%2C+Gadget+News%2C+Computer+News+IT+news%2C+software+technology%2C+IT+resources%2C+computer+software%2C+laptops%2C+desktops%2C++information+systems%2C++hardware+technology%2C+multimedia%2C+Windows+OS%2C+linux+clients%2C+network+solution%2C+easy+internet%2C+essential+guides%2C+domains%2C+webhosting%2C+web+program%2C+database+programming&amp;summary=In%20the%20world%20of%20relational%20data%2C%20many-to-many%20relationships%20are%20one%20of%20the%20hardest%20concepts%20to%20understand%20and%20implement%20correctly.%20Quite%20likely%20the%20scenario%20will%20arise%20for%20a%20developer%20to%20decide%20whether%20to%20support%20a%20one-to-many%20or%20a%20many-to-many%20schem" title="LinkedIn"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/linkedin.png" title="LinkedIn" alt="LinkedIn" /></a>
	<a rel="nofollow"  target="_blank" href="https://favorites.live.com/quickadd.aspx?marklet=1&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;title=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships" title="Live"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/live.png" title="Live" alt="Live" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.mister-wong.com/addurl/?bm_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;bm_description=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships&amp;plugin=soc" title="MisterWong"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/misterwong.png" title="MisterWong" alt="MisterWong" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.myspace.com/Modules/PostTo/Pages/?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;t=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships" title="MySpace"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/myspace.png" title="MySpace" alt="MySpace" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.netvibes.com/share?title=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F" title="Netvibes"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/netvibes.png" title="Netvibes" alt="Netvibes" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.netvouz.com/action/submitBookmark?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;title=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships&amp;popup=no" title="Netvouz"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/netvouz.png" title="Netvouz" alt="Netvouz" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.newsvine.com/_tools/seed&amp;save?u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;h=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships" title="NewsVine"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/newsvine.png" title="NewsVine" alt="NewsVine" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.propeller.com/submit/?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F" title="Propeller"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/propeller.png" title="Propeller" alt="Propeller" /></a>
	<a rel="nofollow"  target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;title=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships" title="Reddit"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" /></a>
	<a rel="nofollow"  target="_blank" href="http://slashdot.org/bookmark.pl?title=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F" title="Slashdot"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/slashdot.png" title="Slashdot" alt="Slashdot" /></a>
	<a rel="nofollow"  target="_blank" href="http://socialogs.com/add_story.php?story_url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;story_title=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships" title="Socialogs"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/socialogs.png" title="Socialogs" alt="Socialogs" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;title=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships" title="StumbleUpon"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" /></a>
	<a rel="nofollow"  target="_blank" href="http://technorati.com/faves?add=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F" title="Technorati"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/technorati.png" title="Technorati" alt="Technorati" /></a>
	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships%20-%20http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F" title="Twitter"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" /></a>
	<a rel="nofollow"  target="_blank" href="http://buzz.yahoo.com/submit/?submitUrl=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Funderstanding-sql-many-to-many-relationships%2F&amp;submitHeadline=Understanding%20SQL%3A%20Many%20to%20Many%20Relationships&amp;submitSummary=In%20the%20world%20of%20relational%20data%2C%20many-to-many%20relationships%20are%20one%20of%20the%20hardest%20concepts%20to%20understand%20and%20implement%20correctly.%20Quite%20likely%20the%20scenario%20will%20arise%20for%20a%20developer%20to%20decide%20whether%20to%20support%20a%20one-to-many%20or%20a%20many-to-many%20schem&amp;submitCategory=science&amp;submitAssetType=text" title="Yahoo! Buzz"><img src="http://www.comteken.com/wp-content/plugins/sociable/images/yahoobuzz.png" title="Yahoo! Buzz" alt="Yahoo! Buzz" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.comteken.com/database-programming/understanding-sql-many-to-many-relationships/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

