<?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; Database Programming</title>
	<atom:link href="http://www.comteken.com/category/database-programming/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>
		<item>
		<title>Improving Performance With LINQ</title>
		<link>http://www.comteken.com/database-programming/improving-performance-with-linq/</link>
		<comments>http://www.comteken.com/database-programming/improving-performance-with-linq/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 15:58:36 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Database Programming]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://www.comteken.com/?p=30</guid>
		<description><![CDATA[<a href="http://www.comteken.com/database-programming/improving-performance-with-linq/"><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>While the title of this article may seem misleading, you actually can achieve incredible performance gains by updating your web application to use LINQ. This article will dispell some common myths about LINQ and demonstrate how LINQ can practically increase performance. The examples in this article will be using LINQ to SQL, but the principles [...]]]></description>
			<content:encoded><![CDATA[<p>While the title of this article may seem misleading, you actually can achieve incredible performance gains by updating your web application to use LINQ. This article will dispell some common myths about LINQ and demonstrate how LINQ can practically increase performance. The examples in this article will be using LINQ to SQL, but the principles apply to LINQ to Entities as well.</p>
<p>First of all, it&#8217;s important to realize what LINQ is and what it isn&#8217;t. LINQ is a language feature you&#8217;ll see in Visual Studio 2008 (Visual Studio Orcas) and beyond. It&#8217;s not dependant on any particular .NET language as you can use it in C# or VB.NET. LINQ stands for &#8220;Language Integrated Query&#8221;, but its usage goes beyond language capabilities alone.</p>
<p>It is true that the language speeds up development by allowing you to use a simple query-syntax in C# or VB.NET to query data from a HashTable, XML file or SQL Database. And it&#8217;s also true that you can have Visual Studio 2008 write tons of code for you to build classes for your data tables (or even to build SQL tables from your classes). However, this article will demonstrate runtime performance gains you&#8217;ll see by using some built in features that come with the language as well.</p>
<p>The benefits we&#8217;ll discuss are:</p>
<ul>
<li>Intelligent query translations (such as faster data pagination).</li>
<li>Redundant query checking to prevent needless data hits.</li>
<li>Redundant update checking to ensure minimal data transfers.</li>
</ul>
<h3>Intelligent Query Translations</h3>
<p>One of the built-in benefits of using LINQ is that methods that are deemed &#8220;best practice&#8221; are used in the underlying technologies. For instance, if you were to use a standard ASP.NET 2.0 SqlDataSource, and you bound that data to a GridView with pagination turned on, you might not realize that you&#8217;re transferring your entire data table just to use a few rows at a time in your paginated GridView. This results in some heavy queries, heavy data transfers and often times slow page loads.</p>
<p>The best place to do pagination would be on the SQL server itself. That way you are only transferring the few rows that are desired, saving you much network bandwidth and time. Ultimately, LINQ isn&#8217;t doing anything that you couldn&#8217;t do yourself, but most developers do not know how to do <a rel="nofollow" href="http://www.singingeels.com/Articles/Pagination_In_SQL_Server_2005.aspx">Pagination In SQL Server 2005</a>, or they may not have time to change all of their queries to do so.</p>
<p>Again, if you take that simple &#8220;SqlDataSource&#8221; example above, but this time bind two ASP.NET controls to it (let&#8217;s say a GridView and a DropDownList), then you&#8217;ll be hitting your SQL server twice, and download all that data twice. This brings us to the next performance gain in LINQ.</p>
<h3>Redundant Query Checking</h3>
<p>Some of the biggest performance gains that I&#8217;ve benefited from by switching to LINQ is it&#8217;s ability to look at the &#8220;context&#8221; of your request to determine if it needs to hit the database again. If you&#8217;ve already started to use LINQ yourself, but you don&#8217;t know what I&#8217;m talking about, then you&#8217;ll probably have a new appreciation for LINQ in a few minutes.</p>
<p>LINQ uses a &#8220;DataContext&#8221; object to determine what connection string to use, what objects to map to and other internal things. But you should be careful not to think of the LINQ data context class as you would think of a traditional &#8220;SqlConnection&#8221;. If you are transitioning from using SqlConnections and SqlCommands you&#8217;ll probably code something like this:</p>
<div><span>// Example of doing your own straight SQL query:</span><br />
<span>public</span> <span>static</span> IEnumerable GetMyData()<br />
{<br />
<span>using</span> (SqlConnection myConnection = <span>new</span> SqlConnection(myConnectionString))<br />
{<br />
<span>using</span> (SqlCommand myCommand = myConnection.CreateCommand())<br />
{<br />
myCommand.CommandText = <span>&#8220;SELECT * FROM dbo.myTable&#8221;</span>;</p>
<p><span>using</span> (SqlDataAdapter myAdapter = <span>new</span> SqlDataAdapter(myCommand))<br />
{<br />
DataTable resultTable = <span>new</span> DataTable();</p>
<p>myAdapter.Fill(resultTable);</p>
<p><span>return</span> resultTable.Rows;<br />
}<br />
}<br />
}<br />
}</div>
<p>If you translated the above method into LINQ, then your method might look something like this:</p>
<div><span>// Example of <span>using</span> LINQ to query the <span>&#8220;Clients&#8221;</span> table:</span><br />
<span>public</span> <span>static</span> IEnumerable GetMyData()<br />
{<br />
<span>using</span> (MyDataContext myContext = <span>new</span> MyDataContext())<br />
{<br />
<span>return</span> <span>from</span> myRow <span>in</span> myContext.Clients <span>select</span> myRow;<br />
}<br />
}</div>
<p>This at first seems like an acceptable conversion from using a SqlConnection to using LINQ, but you&#8217;re missing out on so much (which you&#8217;ll see in a minute).</p>
<p>This is pretty much a 1 to 1 switch from writing your own SQL query to writing a query in LINQ. It is noteworthy that it takes a lot less code to query a database. However, these two code blocks will do the same thing, and you won&#8217;t gain any performance from calling the LINQ method instead of calling the straight SQL method. Even if you call both of these functions twice in a row, you won&#8217;t gain any performance because we are not utilizing the LINQ context correctly.</p>
<p>If we extend the range of our context to last for the entire web request (not just for the life of the function call) then we will begin to see performance increases. Before we examine how to do that, let&#8217;s look at this next example that should help explain how the context works. We&#8217;ll change our above method, &#8220;GetMyData&#8221;, so that we can pass in our own context. Here&#8217;s the code:</p>
<div><span>// Change the GetMyData method to take <span>in</span> an existing context.</span><br />
<span>public</span> <span>static</span> IEnumerable GetMyData(MyDataContext myContext)<br />
{<br />
<span>return</span> <span>from</span> myRow <span>in</span> myContext.Clients <span>select</span> myRow;<br />
}<span></p>
<p>// This will demonstrate how we are going to gain performance with LINQ:</span><br />
<span>protected</span> <span>void</span> Page_Load(<span>object</span> sender, EventArgs e)<br />
{<span><br />
// First, we create our data context just like we did before.</span><br />
MyDataContext myContext = <span>new</span> MyDataContext();<span></p>
<p>// Calling <span>this</span> function the first time will hit SQL and query the data.</span><br />
GetMyData(myContext);<span></p>
<p>// LINQ <span>is</span> smart enough to realize that we&#8217;ve already used <span>this</span> query</span><span><br />
// against <span>this</span> data context, so it won&#8217;t hit SQL again. Instead it will</span><span><br />
// simply <span>return</span> the same result <span>set</span> <span>as</span> last time.</span><br />
GetMyData(myContext);<span></p>
<p>// This <span>is</span> a bit ridiculous, but you <span>get</span> the idea.</span><br />
<span>for</span> (<span>int</span> i = 0; i &lt; 100; i++)<br />
{<br />
GetMyData(myContext);<br />
}<br />
}</div>
<p>The way to achieve the performance benefits of using the same data context during the entire page request is to store your data context instance in the HttpContext Items collection (which is alive for the duration of the thread). We&#8217;ll make a static property that will give us a data context instance, but because we are using the current HttpContext, we won&#8217;t have cross thread issues. You can read a little more about the HttpContext in this article: <a rel="nofollow" href="http://www.singingeels.com/Articles/Connect_Your_Site_With_HttpContext_Items.aspx">Connect Your Site With HttpContext Items</a>. Let&#8217;s look at the code to see how to achieve this:</p>
<div><span>public</span> <span>static</span> <span>class</span> DataAccessLayer<br />
{<span><br />
// This <span>object</span> <span>is</span> a <span>&#8220;key&#8221;</span> to the HttpContext Items dictionary.</span><br />
<span>private</span> <span>static</span> <span>object</span> _eelsContextKey = <span>new</span> <span>object</span>();<span></p>
<p>// This will always <span>return</span> an instance of the MyDataContext</span><span><br />
// (which was created by a LINQ wizard <span>in</span> Visual Studio 2008). It</span><span><br />
// will <span>return</span> the SAME instance <span>if</span> you call it twice during the</span><span><br />
// same HTTP request.</span><br />
<span>private</span> <span>static</span> MyDataContext Context<br />
{<br />
<span>get</span><br />
{<br />
<span>if</span> (HttpContext.Current.Items.Contains(DataAccessLayer._eelsContextKey) == <span>false</span>)<br />
{<br />
MyDataContext context = <span>new</span> MyDataContext(<span>&#8220;Connection String Here&#8230;&#8221;</span>);</p>
<p>HttpContext.Current.Items.Add(DataAccessLayer._eelsContextKey, context);</p>
<p><span>return</span> context;<br />
}<br />
<span>else</span><br />
{<br />
<span>return</span> (MyDataContext)HttpContext.Current.Items[DataAccessLayer._eelsContextKey];<br />
}<br />
}<br />
}<span></p>
<p>// Now we can make very simple DataAccessLayer functions like these:</span></p>
<p><span>public</span> <span>static</span> IEnumerable GetClients()<br />
{<br />
<span>return</span> <span>from</span> myRow <span>in</span> DataAccessLayer.Context.Clients <span>select</span> myRow;<br />
}</p>
<p><span>public</span> <span>static</span> IEnumerable GetProjects()<br />
{<br />
<span>return</span> <span>from</span> myRow <span>in</span> DataAccessLayer.Context.Projects <span>select</span> myRow;<br />
}</p>
<p><span>public</span> <span>static</span> IEnumerable GetThePoint()<br />
{<br />
<span>return</span> <span>from</span> myRow <span>in</span> DataAccessLayer.Context.You_Get_The_Point <span>select</span> myRow;<br />
}<br />
}</div>
<p>Let&#8217;s now look at the last area of performance gain from using LINQ that we will discuss.</p>
<h3>Redundant Update Checking</h3>
<p>The last place where you can see performance gains is with writing back to your data source. The LINQ data context not only remembers if you have already queried some data before, but it also keeps track of any changes that are made. This means that if you call the &#8220;save&#8221; function, but no changes were made first, then LINQ will ignore the request to save. Likewise, if you only change one property (such as &#8220;FirstName&#8221;), then LINQ will build an UPDATE statement that only contains that one column (again saving time and bandwidth).</p>
<h3>That&#8217;s a Wrap!</h3>
<p>New technologies may sometimes seem dauting (or even pointless). Hopefully this article has helped you to appreciate the clear benefits of using LINQ. Download Visual Studio Orcas (beta 2 at this point) and try out some of the examples in this article. I hope you grow to love LINQ as I have.</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%2Fimproving-performance-with-linq%2F&amp;title=Improving%20Performance%20With%20LINQ&amp;bodytext=While%20the%20title%20of%20this%20article%20may%20seem%20misleading%2C%20you%20actually%20can%20achieve%20incredible%20performance%20gains%20by%20updating%20your%20web%20application%20to%20use%20LINQ.%20This%20article%20will%20dispell%20some%20common%20myths%20about%20LINQ%20and%20demonstrate%20how%20LINQ%20can%20practically%20i" 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%2Fimproving-performance-with-linq%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%2Fimproving-performance-with-linq%2F&amp;title=Improving%20Performance%20With%20LINQ&amp;notes=While%20the%20title%20of%20this%20article%20may%20seem%20misleading%2C%20you%20actually%20can%20achieve%20incredible%20performance%20gains%20by%20updating%20your%20web%20application%20to%20use%20LINQ.%20This%20article%20will%20dispell%20some%20common%20myths%20about%20LINQ%20and%20demonstrate%20how%20LINQ%20can%20practically%20i" 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%2Fimproving-performance-with-linq%2F&amp;t=Improving%20Performance%20With%20LINQ" 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%2Fimproving-performance-with-linq%2F&amp;title=Improving%20Performance%20With%20LINQ" 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%2Fimproving-performance-with-linq%2F&amp;title=Improving%20Performance%20With%20LINQ&amp;annotation=While%20the%20title%20of%20this%20article%20may%20seem%20misleading%2C%20you%20actually%20can%20achieve%20incredible%20performance%20gains%20by%20updating%20your%20web%20application%20to%20use%20LINQ.%20This%20article%20will%20dispell%20some%20common%20myths%20about%20LINQ%20and%20demonstrate%20how%20LINQ%20can%20practically%20i" 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%2Fimproving-performance-with-linq%2F&amp;Title=Improving%20Performance%20With%20LINQ" 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%2Fimproving-performance-with-linq%2F&amp;title=Improving%20Performance%20With%20LINQ" 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=Improving%20Performance%20With%20LINQ&amp;u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fimproving-performance-with-linq%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%2Fimproving-performance-with-linq%2F&amp;title=Improving%20Performance%20With%20LINQ" 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%2Fimproving-performance-with-linq%2F&amp;headline=Improving%20Performance%20With%20LINQ&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%2Fimproving-performance-with-linq%2F&amp;title=Improving%20Performance%20With%20LINQ&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=While%20the%20title%20of%20this%20article%20may%20seem%20misleading%2C%20you%20actually%20can%20achieve%20incredible%20performance%20gains%20by%20updating%20your%20web%20application%20to%20use%20LINQ.%20This%20article%20will%20dispell%20some%20common%20myths%20about%20LINQ%20and%20demonstrate%20how%20LINQ%20can%20practically%20i" 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%2Fimproving-performance-with-linq%2F&amp;title=Improving%20Performance%20With%20LINQ" 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%2Fimproving-performance-with-linq%2F&amp;bm_description=Improving%20Performance%20With%20LINQ&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%2Fimproving-performance-with-linq%2F&amp;t=Improving%20Performance%20With%20LINQ" 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=Improving%20Performance%20With%20LINQ&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fimproving-performance-with-linq%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%2Fimproving-performance-with-linq%2F&amp;title=Improving%20Performance%20With%20LINQ&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%2Fimproving-performance-with-linq%2F&amp;h=Improving%20Performance%20With%20LINQ" 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%2Fimproving-performance-with-linq%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%2Fimproving-performance-with-linq%2F&amp;title=Improving%20Performance%20With%20LINQ" 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=Improving%20Performance%20With%20LINQ&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fimproving-performance-with-linq%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%2Fimproving-performance-with-linq%2F&amp;story_title=Improving%20Performance%20With%20LINQ" 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%2Fimproving-performance-with-linq%2F&amp;title=Improving%20Performance%20With%20LINQ" 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%2Fimproving-performance-with-linq%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=Improving%20Performance%20With%20LINQ%20-%20http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fimproving-performance-with-linq%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%2Fimproving-performance-with-linq%2F&amp;submitHeadline=Improving%20Performance%20With%20LINQ&amp;submitSummary=While%20the%20title%20of%20this%20article%20may%20seem%20misleading%2C%20you%20actually%20can%20achieve%20incredible%20performance%20gains%20by%20updating%20your%20web%20application%20to%20use%20LINQ.%20This%20article%20will%20dispell%20some%20common%20myths%20about%20LINQ%20and%20demonstrate%20how%20LINQ%20can%20practically%20i&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/improving-performance-with-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learn The Basics Of LINQ</title>
		<link>http://www.comteken.com/database-programming/learn-the-basics-of-linq/</link>
		<comments>http://www.comteken.com/database-programming/learn-the-basics-of-linq/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 15:48:50 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Database Programming]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://www.comteken.com/?p=28</guid>
		<description><![CDATA[<a href="http://www.comteken.com/database-programming/learn-the-basics-of-linq/"><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>LINQ (Language INtegrated Query) is a powerful but misunderstood new language feature brought to us in the .NET framework version 3.5 (C# 3.0 and VB 9). Even though this is a new feature, it already has some huge misconceptions (such as thinking LINQ is a replacement to SQL). This article will teach you how to [...]]]></description>
			<content:encoded><![CDATA[<p>LINQ (Language INtegrated Query) is a powerful but misunderstood new language feature brought to us in the .NET framework version 3.5 (C# 3.0 and VB 9). Even though this is a new feature, it already has some huge misconceptions (such as thinking LINQ is a replacement to SQL). This article will teach you how to use LINQ (the language itself), where LINQ can save you a lot of time and will cover some basic concepts of Extension Methods and Lambda expressions.</p>
<h3>The Need for LINQ</h3>
<p>At first, when I didn&#8217;t understand LINQ, I couldn&#8217;t appreciate why we needed (or why anyone wanted) it. LINQ seemed very limited in usefulness, and I, like many of my colleagues, bashed it in ignorance. Now, due to understanding the semantics and benefits of the language, I&#8217;ve come to love it and wonder how I lived without it.</p>
<p>LINQ does not allow us to do anything new, as far as functionality goes. Really, if you wanted to make the argument of a &#8216;real programmer&#8217;, you could do all of this same functionality by writing encyclopedias of C code (heck, might as well just write it in assembly for &#8220;performance&#8221; reasons). But, LINQ does create a new way of looking at enumerations of data, and gives out-of-the-box functionality for them.</p>
<p>I realize that the above paragraphs might seem vague, so I&#8217;ll get right into real examples that I have used as well as some odd examples that you might not have thought about as being &#8216;queryable objects&#8217;.</p>
<h3>Baby Steps &#8211; Basic LINQ Queries</h3>
<p>Let&#8217;s look at some very simple examples of LINQ so that we can have a basis to grow on. Let&#8217;s pretend that we have a user control that has a variable amount of TextBoxes added to it (based on some database query or whatever). Our user control might have other controls (Buttons, Literals and the like), and we want to disable all of the TextBoxes if the user doesn&#8217;t have security permissions to edit these controls. Please keep in mind that this is a hypothetical scenario at this point just so we can see some basic LINQ (in this case, LINQ to Objects).</p>
<p>Now, you can do this a few ways. Because the number of TextBoxes is dynamic we would possibly do something like this:</p>
<div><span>// Loop through all of the controls.</span><br />
<span>foreach</span> (Control myChildControl <span>in</span> <span>this</span>.Controls)<br />
{<span><br />
// Make sure the control <span>is</span> a TextBox.</span><br />
<span>if</span> (myChildControl <span>is</span> TextBox)<br />
{<span><br />
// Cast that <span>&#8220;Control&#8221;</span> <span>object</span> to a TextBox and disable it.</span><br />
((TextBox)myChildControl).Enabled = <span>false</span>;<br />
}<br />
}</div>
<p>The above code isn&#8217;t really that bad, but I for one don&#8217;t like that I have to loop through all of my controls, check the type, cast it to the type that I just checked for, and then set my property. So, let&#8217;s see how LINQ will not only &#8220;pretty up&#8221; my code, but will also make more sense to us programmers:</p>
<div><span>// Define a enumeration only containing child TextBoxes.</span><br />
<span>var</span> myChildTextBoxes = <span>from</span> myChildControl <span>in</span> <span>this</span>.Controls<br />
<span>where</span> myChildControl <span>is</span> TextBox<br />
<span>select</span> myChildControl;<span></p>
<p>// Loop through my TextBoxes.</span><br />
<span>foreach</span> (TextBox myChildTextBox <span>in</span> myChildTextBoxes)<br />
{<span><br />
// Disable the TextBox.</span><br />
myChildTextBox.Enabled = <span>false</span>;<br />
}</div>
<p>This LINQ approach is much cleaner. It&#8217;s clear from the start that you want to work with a list of TextBoxes only. Secondly, you aren&#8217;t type checking, then re-type casting. Now, you might argue that you could avoid the second type-cast by using an &#8220;as&#8221; keyword and checking for nulls, or you could say that you don&#8217;t like how many lines of code this takes. Those are some valid claims, but if you are thinking that, then apparently you have a short attention span (as I mentioned above that this is just to get you a little familiar with the language syntax).</p>
<h3>Step Two &#8211; Querying Unconventional Data Sources</h3>
<p>Once you begin to use LINQ a bit more in you&#8217;re C# (or VB), you&#8217;ll begin to think of &#8216;data sources&#8217; in a different way. For instance, you may see a directory (a folder on your computer) as a data source of files. You can even start to look at your list of running processes as a data source. Really, no enumeration is safe!</p>
<p>What if you were to make a web application that allowed you to upload and download files from your home machine? Let&#8217;s say you had a DropDownList that would show a list of the files in the specified directory, perhaps with a button that lets you download it. How would you go about populating that DropDownList with clean file names for the &#8220;Text&#8221; property and perhaps the path for the &#8220;Value&#8221; property? I&#8217;ll go a step further and say that this is what you&#8217;re DropDownList looks like in ASP.NET:</p>
<div>&lt;<span>asp:DropDownList</span> <span>ID</span><span>=&#8221;MyFilesList&#8221;</span> <span>runat</span><span>=&#8221;server&#8221;</span><br />
<span>DataTextField</span><span>=&#8221;FileName&#8221;</span> <span>DataValueField</span><span>=&#8221;FullPath&#8221;</span> /&gt;</div>
<p>Well, you could create you&#8217;re own custom class that has a FileName property and a FullPath property. Then you could make a generic list of that class, loop through the files in a Directory.GetFiles method, add an entry for each file, set the list as the DataSource of the DropDownList and data bind. That&#8217;s a whole lot of nasty that I&#8217;m not even going to show the code for (really, because I never want to write nasty code like that again). Here&#8217;s what I would do using LINQ:</p>
<div><span>// Set the DataSource of our DropDownList to an enumeration of a <span>new</span></span><span><br />
// <span>&#8220;anonymous type&#8221;</span> (meaning a <span>class</span> that <span>is</span> being built <span>on</span> the fly)</span><span><br />
// that contains the file names and full paths <span>in</span> our directory.</span><br />
<span>this</span>.MyFilesList.DataSource = <span>from</span> file <span>in</span> Directory.GetFiles(somePath)<br />
<span>select</span> <span>new</span><br />
{<br />
FileName = Path.GetFileName(file),<br />
FullPath = file<br />
};<span></p>
<p>// Call the <span>&#8220;DataBind&#8221;</span> method <img src='http://www.comteken.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </span><br />
<span>this</span>.MyFilesList.DataBind();</div>
<p>All I can say after that is &#8220;Go LINQ GO!&#8221; and of course &#8220;case closed!&#8221;</p>
<h3>Extension Methods and Lambda Expressions</h3>
<p>One more part to LINQ is the heavy use of Extension Methods and Lambda expressions to accomplish this beautiful language enhancement. If you remember our original example of disabling the TextBoxes, then you&#8217;re going to love one of the 50 STANDARD OPERATORS that are brought to you just by including a reference to the System.Linq namespace! Check this out:</p>
<div><span>// Loop through my TextBoxes.</span><br />
<span>foreach</span> (TextBox myChildTextBox <span>in</span> <span>this</span>.Controls.OfType&lt;TextBox&gt;())<br />
{<span><br />
// Disable the TextBox.</span><br />
myChildTextBox.Enabled = <span>false</span>;<br />
}</div>
<p>Don&#8217;t check you&#8217;re MSDN&#8230; there is no method called &#8220;OfType&#8221; on the ControlCollection class. But, because the ControlCollection class implements the IEnumerable interface, it automatically gets all of the extension methods that LINQ has kindly given to any enumeration (such as &#8220;OfType&#8221; which I am using above).</p>
<p>LINQ can be done one of two ways (or a combination of both): query expressions or method expressions. The difference between the two is only a syntax difference, as they ultimately compile into the same thing. Example:</p>
<div><span>// This line of code&#8230;</span><br />
<span>var</span> textBoxes = <span>from</span> control <span>in</span> <span>this</span>.Controls<br />
<span>where</span> control <span>is</span> TextBox <span>select</span> control;<span></p>
<p>// <span>is</span> the same thing <span>as</span> <span>this</span>.</span><br />
<span>var</span> textBoxes = <span>this</span>.Controls.OfType&lt;TextBox&gt;();</div>
<p>Lambda expressions come into play when you want to perform another standard operation such as &#8220;SUM&#8221; or &#8220;MAX&#8221;. Here&#8217;s an example that I have used recently. I wanted to make a property that displayed the &#8220;TotalBill&#8221; of an object that had child &#8220;orders&#8221; in it. Here&#8217;s how lambda helped out:</p>
<div><span>public</span> <span>decimal</span> TotalBill<br />
{<br />
<span>get</span><br />
{<span><br />
// Keep <span>in</span> mind that <span>&#8220;Orders&#8221;</span> <span>is</span> just a list of</span><span><br />
// &#8216;Order&#8217; objects and has no special functionality.</span><br />
<span>return</span> <span>this</span>.Orders.Sum(order =&gt; order.Price);<br />
}<br />
}</div>
<p>If you&#8217;re not quite familiar with lambda as of yet, you can get a better explaination of the above in a blog post I made not long ago: LINQ, Lamda and Extension Methods Work Together!</p>
<h3>Conclusion</h3>
<p>There is much more to say about LINQ, but I hope for now you have a basic understanding and appreciation for it. As I get more time, I&#8217;ll talk about some deeper subjects with LINQ such as how to use it in an enterprise level application and how to gain performance and improve multi-developer cohesion with it.</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%2Flearn-the-basics-of-linq%2F&amp;title=Learn%20The%20Basics%20Of%20LINQ&amp;bodytext=LINQ%20%28Language%20INtegrated%20Query%29%20is%20a%20powerful%20but%20misunderstood%20new%20language%20feature%20brought%20to%20us%20in%20the%20.NET%20framework%20version%203.5%20%28C%23%203.0%20and%20VB%209%29.%20Even%20though%20this%20is%20a%20new%20feature%2C%20it%20already%20has%20some%20huge%20misconceptions%20%28such%20as%20thinking%20LINQ" 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%2Flearn-the-basics-of-linq%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%2Flearn-the-basics-of-linq%2F&amp;title=Learn%20The%20Basics%20Of%20LINQ&amp;notes=LINQ%20%28Language%20INtegrated%20Query%29%20is%20a%20powerful%20but%20misunderstood%20new%20language%20feature%20brought%20to%20us%20in%20the%20.NET%20framework%20version%203.5%20%28C%23%203.0%20and%20VB%209%29.%20Even%20though%20this%20is%20a%20new%20feature%2C%20it%20already%20has%20some%20huge%20misconceptions%20%28such%20as%20thinking%20LINQ" 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%2Flearn-the-basics-of-linq%2F&amp;t=Learn%20The%20Basics%20Of%20LINQ" 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%2Flearn-the-basics-of-linq%2F&amp;title=Learn%20The%20Basics%20Of%20LINQ" 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%2Flearn-the-basics-of-linq%2F&amp;title=Learn%20The%20Basics%20Of%20LINQ&amp;annotation=LINQ%20%28Language%20INtegrated%20Query%29%20is%20a%20powerful%20but%20misunderstood%20new%20language%20feature%20brought%20to%20us%20in%20the%20.NET%20framework%20version%203.5%20%28C%23%203.0%20and%20VB%209%29.%20Even%20though%20this%20is%20a%20new%20feature%2C%20it%20already%20has%20some%20huge%20misconceptions%20%28such%20as%20thinking%20LINQ" 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%2Flearn-the-basics-of-linq%2F&amp;Title=Learn%20The%20Basics%20Of%20LINQ" 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%2Flearn-the-basics-of-linq%2F&amp;title=Learn%20The%20Basics%20Of%20LINQ" 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=Learn%20The%20Basics%20Of%20LINQ&amp;u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Flearn-the-basics-of-linq%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%2Flearn-the-basics-of-linq%2F&amp;title=Learn%20The%20Basics%20Of%20LINQ" 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%2Flearn-the-basics-of-linq%2F&amp;headline=Learn%20The%20Basics%20Of%20LINQ&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%2Flearn-the-basics-of-linq%2F&amp;title=Learn%20The%20Basics%20Of%20LINQ&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=LINQ%20%28Language%20INtegrated%20Query%29%20is%20a%20powerful%20but%20misunderstood%20new%20language%20feature%20brought%20to%20us%20in%20the%20.NET%20framework%20version%203.5%20%28C%23%203.0%20and%20VB%209%29.%20Even%20though%20this%20is%20a%20new%20feature%2C%20it%20already%20has%20some%20huge%20misconceptions%20%28such%20as%20thinking%20LINQ" 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%2Flearn-the-basics-of-linq%2F&amp;title=Learn%20The%20Basics%20Of%20LINQ" 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%2Flearn-the-basics-of-linq%2F&amp;bm_description=Learn%20The%20Basics%20Of%20LINQ&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%2Flearn-the-basics-of-linq%2F&amp;t=Learn%20The%20Basics%20Of%20LINQ" 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=Learn%20The%20Basics%20Of%20LINQ&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Flearn-the-basics-of-linq%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%2Flearn-the-basics-of-linq%2F&amp;title=Learn%20The%20Basics%20Of%20LINQ&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%2Flearn-the-basics-of-linq%2F&amp;h=Learn%20The%20Basics%20Of%20LINQ" 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%2Flearn-the-basics-of-linq%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%2Flearn-the-basics-of-linq%2F&amp;title=Learn%20The%20Basics%20Of%20LINQ" 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=Learn%20The%20Basics%20Of%20LINQ&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Flearn-the-basics-of-linq%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%2Flearn-the-basics-of-linq%2F&amp;story_title=Learn%20The%20Basics%20Of%20LINQ" 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%2Flearn-the-basics-of-linq%2F&amp;title=Learn%20The%20Basics%20Of%20LINQ" 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%2Flearn-the-basics-of-linq%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=Learn%20The%20Basics%20Of%20LINQ%20-%20http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Flearn-the-basics-of-linq%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%2Flearn-the-basics-of-linq%2F&amp;submitHeadline=Learn%20The%20Basics%20Of%20LINQ&amp;submitSummary=LINQ%20%28Language%20INtegrated%20Query%29%20is%20a%20powerful%20but%20misunderstood%20new%20language%20feature%20brought%20to%20us%20in%20the%20.NET%20framework%20version%203.5%20%28C%23%203.0%20and%20VB%209%29.%20Even%20though%20this%20is%20a%20new%20feature%2C%20it%20already%20has%20some%20huge%20misconceptions%20%28such%20as%20thinking%20LINQ&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/learn-the-basics-of-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Self Sorting GridView with LINQ Expression Trees</title>
		<link>http://www.comteken.com/database-programming/self-sorting-gridview-with-linq-expression-trees/</link>
		<comments>http://www.comteken.com/database-programming/self-sorting-gridview-with-linq-expression-trees/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 15:47:16 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Database Programming]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://www.comteken.com/?p=26</guid>
		<description><![CDATA[<a href="http://www.comteken.com/database-programming/self-sorting-gridview-with-linq-expression-trees/"><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>The GridView control in ASP.NET 2.0 is lacking some major (yet common) functionality &#8211; sorting. This article will show you how to create a &#8220;self-sorting&#8221; GridView using LINQ expression trees. First, it&#8217;s important to explain what I mean when I say that the GridView doesn&#8217;t have sorting capabilities. You&#8217;re probably saying to yourself &#8211; &#8220;I [...]]]></description>
			<content:encoded><![CDATA[<p>The GridView control in ASP.NET 2.0 is lacking some major (yet common) functionality &#8211; sorting. This article will show you how to create a &#8220;self-sorting&#8221; GridView using LINQ expression trees.</p>
<p>First, it&#8217;s important to explain what I mean when I say that the GridView doesn&#8217;t have sorting capabilities. You&#8217;re probably saying to yourself &#8211; &#8220;I know the GridView has sorting built in because it has a &#8216;Sort&#8217; method and &#8216;Sorting&#8217; and &#8216;Sorted&#8217; events.&#8221; And that&#8217;s true, but those are merely placeholders that allow you to write your own sorting code.</p>
<p>Also, if you use the designer to build your GridViews, and bind them to SQL data sources, then you might also be confused about the above statements. But rest assured that the sorting magic is all happening in the terribly inefficient SqlDataSource control, and not the actual GridView itself.</p>
<p>If you&#8217;re not already familiar with the basics of LINQ, then you might want to first read this article: Learn The Basics of LINQ. To sum up LINQ in one sentence (for the purpose of moving on) I would say: &#8220;LINQ is a language feature in .NET that provides a ton of out-of-the-box functionality for querying data.&#8221;</p>
<h3>The Problem &#8211; Why The GridView Can&#8217;t Sort</h3>
<p>So why is it that the GridView control doesn&#8217;t have the ability to sort by default? The problem lies in the fact that the data source is very dynamic, could be of any type and could even be just a paged subset of the ultimate source.</p>
<p>Another problem is performance. If your data source was from a SQL table, then you would want to pass the sorting functionality on to the SQL Server itself to gain the most performance. Because the GridView doesn&#8217;t know what your source will be, it can&#8217;t really provide the needed functionality.</p>
<h3>The Solution &#8211; LINQ</h3>
<p>Since LINQ provides querying capabilities on a generic level, the above problems are no problem. Because LINQ to objects can handle *any* enumerable objects, and LINQ to SQL is smart enough to pass the sorting logic on to SQL Server, you win no matter what.</p>
<p>For example, imagine if the data source was a collection of MembershipUsers (via the Membership.GetUsers method). Here&#8217;s how easy it would be to sort using LINQ and the OrderBy method:</p>
<div><span>// Using LINQ to sort by a user&#8217;s name.</span><br />
myGridView.DataSource = Membership.GetUsers()<br />
.OfType&lt;MembershipUser&gt;()<br />
.OrderBy(user =&gt; user.Name);</div>
<p>That was very easy to do, but that&#8217;s because we know the data type of our source at compile time. But if we are going to make a generic &#8220;self sorting GridView&#8221;, then we have to build our functionality with the limitation of not knowing the data type of the data source or the name of the field that is being sorted. So we&#8217;ll need to reconstruct this functionality at runtime by building &#8220;expression trees&#8221; (the power behind LINQ).</p>
<h3>Step One &#8211; Build Our GridView Control</h3>
<p>To begin with, let&#8217;s build a basic control that inherits from GridView , and stub out a placeholder to put our sorting logic.</p>
<div><span>public</span> <span>class</span> SelfSortingGridView : GridView<br />
{<br />
<span>protected</span> <span>override</span> <span>void</span> OnSorting(GridViewSortEventArgs e)<br />
{<span><br />
// Our code below <span>is</span> going to live here&#8230;</span><br />
}<br />
}</div>
<p>Now that we have our custom GridView control ready to go, we can move on to step two.</p>
<h3>Step Two &#8211; Creating an Expression to Sort With</h3>
<p>As was stated earlier, we need to build an expression that will tell LINQ how we want to sort our data source. There are a few tricky issues here that we need to identify and overcome. If we try to copy the example found in this blog post to reproduce our sorting example at the top of this article, we would get half-way there:</p>
<div><span>// Using a custom LINQ expression to sort by a user&#8217;s name.</span><br />
<span>var</span> param = Expression.Parameter(<span>typeof</span>(MembershipUser), <span>&#8220;user&#8221;</span>);<span></p>
<p>// By the way, <span>if</span> you don&#8217;t <span>&#8220;box&#8221;</span> the <span>return</span> type <span>into</span> an <span>object</span>,</span><span><br />
// you&#8217;ll <span>get</span> a runtime error when you <span>try</span> to sort by a value type.</span><span><br />
// So instead of doing <span>this</span> (which would be expected):</span><br />
<span>var</span> sortExpression = Expression.Lambda&lt;Func&lt;MembershipUser, <span>object</span>&gt;<br />
(Expression.Property(param, <span>&#8220;Name&#8221;</span>), param);<span></p>
<p>// I&#8217;m going to <span>do</span> <span>this</span>:</span><br />
<span>var</span> sortExpression = Expression.Lambda&lt;Func&lt;MembershipUser, <span>object</span>&gt;<br />
(Expression.Convert(Expression.Property(param, <span>&#8220;Name&#8221;</span>), <span>typeof</span>(<span>object</span>)), param);<span></p>
<p>// And then I can sort my data source:</span><br />
myGridView.DataSource = Membership.GetUsers()<br />
.OfType&lt;MembershipUser&gt;().OrderBy(sortExpression);</div>
<p>So we&#8217;ve solved one issue &#8211; that of finding the property to sort with by it&#8217;s name. The &#8220;Expression.Property&#8221; method above did that for us. Now, we have to solve the second issue &#8211; not knowing what the data type of the data source will be until runtime. To solve this in the fewest lines of code, I&#8217;m going to make a custom generic class that will create the sort expression for us so that we can simply supply the type at runtime.</p>
<div><span>public</span> <span>class</span> GenericSorter&lt;T&gt;<br />
{<br />
<span>public</span> IEnumerable&lt;T&gt; Sort(IEnumerable&lt;T&gt; source, <span>string</span> sortBy)<br />
{<br />
<span>var</span> param = Expression.Parameter(<span>typeof</span>(T), <span>&#8220;item&#8221;</span>);</p>
<p><span>var</span> sortExpression = Expression.Lambda&lt;Func&lt;T, <span>object</span>&gt;&gt;<br />
(Expression.Convert(Expression.Property(param, sortBy), <span>typeof</span>(<span>object</span>)), param);</p>
<p><span>return</span> source.AsQueryable&lt;T&gt;().OrderBy&lt;T, <span>object</span>&gt;(sortExpression);<br />
}<br />
}</div>
<p>Beautiful! Notice that because we are using a generic class, we can tell the compiler that we want to use the type &#8220;T&#8221; (whatever &#8220;T&#8221; will be at runtime, we don&#8217;t care)! So, if I wanted to create an instance of my GenericSorter class at runtime, passing in a type that I won&#8217;t know until runtime, and then call the &#8220;Sort&#8221; method, I would just do some simple reflection as will be shown below.</p>
<p>For simplicities sake, the data source is stored in a variable called &#8220;_data&#8221;. You can download the whole source code at the end of the article to see exactly how it&#8217;s done. Here&#8217;s a sample of the code:</p>
<div><span>// Give me the data type of the GridView&#8217;s data source.</span><br />
Type dataSourceType = _data.GetType();<span></p>
<p>// Determine the data type of the items <span>in</span> the data source at runtime.</span><br />
Type dataItemType = <span>typeof</span>(<span>object</span>);</p>
<p><span>if</span> (dataSourceType.HasElementType)<br />
{<span><br />
// Get the element type <span>if</span> the data source <span>is</span> an array.</span><br />
dataItemType = dataSourceType.GetElementType();<br />
}<br />
<span>else</span> <span>if</span> (dataSourceType.IsGenericType)<br />
{<span><br />
// Get the element type <span>if</span> the data source <span>is</span> a generic list.</span><br />
dataItemType = dataSourceType.GetGenericArguments()[0];<br />
}<span></p>
<p>// Create an instance of the GenericSorter <span>class</span> passing <span>in</span> the data item type.</span><br />
Type sorterType = <span>typeof</span>(GenericSorter&lt;&gt;).MakeGenericType(dataItemType);</p>
<p><span>var</span> sorterObject = Activator.CreateInstance(sorterType);<span></p>
<p>// Now I can call the <span>&#8220;Sort&#8221;</span> method passing <span>in</span> my runtime types.</span><br />
<span>this</span>.DataSource = sorterType.GetMethod(<span>&#8220;Sort&#8221;</span>, <span>new</span> Type[] { dataSourceType, <span>typeof</span>(<span>string</span>) })<br />
.Invoke(sorterObject, <span>new</span> <span>object</span>[] { _data, e.SortExpression });</p>
<p><span>this</span>.DataBind();</div>
<h3>Conclusion</h3>
<p>At first glance, it may seem like we&#8217;re doing a lot of code just for sorting functionality. You may even be thinking that this is an extremely convoluted way of sorting a GridView, but really it&#8217;s not. Once you understand what LINQ is doing, and how to build your own expression trees, you&#8217;ll really appreciate this new language feature in .NET.</p>
<p>I&#8217;ll include a web project that has the full source code and some examples of different objects that can be sorted here. If you first don&#8217;t understand what all is going on, I&#8217;d recommend that you download the source code and step through it in the debugger.</p>
<p>I hope this article has excited you about LINQ and expression trees. If you&#8217;re not excited, I hope your informed. If you don&#8217;t feel informed, I hope at least that you&#8217;re not now afraid of LINQ.</p>
<p>Here&#8217;s the source code and sample project: <a href="http://www.singingeels.com/Articles/Articles/UserFile.aspx?FileID=d88d86f6-08e1-40fc-b908-2b4584036099">SingingEels_LinqSelfSortingGridView.zip</a></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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;title=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees&amp;bodytext=The%20GridView%20control%20in%20ASP.NET%202.0%20is%20lacking%20some%20major%20%28yet%20common%29%20functionality%20-%20sorting.%20This%20article%20will%20show%20you%20how%20to%20create%20a%20%22self-sorting%22%20GridView%20using%20LINQ%20expression%20trees.%0D%0A%0D%0AFirst%2C%20it%27s%20important%20to%20explain%20what%20I%20mean%20when%20I%20say" 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%2Fself-sorting-gridview-with-linq-expression-trees%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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;title=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees&amp;notes=The%20GridView%20control%20in%20ASP.NET%202.0%20is%20lacking%20some%20major%20%28yet%20common%29%20functionality%20-%20sorting.%20This%20article%20will%20show%20you%20how%20to%20create%20a%20%22self-sorting%22%20GridView%20using%20LINQ%20expression%20trees.%0D%0A%0D%0AFirst%2C%20it%27s%20important%20to%20explain%20what%20I%20mean%20when%20I%20say" 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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;t=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees" 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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;title=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees" 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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;title=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees&amp;annotation=The%20GridView%20control%20in%20ASP.NET%202.0%20is%20lacking%20some%20major%20%28yet%20common%29%20functionality%20-%20sorting.%20This%20article%20will%20show%20you%20how%20to%20create%20a%20%22self-sorting%22%20GridView%20using%20LINQ%20expression%20trees.%0D%0A%0D%0AFirst%2C%20it%27s%20important%20to%20explain%20what%20I%20mean%20when%20I%20say" 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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;Title=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees" 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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;title=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees" 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=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees&amp;u=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fself-sorting-gridview-with-linq-expression-trees%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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;title=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees" 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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;headline=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees&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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;title=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees&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%20GridView%20control%20in%20ASP.NET%202.0%20is%20lacking%20some%20major%20%28yet%20common%29%20functionality%20-%20sorting.%20This%20article%20will%20show%20you%20how%20to%20create%20a%20%22self-sorting%22%20GridView%20using%20LINQ%20expression%20trees.%0D%0A%0D%0AFirst%2C%20it%27s%20important%20to%20explain%20what%20I%20mean%20when%20I%20say" 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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;title=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees" 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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;bm_description=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees&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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;t=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees" 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=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fself-sorting-gridview-with-linq-expression-trees%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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;title=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees&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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;h=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees" 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%2Fself-sorting-gridview-with-linq-expression-trees%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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;title=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees" 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=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees&amp;url=http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fself-sorting-gridview-with-linq-expression-trees%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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;story_title=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees" 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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;title=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees" 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%2Fself-sorting-gridview-with-linq-expression-trees%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=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees%20-%20http%3A%2F%2Fwww.comteken.com%2Fdatabase-programming%2Fself-sorting-gridview-with-linq-expression-trees%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%2Fself-sorting-gridview-with-linq-expression-trees%2F&amp;submitHeadline=Self%20Sorting%20GridView%20with%20LINQ%20Expression%20Trees&amp;submitSummary=The%20GridView%20control%20in%20ASP.NET%202.0%20is%20lacking%20some%20major%20%28yet%20common%29%20functionality%20-%20sorting.%20This%20article%20will%20show%20you%20how%20to%20create%20a%20%22self-sorting%22%20GridView%20using%20LINQ%20expression%20trees.%0D%0A%0D%0AFirst%2C%20it%27s%20important%20to%20explain%20what%20I%20mean%20when%20I%20say&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/self-sorting-gridview-with-linq-expression-trees/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

