<?xml version="1.0"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title>Stuart Blackler's News Feed</title>
		<link>http://sblackler.net/</link>
		<description>All of the articles from http://sblackler.net/</description>
		<atom:link href="/rss.xml" rel="self" type="application/rss+xml" />
		
			<item>
				<title>Using IDisposible correctly</title>
				<description>&lt;p&gt;&lt;em&gt;After a rather long period of absence thanks to Bournemouth University, I am back again. There are a few subtle changes happening on the website as and when I can get time to make the changes. If you notice a bug or would like to suggest an improvement please do via the comments section on every post or via the social media links in the about page.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In this article, I am going to show you how to use the &lt;code&gt;IDisposable&lt;/code&gt; interface correctly in your code. When I read others code, it is easy to pick up on subtle bugs. We need to begin to train ourselves to see the bugs and we do this by understanding what we are using. Before we begin, we need to make sure that we understand a core piece of computer science theory: Destructors.&lt;/p&gt;

&lt;h2&gt;Destructors&lt;/h2&gt;

&lt;p&gt;Generally speaking, destructors are the computers way of releasing resources from an application. In environments that contain a virtual machine with a garbage collection facility, the destructor is automatically called. In these environments however, the destructor is also called a &lt;code&gt;Finalizer&lt;/code&gt;. Although these environments are &lt;s&gt;good&lt;/s&gt; excellent at managing memory for us, we cannot guarantee when the &lt;code&gt;Finalizer&lt;/code&gt; is going to be called.&lt;/p&gt;

&lt;h2&gt;Enter Dispose&lt;/h2&gt;

&lt;p&gt;The purpose of the &lt;code&gt;Dispose&lt;/code&gt; is to guarantee when we are going to release resources. This might be at the end of a &lt;code&gt;foreach&lt;/code&gt; loop or at the end of a database connection. Either way, we have control of when we can release the resources. There are two types of resources that can be released: Managed and Unmanaged.&lt;/p&gt;

&lt;p&gt;Managed resources are typically objects that are run and controlled by the Common Language Runtime (CLR). Managed code supplies the metadata necessary for the CLR to provide services such as memory management and cross-language integration &lt;a href=&quot;http://stackoverflow.com/questions/334326/what-is-managed-unmanaged-code-in-c&quot;&gt;(Source)&lt;/a&gt;. Unmanaged resources are those outside the CLR such as Win32 API's. These can be called from within managed code allowing some serious memory leaks if we are not careful.&lt;/p&gt;

&lt;p&gt;The .Net libraries have some useful interfaces in them, one of them being the &lt;code&gt;IDisposable&lt;/code&gt; interface. This interface has just one method called &lt;code&gt;Dispose&lt;/code&gt; (the name seems standard from what I have seen). Here is the implementation of the interface:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    public interface IDisposable
    {
       void Dispose()
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When we first implement the interface on our class, we are given the following code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    public sealed class MyClass : IDisposable
    {
        public void Dispose()
        {
            /* Release resources here */
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;While this implementation is fine if you don't mind waiting for the garbage collector to come and release the resources. What if your class has a large object inside (say ~250mb). Do you really want to wait for the garbage collector? Probably not.&lt;/p&gt;

&lt;p&gt;In order to fix our implementation, we need to do two things. Firstly, we need to implement a &lt;code&gt;Finalizer&lt;/code&gt; and then implement an overload to the original &lt;code&gt;Dispose&lt;/code&gt; method. The reason why we implement a &lt;code&gt;Finalizer&lt;/code&gt; is because we want to safe-guard ourselves if we forget to call the &lt;code&gt;Dispose&lt;/code&gt; method. For those that do not know what a &lt;code&gt;Finalizer&lt;/code&gt; looks like, here it is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    public sealed class MyClass : IDisposable
    {
        public MyClass()
        {
            /* Constructor */
        }

        public ~MyClass()
        {
            /* Destructor */
        }

        public void Dispose()
        {
            /* Release resources here */
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In order to safe-guard ourselves as I just mentioned, our &lt;code&gt;Finalizer&lt;/code&gt; needs to call our &lt;code&gt;Dispose&lt;/code&gt; method like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    public ~MyClass()
    {
        /* Destructor */
        Dispose();
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You may have realised by now that we could, potentially, call the &lt;code&gt;Dispose&lt;/code&gt; twice. The user will call it once followed by the CLR calling it for us in case we forget (through the &lt;code&gt;Finalizer&lt;/code&gt;). This gives us the requirement for the overload of the &lt;code&gt;Dispose&lt;/code&gt; method I mentioned earlier. If &lt;strong&gt;we&lt;/strong&gt; call the &lt;code&gt;Dispose&lt;/code&gt; method then it is &lt;em&gt;safe&lt;/em&gt; for us to release managed resources. However, if the &lt;strong&gt;CLR&lt;/strong&gt; calls the &lt;code&gt;Dispose&lt;/code&gt; method then we cannot safely release managed resources because we do not know their current state.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; The CLR runs on a background thread, which we have no control over. Therefore, we cannot know any objects state on that thread.&lt;/p&gt;

&lt;p&gt;Now that we have identified that the &lt;code&gt;Dispose&lt;/code&gt; method can be called from two places, we can implement this into our code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    public sealed class MyClass : IDisposable
    {
        public MyClass()
        {
            /* Constructor */
        }

        public ~MyClass()
        {
            /* Destructor */
            Dispose(false); // the CLR will call Dispose, so its an unsafe call
        }

        public void Dispose()
        {
            /* The interface implementation */
            Dispose(true); // WE are calling Dispose, so its a safe call
        }

        public void Dispose(bool safeToFreeManagedResources)
        {
            /* Free unmanaged resources */

            if (safeToFreeManagedResources)
            {
                /*  Free managed resources */
            }
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Even though we have told the CLR that we are not to release managed resources twice, we will still release unmanaged resources twice. This is not only wasteful, but you could end up with an exception here which is something that &lt;strong&gt;SHOULD NEVER HAPPEN&lt;/strong&gt;. Luckily for us, the CLR has a neat way for us to tell it not to call the &lt;code&gt;Finalizer&lt;/code&gt; because we have already released all the resources necessary. Here is the one line magic fix:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    public void Dispose()
    {
        /* The interface implementation */
        Dispose(true); // WE are calling Dispose, so its a safe call
        GC.SuppressFinalize(this); // WE have called dispose, there is no need to call it again Mr. GC.
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Best Practise&lt;/h2&gt;

&lt;p&gt;Now that we have our code fixed, without any issues or bugs, it's time to know a best practise. When an object implements the &lt;code&gt;IDisposable&lt;/code&gt; interface, we have the opportunity to use the &lt;code&gt;using&lt;/code&gt; statement. The idea of the &lt;code&gt;using&lt;/code&gt; statement is that once you have finished with the object, the CLR will call the &lt;code&gt;Dispose&lt;/code&gt; method for you. Note I said &lt;code&gt;Dispose&lt;/code&gt; not the &lt;code&gt;Finalizer&lt;/code&gt;. The &lt;code&gt;using&lt;/code&gt; statement is really easy to use:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    static void Main(string[] args)
    {
        using (var myClass = new MyClass())
        {
            /* Do stuff here */
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When the compiler sees this code, it actually expands it to this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    static void Main(string[] args)
    {
        var myClass = new MyClass();
        try
        {
            /* Do stuff here */
        }
        finally
        {
            myClass.Dispose();
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So there it is. Hopefully now you can implement &lt;code&gt;IDisposable&lt;/code&gt; correctly according to your needs.&lt;/p&gt;
</description>
				<pubDate>Mon, 06 May 2013 00:00:00 -0700</pubDate>
				<link>/2013/05/06/Using-IDisposible-correctly</link>
				<guid isPermaLink="true">/2013/05/06/Using-IDisposible-correctly</guid>
			</item>
		
			<item>
				<title>Semaphore vs SemaphoreSlim - A performance benchmark</title>
				<description>&lt;p&gt;In this post, I am going to show a small micro-benchmark to demonstrate the performance difference between the &lt;code&gt;Semaphore&lt;/code&gt; and &lt;code&gt;SemaphoreSlim&lt;/code&gt; classes in C#. A &lt;code&gt;Semaphore&lt;/code&gt; is often used to restrict the number of threads than can access some (physical or logical) resource. In this case, we want the restriction to be as little as possible.&lt;/p&gt;

&lt;p&gt;Semaphores are of two types: local semaphores and named system semaphores. If you create a Semaphore object using a constructor that accepts a name, it is associated with an operating-system semaphore of that name. Named system semaphores are visible throughout the operating system, and can be used to synchronize the activities of processes. You can create multiple Semaphore objects that represent the same named system semaphore, and you can use the OpenExisting method to open an existing named system semaphore. &lt;em&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-gb/library/system.threading.semaphore.aspx&quot;&gt;Source&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;A local semaphore exists only within your process. It can be used by any thread in your process that has a reference to the local Semaphore object. Each Semaphore object is a separate local semaphore. &lt;em&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-gb/library/system.threading.semaphore.aspx&quot;&gt;Source&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The machine that I am using for this benchmark is a Intel core i3, clocked at 4ghz with 4GB DDR3 ram running Windows 7 x64 SP1 and .Net Framework 4.5.&lt;/p&gt;

&lt;p&gt;In order to begin the test, I created a new console application and imported the &lt;a href=&quot;http://sblackler.net/2013/03/11/Introducing-BMark-v1/&quot;&gt;BMark&lt;/a&gt; package from the &lt;a href=&quot;https://nuget.org/packages/BMark/&quot;&gt;NuGet&lt;/a&gt; repository. Next, I added the following code to the application as shown below:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;const Int32 count = 106;

Semaphore regularSemaphore = new Semaphore(count, count);
SemaphoreSlim slimSemaphore = new SemaphoreSlim(count, count);

UInt64 amountToRun = (UInt64)(count - PerformanceTester.PreRunAmount - 2);

PerformanceTester.Run(&quot;Semaphore.WaitOne&quot;, amountToRun, () =&amp;gt; { regularSemaphore.WaitOne(); });
PerformanceTester.Run(&quot;Semaphore.Release&quot;, amountToRun, () =&amp;gt; { regularSemaphore.Release(); });
PerformanceTester.Run(&quot;SemaphoreSlim.WaitOne&quot;, amountToRun, () =&amp;gt; { slimSemaphore.Wait(); });
PerformanceTester.Run(&quot;SemaphoreSlim.Release&quot;, amountToRun, () =&amp;gt; { slimSemaphore.Release(); });

Console.WriteLine(PerformanceTester.GetResults());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;By default, the &lt;code&gt;PerformanceTester&lt;/code&gt; will run each test 4 times before starting the actual timed test. Since we are dealing with a blocking resource, I added some extra capacity so that the test would not block at any point. When the code is run in release mode without the debugger, the output of the program is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Semaphore.WaitOne:         0.09ms    NumberOfSamples: 100
Semaphore.Release:         0.05ms    NumberOfSamples: 100
SemaphoreSlim.WaitOne:     0.01ms    NumberOfSamples: 100
SemaphoreSlim.Release:     0.01ms    NumberOfSamples: 100
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As the results show, the &lt;code&gt;SemaphoreSlim&lt;/code&gt; class is a tiny bit quicker. After testing this myself earlier, I thought that others could run this themselves and hopefully receive a small increase in performance in their applications. The reason for the performance increase is because the &lt;code&gt;SemaphoreSlim&lt;/code&gt; class provides a lightweight alternative to the &lt;code&gt;Semaphore&lt;/code&gt; class that doesn't use Windows kernel semaphores.&lt;/p&gt;

&lt;p&gt;In essence, if you do not need a named &lt;code&gt;Semaphore&lt;/code&gt;, use the &lt;code&gt;SemaphoreSlim&lt;/code&gt; class.&lt;/p&gt;
</description>
				<pubDate>Mon, 11 Mar 2013 00:00:00 -0700</pubDate>
				<link>/2013/03/11/Semaphore-vs-SeamphoreSlim-Micro-Benchmark</link>
				<guid isPermaLink="true">/2013/03/11/Semaphore-vs-SeamphoreSlim-Micro-Benchmark</guid>
			</item>
		
			<item>
				<title>Introducing BMark Version 0.1 - A .Net Micro-Benchmarking package</title>
				<description>&lt;p&gt;This post is dedicated to the release of a small utility class that I have just released on &lt;a href=&quot;https://nuget.org/packages/BMark/&quot;&gt;NuGet&lt;/a&gt;. The aim of BMark is to provide a simple way of running multiple microbenchmarks. This is my first ever NuGet package so there is a chance that I have done something wrong. Please notify me ASAP if you do notice anything and I will sort it out when I can.&lt;/p&gt;

&lt;h2&gt;Using BMark&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;In order to use BMark, please make sure that you have NuGet package manager installed, or download the code from the &lt;a href=&quot;https://github.com/sblackler/BMark&quot;&gt;GitHub Project Page&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If you are using the NuGet package manager to install packages, simply search for &lt;code&gt;BMark&lt;/code&gt; in the online sources and click install.&lt;/p&gt;

&lt;p&gt;Or, if you prefer to use the NuGet package console, simply type in the following command:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Install-Package BMark
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now you are ready to run some benchmarks. The core method &lt;code&gt;Run&lt;/code&gt; has three parameters which are the test name, the amount of times to run the test and the actual code to test. Here is a quick demonstration from a future blog post:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;PerformanceTester.Run(&quot;SemaphoreSlim.Release&quot;, amountToRun, () =&amp;gt; { slimSemaphore.Release(); });

Console.WriteLine(PerformanceTester.GetResults());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It's as easy as that. Feel free to contribute any modifications to the &lt;a href=&quot;https://github.com/sblackler/BMark&quot;&gt;GitHub Project Page&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Happy benchmarking&lt;/p&gt;
</description>
				<pubDate>Mon, 11 Mar 2013 00:00:00 -0700</pubDate>
				<link>/2013/03/11/Introducing-BMark-v1</link>
				<guid isPermaLink="true">/2013/03/11/Introducing-BMark-v1</guid>
			</item>
		
			<item>
				<title>Implementing The Observer Pattern</title>
				<description>&lt;p&gt;The observer pattern is a way of defining a one-to-many relationship between two classes. Typically the pattern is used to provide push based notifications of changes from the observed subject to the subscribed listeners, much like you receive notifications on a mobile phone.&lt;/p&gt;

&lt;p&gt;For this pattern we need to two interfaces which classes will implement. First of all, we have &lt;code&gt;IObservable&lt;/code&gt; which, when implemented, is going to push any changes to the observers. Secondly, we have &lt;code&gt;IObserver&lt;/code&gt; which, when implemented, is going to listen to the &lt;code&gt;IObservable&lt;/code&gt; instance for changes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; &lt;em&gt;I have made everything in this post as generic as possible with the aim of ease of use for you, dear reader.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;IObservable&amp;lt;T&amp;gt;&lt;/h2&gt;

&lt;p&gt;This interface needs to define a subscribe method and optionally an unsubscribe method, such as this Java implementation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface IObservable&amp;lt;T&amp;gt; {
    void subscribe(IObserver&amp;lt;T&amp;gt; observer);
    void unsubscribe(IObserver&amp;lt;T&amp;gt; observer);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;IObserver&amp;lt;T&amp;gt;&lt;/h2&gt;

&lt;p&gt;This interface needs to define a method from which the &lt;code&gt;IObservable&lt;/code&gt; instance can call when it detects a change. A typical example, taken from the .Net implementation, is to define an &lt;code&gt;onNext&lt;/code&gt; method such as this implementation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface IObserver&amp;lt;T&amp;gt; {
    void onNext(T value);
    void onCompleted();
    void onError(Exception e);      
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;onNext&lt;/code&gt; method takes the value added/changed in the &lt;code&gt;IObservable&lt;/code&gt; instance. I have also defined two additional methods for when an error is raised and when the observer should complete its work. This interface is already defined for .Net programmers.&lt;/p&gt;

&lt;h2&gt;The Headmaster Example&lt;/h2&gt;

&lt;p&gt;I am going to briefly show a full implementation using a school classroom. In this example, we are simply going to watch a &lt;code&gt;Lesson&lt;/code&gt; for any pupils enrolling onto the lesson and write their names to the console window. To make this clear, the example is in Java.&lt;/p&gt;

&lt;p&gt;To start off with, I am going to define an immutable (an object whose state cannot be modified after it is created) &lt;code&gt;Pupil&lt;/code&gt; class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Pupil {

    private String _name;
    private int _age;

    public Pupil(String name, int age)
    {
        _name = name;
        _age = age;
    }

    public String getName()
    {
        return _name;
    }

    public int getAge()
    {
        return _age;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Next, I am going to implement a &lt;code&gt;Lesson&lt;/code&gt; class that implements &lt;code&gt;IObservable&lt;/code&gt; of the type &lt;code&gt;Pupil&lt;/code&gt;. If the concepts of generics confuses you, don't worry, I will explain this in a future post.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import java.util.ArrayList;
import java.util.List;

public class Lesson implements IObservable&amp;lt;Pupil&amp;gt; {

    List&amp;lt;IObserver&amp;lt;Pupil&amp;gt;&amp;gt; _subscribers = new ArrayList&amp;lt;IObserver&amp;lt;Pupil&amp;gt;&amp;gt;();

    @Override
    public void subscribe(IObserver&amp;lt;Pupil&amp;gt; observer) {
        // check the argument
        if(observer != null)
        {
            _subscribers.add(observer);
        }
        // if the argument is null throw the exception or something
    }

    @Override
    public void unsubscribe(IObserver&amp;lt;Pupil&amp;gt; observer) {
        // check the argument
        if(observer != null)
        {
            _subscribers.remove(observer);
        }
        // if the argument is null throw the exception or something
    }

    public void enrollPupil(Pupil p)
    {
        // do something with p here...
        for(IObserver&amp;lt;Pupil&amp;gt; observer : _subscribers)
        {
            // Notify the subscribers of the new pupil
            observer.onNext(p);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see from the implementation above, in order to implement &lt;code&gt;IObservable&lt;/code&gt; properly, we need to have a way of maintaining a collection of objects that are subscribed to changes. The easiest way of doing this is through a list as shown above. The &lt;code&gt;subscribe&lt;/code&gt; method adds to the list while the &lt;code&gt;unsubscribe&lt;/code&gt; method removes it from the list. When the &lt;code&gt;enrollPupil&lt;/code&gt; method is called, we perform an action with the &lt;code&gt;Pupil&lt;/code&gt; before iterating through the list and letting each observer know of the change.&lt;/p&gt;

&lt;p&gt;Penultimately, we need to implement the &lt;code&gt;IObserver&lt;/code&gt; interface in the form of a &lt;code&gt;LessonObserver&lt;/code&gt;. This is implemented as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class LessonObserver implements IObserver&amp;lt;Pupil&amp;gt; {
    @Override
    public void onNext(Pupil value) {
        System.out.println(value.getName() + &quot; has enrolled on the course.&quot;);
    }

    @Override
    public void onCompleted() {
        // This is fired when we stop listening
    }

    @Override
    public void onError(Exception e) {
        // This is fired when an error occurs (if the Observable throws it to us)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Lastly, we just need a simple way of testing the application which I have done for you:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Driver {
    public static void main(String[] args)
    {
        // create the objects
        Lesson l = new Lesson();
        LessonObserver lo = new LessonObserver();

        // subscribe to notifications
        l.subscribe(lo);

        // add some dummy data
        l.enrollPupil(new Pupil(&quot;Stueh&quot;, 18));
        l.enrollPupil(new Pupil(&quot;Jon&quot;, 18));
        l.enrollPupil(new Pupil(&quot;Kirsty&quot;, 18));

        // unsubscribe to finish off
        l.unsubscribe(lo);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;All being well you should end up with the following output in your console window:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Stueh has enrolled on the course.
Jon has enrolled on the course.
Kirsty has enrolled on the course.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I hope that you now understand how simple the observer pattern is and how it can be useful.&lt;/p&gt;
</description>
				<pubDate>Thu, 07 Mar 2013 00:00:00 -0800</pubDate>
				<link>/2013/03/07/The-Observer-Pattern-In-CSharp-and-Java</link>
				<guid isPermaLink="true">/2013/03/07/The-Observer-Pattern-In-CSharp-and-Java</guid>
			</item>
		
			<item>
				<title>System Databases and Backups</title>
				<description>&lt;p&gt;In this post I am going to talk a little bit about the system databases, what they are used for and provide a few additional resources should you be interested in reading more about each database.&lt;/p&gt;

&lt;h2&gt;Master&lt;/h2&gt;

&lt;p&gt;The name of this database gives away its true purpose. It is the &lt;em&gt;master&lt;/em&gt; database for SQL Server. It is responsible for the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Instance wide metadata;&lt;/li&gt;
&lt;li&gt;Server configuration;&lt;/li&gt;
&lt;li&gt;Initialisation information; and&lt;/li&gt;
&lt;li&gt;Information about all databases in the instance.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;Because of the reasons specified above, the &lt;em&gt;master&lt;/em&gt; database is very important to SQL Server. Therefore, it is extremely important that you backup the &lt;em&gt;master&lt;/em&gt; regularly in the event that the &lt;em&gt;master&lt;/em&gt; database becomes corrupted.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://blog.sqlauthority.com/2009/02/15/sql-server-reasons-to-backup-master-database-why-should-master-database-backedup/&quot;&gt;Reasons to Backup Master Database – Why Should Master Database Backed up&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://blog.sqlauthority.com/2009/08/12/sql-server-backup-master-database-interval-master-database-best-practices/&quot;&gt;Backup master Database interval&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;MSDB&lt;/h2&gt;

&lt;p&gt;The &lt;em&gt;msdb&lt;/em&gt; database stores configuration data for a number of resources including but not limited to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;SQL Server Agent&lt;/li&gt;
&lt;li&gt;Database Mail&lt;/li&gt;
&lt;li&gt;Service Broker&lt;/li&gt;
&lt;li&gt;Backups&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;As this database contains alot of configuration data, it is vital that this database is backed up alongside the &lt;em&gt;master&lt;/em&gt; database. Simply backup this database when ever a configuration change is made to one of the above services.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://technet.microsoft.com/en-us/library/ms188274.aspx&quot;&gt;Considerations for Backing Up the model and msdb Databases&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms190749.aspx&quot;&gt;Considerations for Restoring the model and msdb Databases&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;Model&lt;/h2&gt;

&lt;p&gt;As the name suggests, the &lt;em&gt;model&lt;/em&gt; database is used as a template for every database that you create. For example, if you want a series of stored procedures in every database you create on the system from now on, you create the scripts in &lt;em&gt;model&lt;/em&gt;. It is not just limited to stored procedures though, other SQL objects such as custom data types can also be created inside of &lt;em&gt;model&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Depending on your businesses needs, this is also a vital database to backup as it may contain some code that should not be lost. As the database is small, Microsoft recommend creating a full database backup with backing up the log file deemed unnecessary.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://technet.microsoft.com/en-us/library/ms188274.aspx&quot;&gt;Considerations for Backing Up the model and msdb Databases&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms190749.aspx&quot;&gt;Considerations for Restoring the model and msdb Databases&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;Resource&lt;/h2&gt;

&lt;p&gt;The &lt;em&gt;resource&lt;/em&gt; database is a special database. For starters, it is read-only and hidden which would explain why we never see it in list of databases in SSMS. The purpose of this database is to hold the definitions of all system objects.&lt;/p&gt;

&lt;p&gt;When querying against a user database, it appears that the &lt;code&gt;sys&lt;/code&gt; schema belongs to the user database. In fact, the definitions of all &lt;code&gt;sys&lt;/code&gt; objects are held inside of the &lt;em&gt;resource&lt;/em&gt; database.&lt;/p&gt;

&lt;h2&gt;TempDB&lt;/h2&gt;

&lt;p&gt;The tempdb system database is a global resource that has been used since
the inception of SQL Server. It is available to all SQL Server users
connected to the SQL Server instance. It holds many types of data and
can often be the source of a performance bottleneck.&lt;/p&gt;

&lt;p&gt;For example, tempdb can hold the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Temporary user objects that are explicitly created, such as: global
or local temporary tables, temporary stored procedures, table
variables, or cursors.&lt;/li&gt;
&lt;li&gt;Internal objects that are created by the SQL Server Database Engine,
for example, work tables to store intermediate results for spools or
sorting&lt;/li&gt;
&lt;li&gt;Row versions that are generated by data modification transactions in
a database that uses read-committed using row versioning isolation
or snapshot isolation transactions&lt;/li&gt;
&lt;li&gt;Row versions that are generated by data modification transactions
for features, such as: online index operations, Multiple Active
Result Sets (MARS), and AFTER triggers&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;For more information about how you know whether &lt;em&gt;tempdb&lt;/em&gt; is a problem for your system, read a few of the following articles:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://sblackler.net/2012/06/15/tempdb-health-check-queries/&quot;&gt;TempDB Health Check Queries&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms190768.aspx&quot;&gt;TempDB
(MSDN)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.brentozar.com/archive/2012/12/bob-dylan-explains-tempdb-video/&quot;&gt;Bob Dylan Explains TempDB&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;Distribution&lt;/h2&gt;

&lt;p&gt;The &lt;em&gt;distribution&lt;/em&gt; database is not always created on a SQL server instance. This is because it has the important role of storing metadata and history data for all types of replication and transactions for transactional replication.&lt;/p&gt;

&lt;p&gt;Only when the server is configured as a distributor, link at the end of this section, is the database created. Because of the data stored in the &lt;em&gt;distribution&lt;/em&gt; database, Microsoft recommend that this database is backed up in the event of a disaster to the distribution instance.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://technet.microsoft.com/en-us/library/ms152531.aspx&quot;&gt;Types of Replication&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-gb/library/ms151860.aspx&quot;&gt;Configuring Distribution DB&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-gb/library/ms151152.aspx&quot;&gt;Backup and Restore Replicated Databases&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;Backups&lt;/h2&gt;

&lt;p&gt;As I have mentioned in the article so far, it is important to backup the system databases. Luckily, there is an excellent guide on MSDN for &lt;a href=&quot;http://msdn.microsoft.com/en-gb/library/ms190190.aspx&quot;&gt;backing up our system databases&lt;/a&gt;. This guide covers what recovery options can be used and the implications as well. &lt;a href=&quot;http://msdn.microsoft.com/en-gb/library/ms189272.aspx&quot;&gt;This guide&lt;/a&gt; will provide you information on how to view or change your recovery model for a specific database, should you need the reminder.&lt;/p&gt;

&lt;p&gt;Hopefully that gives you a quick oversight on what each database is used for and resources to continue exploration if you would like to.&lt;/p&gt;
</description>
				<pubDate>Fri, 25 Jan 2013 00:00:00 -0800</pubDate>
				<link>/2013/01/25/System-Databases-and-Backups</link>
				<guid isPermaLink="true">/2013/01/25/System-Databases-and-Backups</guid>
			</item>
		
			<item>
				<title>SQL Server - Notes on SARGability</title>
				<description>&lt;p&gt;Sargabliity is a term used to describe whether or not a query can leverage existing indexes in order to speed up query execution. SARGABLE means Search ARGument ABLE.&lt;/p&gt;

&lt;p&gt;Commonly, new or inexperienced SQL developers will often write queries such as:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT col1, col2 FROM myTable WHERE YEAR(col3) &amp;gt;= 2008
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;While this is perfectly valid SQL, having the function &lt;code&gt;YEAR()&lt;/code&gt;  on the left hand side of the condition will cause SQL Server to evaluate every single row of the table. This is fine for a small table but for a large table and multiple users, this approach will not scale very well at all as it will consume too many resources.&lt;/p&gt;

&lt;p&gt;In essence, if you ask the database server to manipulate the data in order to get the results, you will suffer a performance impact and reduce your ability to scale. Now we know this, we can re-write the query to perform a lot better:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT col1, col2 FROM myTable WHERE col3 &amp;gt;= '2008-01-01 00:00:00'
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With our new query above, we can leverage our fictious index on &lt;code&gt;col3&lt;/code&gt; to quickly search and return all the results. This approach is much like you would go through a phonebook. You would not search through the phonebook, looking at every name to see whether they started with the letter S. Instead, you know that the phonebook is split into sections (much like our index in our database) so you can jump straight to the section that begins with S and begin searching from there. This is what we have just told SQL Server to do with a minor modification of our query.&lt;/p&gt;

&lt;h2&gt;Matching your data types&lt;/h2&gt;

&lt;p&gt;By matching the data types in your &lt;code&gt;WHERE&lt;/code&gt; statements you avoid implicit conversions (automatic conversions). There are two main reasons that we want to avoid implicit conversions:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It is an extra operation that we potentially don't need&lt;/li&gt;
&lt;li&gt;If the conversion is on the side of the data table, it will evaluate the conversion for every row in the table which is &lt;strong&gt;SLOW&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;Which side of the evaluation expression the conversion happens on depends on the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms190309.aspx&quot;&gt;order of precedence&lt;/a&gt;. It is important to note the following from the article linked:&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;When an operator combines two expressions of different data types, the rules for data type precedence specify that the data type with the lower precedence is converted to the data type with the higher precedence. If the conversion is not a supported implicit conversion, an error is returned.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;&lt;a href=&quot;http://sqlblog.com/blogs/tibor_karaszi/&quot;&gt;Tibor Karaszi&lt;/a&gt; has a detailed post on the subject here: &lt;a href=&quot;http://sqlblog.com/blogs/tibor_karaszi/archive/2009/04/28/match-those-types.aspx&quot;&gt;Match Those Types&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;Finding implicit conversions in the QPC&lt;/h2&gt;

&lt;p&gt;Jonathon Kehayias (&lt;a href=&quot;http://sqlblog.com/blogs/jonathan_kehayias/&quot;&gt;blog&lt;/a&gt;) has a great query to find queries that have implicate conversions that exist in the query plan cache. I have included the query below as a point-in-time snapshot of the query, but please check &lt;a href=&quot;http://sqlblog.com/blogs/jonathan_kehayias/archive/2010/01/08/finding-implicit-column-conversions-in-the-plan-cache.aspx&quot;&gt;the original&lt;/a&gt; link for updated versions of the query and additional comments.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 

DECLARE @dbname SYSNAME 
SET @dbname = QUOTENAME(DB_NAME()); 

WITH XMLNAMESPACES 
   (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan') 
SELECT 
   stmt.value('(@StatementText)[1]', 'varchar(max)'), 
   t.value('(ScalarOperator/Identifier/ColumnReference/@Schema)[1]', 'varchar(128)'), 
   t.value('(ScalarOperator/Identifier/ColumnReference/@Table)[1]', 'varchar(128)'), 
   t.value('(ScalarOperator/Identifier/ColumnReference/@Column)[1]', 'varchar(128)'), 
   ic.DATA_TYPE AS ConvertFrom, 
   ic.CHARACTER_MAXIMUM_LENGTH AS ConvertFromLength, 
   t.value('(@DataType)[1]', 'varchar(128)') AS ConvertTo, 
   t.value('(@Length)[1]', 'int') AS ConvertToLength, 
   query_plan 
FROM sys.dm_exec_cached_plans AS cp 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
CROSS APPLY query_plan.nodes('/ShowPlanXML/BatchSequence/Batch/Statements/StmtSimple') AS batch(stmt) 
CROSS APPLY stmt.nodes('.//Convert[@Implicit=&quot;1&quot;]') AS n(t) 
JOIN INFORMATION_SCHEMA.COLUMNS AS ic 
   ON QUOTENAME(ic.TABLE_SCHEMA) = t.value('(ScalarOperator/Identifier/ColumnReference/@Schema)[1]', 'varchar(128)') 
   AND QUOTENAME(ic.TABLE_NAME) = t.value('(ScalarOperator/Identifier/ColumnReference/@Table)[1]', 'varchar(128)') 
   AND ic.COLUMN_NAME = t.value('(ScalarOperator/Identifier/ColumnReference/@Column)[1]', 'varchar(128)') 
WHERE t.exist('ScalarOperator/Identifier/ColumnReference[@Database=sql:variable(&quot;@dbname&quot;)][@Schema!=&quot;[sys]&quot;]') = 1
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Invertability&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;http://sqlblog.com/blogs/rob_farley&quot;&gt;Rob Farley&lt;/a&gt; has an &lt;a href=&quot;http://sqlblog.com/blogs/rob_farley/archive/2010/11/09/inverse-predicates-look-both-ways-before-you-cross.aspx&quot;&gt;excellent article&lt;/a&gt; on inverting the search predicates. I thought this is a must read and a technique that we could apply to our own development.&lt;/p&gt;

&lt;h2&gt;For the unavoidable situations&lt;/h2&gt;

&lt;p&gt;Sometimes you need to break the guidelines of SARGABILITY for various reasons. But there are ways in which you can still improve the performance of your queries. For instance, you can use an indexed view or a computed column.&lt;/p&gt;

&lt;p&gt;Remember these are only guidelines. Test, test and test some more for your specific scenario.&lt;/p&gt;

&lt;h2&gt;The Big 3&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Try to leave the manipulation of the data in the table alone where you can&lt;/li&gt;
&lt;li&gt;If you can not effectively do #1 explore other avenues such as computed columns or indexed views&lt;/li&gt;
&lt;li&gt;Make sure you know the data types in your system in order to avoid implicit conversions&lt;/li&gt;
&lt;/ol&gt;


&lt;h2&gt;Further Reading&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://sqlbits.com/Sessions/Event7/Understanding_SARGability_to_make_your_queries_run_faster&quot;&gt;Understanding SARGability (to make your queries run faster)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://msmvps.com/blogs/robfarley/archive/2010/01/22/sargable-functions-in-sql-server.aspx&quot;&gt;SARGable functions in SQL Server&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.brentozar.com/archive/2010/06/sargable-why-string-is-slow/&quot;&gt;Sargability: Why %string% Is Slow&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://sqlblog.com/blogs/rob_farley/archive/2010/02/02/a-case-study-in-sargability.aspx&quot;&gt;A CASE study in SARGability&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
				<pubDate>Thu, 13 Dec 2012 00:00:00 -0800</pubDate>
				<link>/2012/12/13/Notes-on-Sargability</link>
				<guid isPermaLink="true">/2012/12/13/Notes-on-Sargability</guid>
			</item>
		
			<item>
				<title>DELETE vs TRUNCATE</title>
				<description>&lt;p&gt;In this post, I continue my beginners series by looking at the difference between delete and truncate. As a developer it is an important to recognise the differences between the two and how they affect the recovery options you have should an error occur or a malicious user enters your system.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Like my previous posts, this information is specific to MSSQL but the concepts are similar in other RDBMS'.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;DELETE&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;DELETE&lt;/code&gt; keyword is the most common form of deletion that you will see in most environments. The basic syntax looks like the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;DELETE FROM &amp;lt;table&amp;gt; [WHERE &amp;lt;some boolean condition&amp;gt;]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As the keyword &lt;code&gt;DELETE&lt;/code&gt; suggests, running this query against a relational database engine will delete the specified rows from the table. &lt;code&gt;DELETE&lt;/code&gt; effectively has two main modes of operation. Delete everything or delete specific rows.&lt;/p&gt;

&lt;p&gt;In order to delete specific values from a given table, the &lt;code&gt;WHERE&lt;/code&gt; clause must be specified. The &lt;code&gt;WHERE&lt;/code&gt; clause is exactly the same as the &lt;code&gt;WHERE&lt;/code&gt; clause for any &lt;code&gt;SELECT&lt;/code&gt; statement. If the &lt;code&gt;WHERE&lt;/code&gt; clause is not specified, the &lt;code&gt;DELETE&lt;/code&gt; reverts back to its delete everything mode of operation. Depending on the amount of rows being deleted, and the recovery scenario needed, &lt;code&gt;TRUNCATE&lt;/code&gt; may be a better option for your query, more on this later.&lt;/p&gt;

&lt;p&gt;As a best practise of mine, I always write my queries as a &lt;code&gt;SELECT&lt;/code&gt; statement first. There are many reasons for doing/not doing this but my reasoning is simple. I want to test that my &lt;code&gt;WHERE&lt;/code&gt; clauses functioned as I intended. By looking at the results from the &lt;code&gt;SELECT&lt;/code&gt; statement, I can tell whether or not the &lt;code&gt;DELETE&lt;/code&gt; will function correctly.&lt;/p&gt;

&lt;h2&gt;TRUNCATE&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;TRUNCATE&lt;/code&gt; keyword is rarely used in production environments purely for the main reason being that it is &lt;strong&gt;VERY DANGEROUS&lt;/strong&gt;. Maximum caution is advised. &lt;code&gt;TRUNCATE&lt;/code&gt; only has one mode of operation, delete everything. The syntax for truncating a table looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; TRUNCATE &amp;lt;table name&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As I said before, this will delete everything. But there are a number of reasons why you would choose to truncate over delete with the main reason being efficiency.&lt;/p&gt;

&lt;h2&gt;The Internals&lt;/h2&gt;

&lt;p&gt; &lt;em&gt;Warning: Information in this section is likely to be very MSSQL specific and advanced in nature&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;To understand why &lt;code&gt;TRUNCATE&lt;/code&gt; is more efficient than &lt;code&gt;DELETE&lt;/code&gt;, you need to understand the internals how the two types of query work.&lt;/p&gt;

&lt;h3&gt;DELETE&lt;/h3&gt;

&lt;p&gt;When the database engine is asked to delete from a table, the database engine finds and removes the row from the relevant data pages and all index pages where the row is entered and adds an entry to the log file. The process of going through each index involves &lt;code&gt;SEEK&lt;/code&gt; operations as opposed to &lt;code&gt;SCAN&lt;/code&gt; operations (for better performance).&lt;/p&gt;

&lt;p&gt;In essence, the more indexes you have on your table, then longer your &lt;code&gt;DELETE&lt;/code&gt; statements will take. The same principal applies to &lt;code&gt;INSERT&lt;/code&gt; and &lt;code&gt;UPDATE&lt;/code&gt; statements.&lt;/p&gt;

&lt;p&gt;Depending on what recovery mode you have selected will depend on the information stored in the log file. However, all deletes are logged in the log file, it is just the information in the log file that changes. The log file stores the data in hexidecimal format and will need to be converted before any potential data recovery.&lt;/p&gt;

&lt;h3&gt;TRUNCATE&lt;/h3&gt;

&lt;p&gt;When the database engine is asked to &lt;code&gt;TRUNCATE&lt;/code&gt; a table, it simply removes all the table's data pages en mass. If the statement is encapsulated in a transaction then a &lt;code&gt;TRUNCATE&lt;/code&gt; operation has the potential to be rolled back.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;TRUNCATE&lt;/code&gt; is more efficient than &lt;code&gt;DELETE&lt;/code&gt;'s because:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Fewer locks may be needed. Truncation typically requires only a single schema modification lock at the table level (and exclusive locks on each &lt;em&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms190969.aspx&quot;&gt;extent&lt;/a&gt;&lt;/em&gt; deallocated). Deletion might acquire locks at a lower (row or page) granularity as well as exclusive locks on any pages deallocated.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Only truncation guarantees that all pages are deallocated from a heap table. Deletion may leave empty pages in a heap even if an exclusive table lock hint is specified (for example if a row-versioning isolation level is enabled for the database).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Truncation is &lt;a href=&quot;http://technet.microsoft.com/en-us/magazine/gg552991.aspx&quot;&gt;always minimally logged&lt;/a&gt; (regardless of the recovery model in use). Only page deallocation operations are recorded in the transaction log.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Truncation can use &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms177495.aspx&quot;&gt;deferred drop&lt;/a&gt; if the object is 128 extents or larger in size. Deferred drop means the actual deallocation work is performed asynchronously by a background server thread.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;


&lt;h2&gt;Replication&lt;/h2&gt;

&lt;p&gt;The main difference between &lt;code&gt;DELETE&lt;/code&gt; and &lt;code&gt;TRUNCATE&lt;/code&gt; in terms of replication is that Truncation is &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms177570.aspx&quot;&gt;not allowed&lt;/a&gt; on a table that is published using transactional or merge replication.  How deletions are replicated depends on the type of replication and how it is configured. For example, snapshot replication just replicates a point-in-time view of the table using bulk methods - incremental changes are not tracked or applied. Transactional replication works by reading log records and generating appropriate transactions to apply the changes at subscribers. Merge replication tracks changes using triggers and metadata tables.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;- Credit to SQLKiwi for &lt;a href=&quot;http://dba.stackexchange.com/a/30347/2334&quot;&gt;his answer&lt;/a&gt; on DBA.SE which explains more about the internals of the &lt;code&gt;DELETE&lt;/code&gt; and &lt;code&gt;TRUNCATE&lt;/code&gt; operations. I advise reading this and the links in the comments also. Here is Paul's &lt;a href=&quot;http://sqlblog.com/blogs/paul_white/default.aspx&quot;&gt;Blog&lt;/a&gt; &amp;amp; &lt;a href=&quot;https://twitter.com/SQL_Kiwi&quot;&gt;Twitter&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</description>
				<pubDate>Thu, 13 Dec 2012 00:00:00 -0800</pubDate>
				<link>/2012/12/13/Delete-vs-truncate</link>
				<guid isPermaLink="true">/2012/12/13/Delete-vs-truncate</guid>
			</item>
		
			<item>
				<title>SQL Joins for Beginners</title>
				<description>&lt;p&gt;In this post I am going to focus on JOINs in SQL which is primarily aimed at beginners. I will also cover typical scenarios when you would use each type of join starting with an INNER JOIN.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This information has only been tested on SQL Server 2012, but the queries should easily transfer to Oracle and MySQL with very little modification. The only bit you may have to modify is the &lt;code&gt;CREATE TABLE&lt;/code&gt; statements in the sql fiddle's provided in the article.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;INNER JOIN&lt;/h2&gt;

&lt;p&gt;An INNER JOIN is one of the joins that I commonly use. The purpose of the join is to take the records from both tables where the join condition is met. For example, imagine that you have the following tables&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Table A&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;id      value
------------
 1      stuart
 2      sophia
 3      victoria
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Table B&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;id      value
------------
 2      sophia
 3      victoria
 4      andy
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If we join the two tables on the &lt;code&gt;name&lt;/code&gt; field we should expect to get sophia and victoria as our results as they exist in both tables. The following &lt;a href=&quot;http://sqlfiddle.com/#!6/c6709/2&quot;&gt;query&lt;/a&gt; demonstrates this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT *
FROM tableA
INNER JOIN tableB ON tableA.value = tableB.value
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We get the following output:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;| ID |    VALUE |
-----------------
|  2 | sophia |
|  3 | victoria |
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The results for stuart and andy are not included as part of the results because they do not exist in the other table. For either one of them to be returned in the results, they would need a corresponding record in the other table.&lt;/p&gt;

&lt;h2&gt;LEFT/RIGHT (OUTER) JOIN&lt;/h2&gt;

&lt;p&gt;If we want to pull all of the results from one of the tables but not all of the results from the other table, we can use a LEFT/RIGHT join. Using the same tables as before, I want to pull all the results from TableA and only those records in TableB where it has a corresponding record in TableA. So I modify my query to be the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT *
FROM tableA
LEFT JOIN tableB ON tableA.value = tableB.value
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;What I am expecting from this query is the rows for stuart, sophia and victoria to be returned. We can test this in the following &lt;a href=&quot;http://sqlfiddle.com/#!6/775bd/1&quot;&gt;query&lt;/a&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;| ID |    VALUE |
-----------------
|  1 |   stuart |
|  2 | sophia |
|  3 | victoria |
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;One thing that you may have noticed is that in the title for this section I included &lt;code&gt;OUTER&lt;/code&gt; in brackets. This is because the &lt;code&gt;OUTER&lt;/code&gt; keyword is optional for LEFT/RIGHT/FULL joins. So to make this clear, &lt;code&gt;LEFT JOIN&lt;/code&gt; is the exact same as &lt;code&gt;LEFT OUTER JOIN&lt;/code&gt;. I always omit the &lt;code&gt;OUTER&lt;/code&gt; keyword to save on the amount that I have to type, as do most SQL professionals.&lt;/p&gt;

&lt;p&gt;If we want all the rows from TableB and only the matching rows from TableA then we can modify the original query to look like the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT *
FROM tableA
RIGHT JOIN tableB ON tableA.value = tableB.value
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;FULL (OUTER) JOIN&lt;/h2&gt;

&lt;p&gt;A FULL JOIN is not one that you commonly see in beginner examples. This type of join returns both tables but any results that do not match the join condition will be replaced with &lt;code&gt;NULL&lt;/code&gt;. Put simpley, one way to think of a FULL JOIN is that is effectively a LEFT JOIN and a RIGHT JOIN merged together.  So if we modify our original query we should see all the rows returned, a total of four rows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;|     ID |    VALUE |
---------------------
|      1 |   stuart |
|      2 | sophia |
|      3 | victoria |
| (null) |   (null) |
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this you will notice the last record is &lt;code&gt;NULL&lt;/code&gt;. This is because the &lt;code&gt;NULL&lt;/code&gt; record appears in TableB but not TableA. If we swapped TableA and TableB in our query, we would see the following result:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;|     ID |    VALUE |
---------------------
|      2 | sophia |
|      3 | victoria |
|      4 |     andy |
| (null) |   (null) |
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To test this out for yourself click &lt;a href=&quot;http://sqlfiddle.com/#!6/d99ca/1&quot;&gt;this link&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;CROSS JOIN&lt;/h2&gt;

&lt;p&gt;With a CROSS JOIN every row from TableA will be matched to every row of TableB. So if you had 5 rows in each table, the result would contain 25 rows (TableA's rows x TableB's rows). The result of the join is known as a Cartesian product. Unlike the other types of join that we have seen so far, a CROSS JOIN does not have a join condition (so it misses of the &lt;code&gt;on x = y&lt;/code&gt; part of the query). We can test this by modifying our query to:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT *
FROM tableA
CROSS JOIN tableB
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which gives us the following result:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;| ID |    VALUE |
-----------------
|  1 |   stuart |
|  2 | sophia |
|  3 | victoria |
|  1 |   stuart |
|  2 | sophia |
|  3 | victoria |
|  1 |   stuart |
|  2 | sophia |
|  3 | victoria |
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you would like to experiment with this more, use &lt;a href=&quot;http://sqlfiddle.com/#!6/d99ca/8&quot;&gt;this sql fiddle&lt;/a&gt;. In fact Cartesian products are formed for more than just CROSS JOIN's. I will go into detail on this in a later blog post.&lt;/p&gt;

&lt;p&gt;It is also possible to use a technique called &lt;code&gt;SELF JOINING&lt;/code&gt;, in which you would join say TableA to TableA. In other words you create a INNER/OUTER join to the same table. There are a few reasons why you would do this, which I will cover in a future blog post if necessary.&lt;/p&gt;

&lt;p&gt;Hopefully this will give the beginners a starting point to learn the basics of joins. I am going to add a few pictures in a few days to help explain for those who learn visually. Please do experiment with the code given in the article, it is honestly the best way of learning the concepts. If you have any feedback to give, please leave a comment or drop me an email.&lt;/p&gt;
</description>
				<pubDate>Fri, 30 Nov 2012 00:00:00 -0800</pubDate>
				<link>/2012/11/30/SQL-Joins-Beginners</link>
				<guid isPermaLink="true">/2012/11/30/SQL-Joins-Beginners</guid>
			</item>
		
			<item>
				<title>Website Update - Almost there now</title>
				<description>&lt;p&gt;Welcome to my newly updated website. In this post I am going to talk a little bit about the tools that I used to develop the website and the intuition behind it.&lt;/p&gt;

&lt;p&gt;The reason behind the update can be attributed to the following reasons:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;the old design dated very fast and was not flexible at all&lt;/li&gt;
&lt;li&gt;I wanted to remove the dependency on &lt;a href=&quot;https://posterous.com/&quot;&gt;posterous&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;I wanted to write my content in markdown&lt;/li&gt;
&lt;li&gt;the performance of the was not what I desired ( &gt; 1 second load time)&lt;/li&gt;
&lt;li&gt;I wanted to add more semantic markup to help google index my content more effectively&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;The first step in my update process was to get a new, professional looking design in place. The result is what you are currently looking at. Overall, I am happy with the redesign as I focused on removing the clutter from the screen and making the text readability better.&lt;/p&gt;

&lt;p&gt;The next step was too remove the dependency on &lt;a href=&quot;https://posterous.com/&quot;&gt;posterous&lt;/a&gt;. Whilst &lt;a href=&quot;https://posterous.com/&quot;&gt;posterous&lt;/a&gt; is a good platform for bloggers to get started with, the end result is horribly slow and the markup less than ideal. During my research, I found &lt;a href=&quot;http://pages.github.com/&quot; title=&quot;GitHub Pages&quot;&gt;GitHub Pages&lt;/a&gt;. &lt;a href=&quot;http://pages.github.com/&quot; title=&quot;GitHub Pages&quot;&gt;GitHub Pages&lt;/a&gt; uses the &lt;a href=&quot;https://github.com/mojombo/jekyll&quot; title=&quot;Jekyll&quot;&gt;Jekyll&lt;/a&gt; static site generator and is compatible with the markdown format. By only serving static pages the performance of my website is going to improve dramatically. It also gives me complete control over the urls with &lt;a href=&quot;https://github.com/mojombo/jekyll&quot; title=&quot;Jekyll&quot;&gt;Jekyll&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;To further help improve performance I reduced the amount of images being loaded using a technique known as CSS sprites which I will cover in a future post. I also removed the JQuery dependency to reduce my technical debt and improve perceived performance. The tools that I used to help me redesign the site are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://cleancss.com/&quot; title=&quot;Clean CSS&quot;&gt;CleanCSS&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://code52.org/DownmarkerWPF/&quot; title=&quot;Markpad Download&quot;&gt;Markpad&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://notepad-plus-plus.org/&quot; title=&quot;Notepad ++ Download&quot;&gt;Notepad++&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/&quot; title=&quot;GitHub&quot;&gt;GitHub&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.webpagetest.org/&quot; title=&quot;Web Page Tester&quot;&gt;WebPageTest&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;There is still a lot to do such as fixing the markup for older posts, updating google etc. I have plans to do some beginner posts to help people at my university get started with SQL so it is going to be a long process.&lt;/p&gt;

&lt;p&gt;As ever, any feedback is welcome regarding any of my work or my website.&lt;/p&gt;
</description>
				<pubDate>Thu, 29 Nov 2012 00:00:00 -0800</pubDate>
				<link>/2012/11/29/Website-Almost-There</link>
				<guid isPermaLink="true">/2012/11/29/Website-Almost-There</guid>
			</item>
		
			<item>
				<title>Website Update</title>
				<description>&lt;p&gt;Just a quick message for today. I am in the process of transferring all of my blog posts to a new system. Unfortunately, this takes quiet a bit of work converting the html to the markdown format. More on this soon and about the re-design itself.&lt;/p&gt;

&lt;p&gt;Keep coding!&lt;/p&gt;
</description>
				<pubDate>Sun, 18 Nov 2012 00:00:00 -0800</pubDate>
				<link>/2012/11/18/Website-Update</link>
				<guid isPermaLink="true">/2012/11/18/Website-Update</guid>
			</item>
		
	</channel>
</rss>