Dealing with SQL Performance (for .Net developers)

Introduction

I use Entity Framework… what do I care about SQL Performance?

It seems all too often that the answer to dealing with SQL is now to use an Object-Relational Mapping (ORM) tool to avoid SQL like the plague when talking to .Net developers.  Some of the reasons for this are that SQL contains black magic or because Entity Framework handles it for you so that you don’t have to.  And about a million other reasons to not work within SQL itself.

And to be honest, in a lot of cases the ORMs that are widely used will do an excellent job.  But there are going to be cases where that ORM falls on its face when you try to create a query and now you are the unfortunate soul who is tasked with resolving the issue.

So let’s be clear before we get started.  ORMs aren’t evil and they really do have a place within .Net applications but sometimes they can prove to be a square peg in a round hole.  So this write up is to add another tool to your tool belt.

ORM Example

We are going to use Entity Framework (EF) for our example because it’s a popular ORM out there so why not?

Setup & Background

We want to pull back all of the information from the database for a person that is currently using the application.

We are using AdventureWorks2014 running on a SQL 2014 server and using .Net 4.6.1 with EF 6.1.3 Code First for this test case.  The concepts we will be discussing here will apply to other versions of both .Net, SQL, and EF.

.Net Code

The code seen below seems to be popular in a lot of data access layers that are built in order to make querying objects easier for development teams.  The concept being that if you request a person object, you get a fully qualified object so you don’t need to worry about having the context available to get some information about the object in repeat trips to the database.  At a price of course which we will go over down below.

            Person person;

            using (var context = new AdventureWorks2014Context())
            {
                // Write out the query & parameters so we can view everything if the debugger is attached
                if (System.Diagnostics.Debugger.IsAttached) context.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

                // Include all the possible user information we could ever need
                person = context.People
                    .Include(p => p.Employee)
                    .Include(p => p.BusinessEntity)
                    .Include(p => p.BusinessEntityContacts)
                    .Include(p => p.EmailAddresses)
                    .Include(p => p.Password)
                    .Include(p => p.Customers)
                    .Include(p => p.PersonCreditCards)
                    .Include(p => p.PersonPhones)
                    .Single(p => p.LastName == lastName && p.FirstName == firstName);
            }

            Console.WriteLine($"Person: {person.LastName}, {person.FirstName}");
            Console.WriteLine("Phone Numbers:");
            foreach (var phone in person.PersonPhones)
                Console.WriteLine($"....{phone.PhoneNumber}");

So in the code above, we will query using the first and last name of a person and get back all the relevant data we could need about that person.

Generated SQL Query

Here is a general idea of the query that is generated:

SELECT 
    [UnionAll4].[BusinessEntityID] AS [C1], 
    [UnionAll4].[BusinessEntityID1] AS [C2], 
    [UnionAll4].[BusinessEntityID2] AS [C3], 
    [UnionAll4].[BusinessEntityID3] AS [C4], 
    [UnionAll4].[BusinessEntityID4] AS [C5], 
    [UnionAll4].[BusinessEntityID5] AS [C6], 
    [UnionAll4].[BusinessEntityID6] AS [C7], 
    [UnionAll4].[BusinessEntityID7] AS [C8], 
    [UnionAll4].[BusinessEntityID8] AS [C9], 
    [UnionAll4].[PersonType] AS [C10], 
    [UnionAll4].[NameStyle] AS [C11], 
    [UnionAll4].[Title] AS [C12], 
    [UnionAll4].[FirstName] AS [C13], 
        ...removed for brevity...
        FROM   (SELECT TOP (2) [Extent33].[BusinessEntityID] AS [BusinessEntityID34], [Extent33].[PersonType] AS [PersonType5], [Extent33].[NameStyle] AS [NameStyle5], [Extent33].[Title] AS [Title5], [Extent33].[FirstName] AS [FirstName5], [Extent33].[MiddleName] AS [MiddleName5], [Extent33].[LastName] AS [LastName5], [Extent33].[Suffix] AS [Suffix5], [Extent33].[EmailPromotion] AS [EmailPromotion5], [Extent33].[AdditionalContactInfo] AS [AdditionalContactInfo5], [Extent33].[Demographics] AS [Demographics5], [Extent33].[rowguid] AS [rowguid17], [Extent33].[ModifiedDate] AS [ModifiedDate17], [Extent34].[BusinessEntityID] AS [BusinessEntityID29], [Extent34].[NationalIDNumber] AS [NationalIDNumber5], [Extent34].[LoginID] AS [LoginID5], [Extent34].[OrganizationLevel] AS [OrganizationLevel5], [Extent34].[JobTitle] AS [JobTitle5], [Extent34].[BirthDate] AS [BirthDate5], [Extent34].[MaritalStatus] AS [MaritalStatus5], [Extent34].[Gender] AS [Gender5], [Extent34].[HireDate] AS [HireDate5], [Extent34].[SalariedFlag] AS [SalariedFlag5], [Extent34].[VacationHours] AS [VacationHours5], [Extent34].[SickLeaveHours] AS [SickLeaveHours5], [Extent34].[CurrentFlag] AS [CurrentFlag5], [Extent34].[rowguid] AS [rowguid18], [Extent34].[ModifiedDate] AS [ModifiedDate18], [Extent35].[BusinessEntityID] AS [BusinessEntityID30], [Extent35].[PasswordHash] AS [PasswordHash5], [Extent35].[PasswordSalt] AS [PasswordSalt5], [Extent35].[rowguid] AS [rowguid20], [Extent35].[ModifiedDate] AS [ModifiedDate20], [Join33].[BusinessEntityID35], [Join33].[rowguid19], [Join33].[ModifiedDate19], [Join33].[BusinessEntityID33], [Join33].[BusinessEntityID31], [Join33].[BusinessEntityID32]
            FROM    [Person].[Person] AS [Extent33]
            LEFT OUTER JOIN [HumanResources].[Employee] AS [Extent34] ON [Extent33].[BusinessEntityID] = [Extent34].[BusinessEntityID]
            LEFT OUTER JOIN [Person].[Password] AS [Extent35] ON [Extent33].[BusinessEntityID] = [Extent35].[BusinessEntityID]
            LEFT OUTER JOIN  (SELECT [Extent36].[BusinessEntityID] AS [BusinessEntityID35], [Extent36].[rowguid] AS [rowguid19], [Extent36].[ModifiedDate] AS [ModifiedDate19], [Join32].[BusinessEntityID33], [Join32].[BusinessEntityID31], [Join32].[BusinessEntityID32]
                FROM  [Person].[BusinessEntity] AS [Extent36]
                INNER JOIN  (SELECT [Extent37].[BusinessEntityID] AS [BusinessEntityID33], [Extent38].[BusinessEntityID] AS [BusinessEntityID31], [Extent39].[BusinessEntityID] AS [BusinessEntityID32]
                    FROM   [Person].[Person] AS [Extent37]
                    LEFT OUTER JOIN [HumanResources].[Employee] AS [Extent38] ON [Extent37].[BusinessEntityID] = [Extent38].[BusinessEntityID]
                    LEFT OUTER JOIN [Person].[Password] AS [Extent39] ON [Extent37].[BusinessEntityID] = [Extent39].[BusinessEntityID] ) AS [Join32] ON [Extent36].[BusinessEntityID] = [Join32].[BusinessEntityID33] ) AS [Join33] ON [Extent33].[BusinessEntityID] = [Join33].[BusinessEntityID33]
            WHERE (N'Griffin' = [Extent33].[LastName]) AND (N'Abigail' = [Extent33].[FirstName]) ) AS [Limit5]
        INNER JOIN [Person].[PersonPhone] AS [Extent40] ON [Limit5].[BusinessEntityID34] = [Extent40].[BusinessEntityID]) AS [UnionAll4]
    ORDER BY [UnionAll4].[BusinessEntityID] ASC, [UnionAll4].[BusinessEntityID1] ASC, [UnionAll4].[BusinessEntityID2] ASC, [UnionAll4].[BusinessEntityID3] ASC, [UnionAll4].[BusinessEntityID4] ASC, [UnionAll4].[BusinessEntityID5] ASC, [UnionAll4].[BusinessEntityID6] ASC, [UnionAll4].[BusinessEntityID8] ASC, [UnionAll4].[BusinessEntityID10] ASC, [UnionAll4].[C1] ASC

If you wish, you can expand here to see the full query (it’s long):
Show Large Query

SELECT 
    [UnionAll4].[BusinessEntityID] AS [C1], 
    [UnionAll4].[BusinessEntityID1] AS [C2], 
    [UnionAll4].[BusinessEntityID2] AS [C3], 
    [UnionAll4].[BusinessEntityID3] AS [C4], 
    [UnionAll4].[BusinessEntityID4] AS [C5], 
    [UnionAll4].[BusinessEntityID5] AS [C6], 
    [UnionAll4].[BusinessEntityID6] AS [C7], 
    [UnionAll4].[BusinessEntityID7] AS [C8], 
    [UnionAll4].[BusinessEntityID8] AS [C9], 
    [UnionAll4].[PersonType] AS [C10], 
    [UnionAll4].[NameStyle] AS [C11], 
    [UnionAll4].[Title] AS [C12], 
    [UnionAll4].[FirstName] AS [C13], 
    [UnionAll4].[MiddleName] AS [C14], 
    [UnionAll4].[LastName] AS [C15], 
    [UnionAll4].[Suffix] AS [C16], 
    [UnionAll4].[EmailPromotion] AS [C17], 
    [UnionAll4].[AdditionalContactInfo] AS [C18], 
    [UnionAll4].[Demographics] AS [C19], 
    [UnionAll4].[rowguid] AS [C20], 
    [UnionAll4].[ModifiedDate] AS [C21], 
    [UnionAll4].[BusinessEntityID9] AS [C22], 
    [UnionAll4].[NationalIDNumber] AS [C23], 
    [UnionAll4].[LoginID] AS [C24], 
    [UnionAll4].[OrganizationLevel] AS [C25], 
    [UnionAll4].[JobTitle] AS [C26], 
    [UnionAll4].[BirthDate] AS [C27], 
    [UnionAll4].[MaritalStatus] AS [C28], 
    [UnionAll4].[Gender] AS [C29], 
    [UnionAll4].[HireDate] AS [C30], 
    [UnionAll4].[SalariedFlag] AS [C31], 
    [UnionAll4].[VacationHours] AS [C32], 
    [UnionAll4].[SickLeaveHours] AS [C33], 
    [UnionAll4].[CurrentFlag] AS [C34], 
    [UnionAll4].[rowguid1] AS [C35], 
    [UnionAll4].[ModifiedDate1] AS [C36], 
    [UnionAll4].[BusinessEntityID10] AS [C37], 
    [UnionAll4].[rowguid2] AS [C38], 
    [UnionAll4].[ModifiedDate2] AS [C39], 
    [UnionAll4].[BusinessEntityID11] AS [C40], 
    [UnionAll4].[PasswordHash] AS [C41], 
    [UnionAll4].[PasswordSalt] AS [C42], 
    [UnionAll4].[rowguid3] AS [C43], 
    [UnionAll4].[ModifiedDate3] AS [C44], 
    [UnionAll4].[C1] AS [C45], 
    [UnionAll4].[BusinessEntityID12] AS [C46], 
    [UnionAll4].[PersonID] AS [C47], 
    [UnionAll4].[ContactTypeID] AS [C48], 
    [UnionAll4].[rowguid4] AS [C49], 
    [UnionAll4].[ModifiedDate4] AS [C50], 
    [UnionAll4].[PersonID1] AS [C51], 
    [UnionAll4].[C2] AS [C52], 
    [UnionAll4].[C3] AS [C53], 
    [UnionAll4].[C4] AS [C54], 
    [UnionAll4].[C5] AS [C55], 
    [UnionAll4].[C6] AS [C56], 
    [UnionAll4].[C7] AS [C57], 
    [UnionAll4].[C8] AS [C58], 
    [UnionAll4].[C9] AS [C59], 
    [UnionAll4].[C10] AS [C60], 
    [UnionAll4].[C11] AS [C61], 
    [UnionAll4].[C12] AS [C62], 
    [UnionAll4].[C13] AS [C63], 
    [UnionAll4].[C14] AS [C64], 
    [UnionAll4].[C15] AS [C65], 
    [UnionAll4].[C16] AS [C66], 
    [UnionAll4].[C17] AS [C67], 
    [UnionAll4].[C18] AS [C68], 
    [UnionAll4].[C19] AS [C69], 
    [UnionAll4].[C20] AS [C70], 
    [UnionAll4].[C21] AS [C71], 
    [UnionAll4].[C22] AS [C72], 
    [UnionAll4].[C23] AS [C73]
    FROM  (SELECT 
        CASE WHEN ([Extent8].[BusinessEntityID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1], 
        [Limit1].[BusinessEntityID1] AS [BusinessEntityID], 
        [Limit1].[BusinessEntityID2] AS [BusinessEntityID1], 
        [Limit1].[BusinessEntityID1] AS [BusinessEntityID2], 
        [Limit1].[BusinessEntityID3] AS [BusinessEntityID3], 
        [Limit1].[BusinessEntityID4] AS [BusinessEntityID4], 
        [Limit1].[BusinessEntityID5] AS [BusinessEntityID5], 
        [Limit1].[BusinessEntityID2] AS [BusinessEntityID6], 
        [Limit1].[BusinessEntityID6] AS [BusinessEntityID7], 
        [Limit1].[BusinessEntityID6] AS [BusinessEntityID8], 
        [Limit1].[PersonType1] AS [PersonType], 
        [Limit1].[NameStyle1] AS [NameStyle], 
        [Limit1].[Title1] AS [Title], 
        [Limit1].[FirstName1] AS [FirstName], 
        [Limit1].[MiddleName1] AS [MiddleName], 
        [Limit1].[LastName1] AS [LastName], 
        [Limit1].[Suffix1] AS [Suffix], 
        [Limit1].[EmailPromotion1] AS [EmailPromotion], 
        [Limit1].[AdditionalContactInfo1] AS [AdditionalContactInfo], 
        [Limit1].[Demographics1] AS [Demographics], 
        [Limit1].[rowguid1] AS [rowguid], 
        [Limit1].[ModifiedDate1] AS [ModifiedDate], 
        [Limit1].[BusinessEntityID1] AS [BusinessEntityID9], 
        [Limit1].[NationalIDNumber1] AS [NationalIDNumber], 
        [Limit1].[LoginID1] AS [LoginID], 
        [Limit1].[OrganizationLevel1] AS [OrganizationLevel], 
        [Limit1].[JobTitle1] AS [JobTitle], 
        [Limit1].[BirthDate1] AS [BirthDate], 
        [Limit1].[MaritalStatus1] AS [MaritalStatus], 
        [Limit1].[Gender1] AS [Gender], 
        [Limit1].[HireDate1] AS [HireDate], 
        [Limit1].[SalariedFlag1] AS [SalariedFlag], 
        [Limit1].[VacationHours1] AS [VacationHours], 
        [Limit1].[SickLeaveHours1] AS [SickLeaveHours], 
        [Limit1].[CurrentFlag1] AS [CurrentFlag], 
        [Limit1].[rowguid2] AS [rowguid1], 
        [Limit1].[ModifiedDate2] AS [ModifiedDate1], 
        [Limit1].[BusinessEntityID7] AS [BusinessEntityID10], 
        [Limit1].[rowguid3] AS [rowguid2], 
        [Limit1].[ModifiedDate3] AS [ModifiedDate2], 
        [Limit1].[BusinessEntityID2] AS [BusinessEntityID11], 
        [Limit1].[PasswordHash1] AS [PasswordHash], 
        [Limit1].[PasswordSalt1] AS [PasswordSalt], 
        [Limit1].[rowguid4] AS [rowguid3], 
        [Limit1].[ModifiedDate4] AS [ModifiedDate3], 
        [Extent8].[BusinessEntityID] AS [BusinessEntityID12], 
        [Extent8].[PersonID] AS [PersonID], 
        [Extent8].[ContactTypeID] AS [ContactTypeID], 
        [Extent8].[rowguid] AS [rowguid4], 
        [Extent8].[ModifiedDate] AS [ModifiedDate4], 
        [Extent8].[PersonID] AS [PersonID1], 
        CAST(NULL AS int) AS [C2], 
        CAST(NULL AS int) AS [C3], 
        CAST(NULL AS varchar(1)) AS [C4], 
        CAST(NULL AS uniqueidentifier) AS [C5], 
        CAST(NULL AS datetime2) AS [C6], 
        CAST(NULL AS int) AS [C7], 
        CAST(NULL AS int) AS [C8], 
        CAST(NULL AS int) AS [C9], 
        CAST(NULL AS int) AS [C10], 
        CAST(NULL AS int) AS [C11], 
        CAST(NULL AS varchar(1)) AS [C12], 
        CAST(NULL AS uniqueidentifier) AS [C13], 
        CAST(NULL AS datetime2) AS [C14], 
        CAST(NULL AS int) AS [C15], 
        CAST(NULL AS int) AS [C16], 
        CAST(NULL AS datetime2) AS [C17], 
        CAST(NULL AS int) AS [C18], 
        CAST(NULL AS int) AS [C19], 
        CAST(NULL AS varchar(1)) AS [C20], 
        CAST(NULL AS int) AS [C21], 
        CAST(NULL AS datetime2) AS [C22], 
        CAST(NULL AS int) AS [C23]
        FROM   (SELECT TOP (2) [Extent1].[BusinessEntityID] AS [BusinessEntityID6], [Extent1].[PersonType] AS [PersonType1], [Extent1].[NameStyle] AS [NameStyle1], [Extent1].[Title] AS [Title1], [Extent1].[FirstName] AS [FirstName1], [Extent1].[MiddleName] AS [MiddleName1], [Extent1].[LastName] AS [LastName1], [Extent1].[Suffix] AS [Suffix1], [Extent1].[EmailPromotion] AS [EmailPromotion1], [Extent1].[AdditionalContactInfo] AS [AdditionalContactInfo1], [Extent1].[Demographics] AS [Demographics1], [Extent1].[rowguid] AS [rowguid1], [Extent1].[ModifiedDate] AS [ModifiedDate1], [Extent2].[BusinessEntityID] AS [BusinessEntityID1], [Extent2].[NationalIDNumber] AS [NationalIDNumber1], [Extent2].[LoginID] AS [LoginID1], [Extent2].[OrganizationLevel] AS [OrganizationLevel1], [Extent2].[JobTitle] AS [JobTitle1], [Extent2].[BirthDate] AS [BirthDate1], [Extent2].[MaritalStatus] AS [MaritalStatus1], [Extent2].[Gender] AS [Gender1], [Extent2].[HireDate] AS [HireDate1], [Extent2].[SalariedFlag] AS [SalariedFlag1], [Extent2].[VacationHours] AS [VacationHours1], [Extent2].[SickLeaveHours] AS [SickLeaveHours1], [Extent2].[CurrentFlag] AS [CurrentFlag1], [Extent2].[rowguid] AS [rowguid2], [Extent2].[ModifiedDate] AS [ModifiedDate2], [Extent3].[BusinessEntityID] AS [BusinessEntityID2], [Extent3].[PasswordHash] AS [PasswordHash1], [Extent3].[PasswordSalt] AS [PasswordSalt1], [Extent3].[rowguid] AS [rowguid4], [Extent3].[ModifiedDate] AS [ModifiedDate4], [Join5].[BusinessEntityID7], [Join5].[rowguid3], [Join5].[ModifiedDate3], [Join5].[BusinessEntityID5], [Join5].[BusinessEntityID3], [Join5].[BusinessEntityID4]
            FROM    [Person].[Person] AS [Extent1]
            LEFT OUTER JOIN [HumanResources].[Employee] AS [Extent2] ON [Extent1].[BusinessEntityID] = [Extent2].[BusinessEntityID]
            LEFT OUTER JOIN [Person].[Password] AS [Extent3] ON [Extent1].[BusinessEntityID] = [Extent3].[BusinessEntityID]
            LEFT OUTER JOIN  (SELECT [Extent4].[BusinessEntityID] AS [BusinessEntityID7], [Extent4].[rowguid] AS [rowguid3], [Extent4].[ModifiedDate] AS [ModifiedDate3], [Join4].[BusinessEntityID5], [Join4].[BusinessEntityID3], [Join4].[BusinessEntityID4]
                FROM  [Person].[BusinessEntity] AS [Extent4]
                INNER JOIN  (SELECT [Extent5].[BusinessEntityID] AS [BusinessEntityID5], [Extent6].[BusinessEntityID] AS [BusinessEntityID3], [Extent7].[BusinessEntityID] AS [BusinessEntityID4]
                    FROM   [Person].[Person] AS [Extent5]
                    LEFT OUTER JOIN [HumanResources].[Employee] AS [Extent6] ON [Extent5].[BusinessEntityID] = [Extent6].[BusinessEntityID]
                    LEFT OUTER JOIN [Person].[Password] AS [Extent7] ON [Extent5].[BusinessEntityID] = [Extent7].[BusinessEntityID] ) AS [Join4] ON [Extent4].[BusinessEntityID] = [Join4].[BusinessEntityID5] ) AS [Join5] ON [Extent1].[BusinessEntityID] = [Join5].[BusinessEntityID5]
            WHERE (N'Griffin' = [Extent1].[LastName]) AND (N'Abigail' = [Extent1].[FirstName]) ) AS [Limit1]
        LEFT OUTER JOIN [Person].[BusinessEntityContact] AS [Extent8] ON [Limit1].[BusinessEntityID6] = [Extent8].[PersonID]
    UNION ALL
        SELECT 
        2 AS [C1], 
        [Limit2].[BusinessEntityID8] AS [BusinessEntityID], 
        [Limit2].[BusinessEntityID9] AS [BusinessEntityID1], 
        [Limit2].[BusinessEntityID8] AS [BusinessEntityID2], 
        [Limit2].[BusinessEntityID10] AS [BusinessEntityID3], 
        [Limit2].[BusinessEntityID11] AS [BusinessEntityID4], 
        [Limit2].[BusinessEntityID12] AS [BusinessEntityID5], 
        [Limit2].[BusinessEntityID9] AS [BusinessEntityID6], 
        [Limit2].[BusinessEntityID13] AS [BusinessEntityID7], 
        [Limit2].[BusinessEntityID13] AS [BusinessEntityID8], 
        [Limit2].[PersonType2] AS [PersonType], 
        [Limit2].[NameStyle2] AS [NameStyle], 
        [Limit2].[Title2] AS [Title], 
        [Limit2].[FirstName2] AS [FirstName], 
        [Limit2].[MiddleName2] AS [MiddleName], 
        [Limit2].[LastName2] AS [LastName], 
        [Limit2].[Suffix2] AS [Suffix], 
        [Limit2].[EmailPromotion2] AS [EmailPromotion], 
        [Limit2].[AdditionalContactInfo2] AS [AdditionalContactInfo], 
        [Limit2].[Demographics2] AS [Demographics], 
        [Limit2].[rowguid5] AS [rowguid], 
        [Limit2].[ModifiedDate5] AS [ModifiedDate], 
        [Limit2].[BusinessEntityID8] AS [BusinessEntityID9], 
        [Limit2].[NationalIDNumber2] AS [NationalIDNumber], 
        [Limit2].[LoginID2] AS [LoginID], 
        [Limit2].[OrganizationLevel2] AS [OrganizationLevel], 
        [Limit2].[JobTitle2] AS [JobTitle], 
        [Limit2].[BirthDate2] AS [BirthDate], 
        [Limit2].[MaritalStatus2] AS [MaritalStatus], 
        [Limit2].[Gender2] AS [Gender], 
        [Limit2].[HireDate2] AS [HireDate], 
        [Limit2].[SalariedFlag2] AS [SalariedFlag], 
        [Limit2].[VacationHours2] AS [VacationHours], 
        [Limit2].[SickLeaveHours2] AS [SickLeaveHours], 
        [Limit2].[CurrentFlag2] AS [CurrentFlag], 
        [Limit2].[rowguid6] AS [rowguid1], 
        [Limit2].[ModifiedDate6] AS [ModifiedDate1], 
        [Limit2].[BusinessEntityID14] AS [BusinessEntityID10], 
        [Limit2].[rowguid7] AS [rowguid2], 
        [Limit2].[ModifiedDate7] AS [ModifiedDate2], 
        [Limit2].[BusinessEntityID9] AS [BusinessEntityID11], 
        [Limit2].[PasswordHash2] AS [PasswordHash], 
        [Limit2].[PasswordSalt2] AS [PasswordSalt], 
        [Limit2].[rowguid8] AS [rowguid3], 
        [Limit2].[ModifiedDate8] AS [ModifiedDate3], 
        CAST(NULL AS int) AS [C2], 
        CAST(NULL AS int) AS [C3], 
        CAST(NULL AS int) AS [C4], 
        CAST(NULL AS uniqueidentifier) AS [C5], 
        CAST(NULL AS datetime2) AS [C6], 
        CAST(NULL AS int) AS [C7], 
        [Extent16].[BusinessEntityID] AS [BusinessEntityID12], 
        [Extent16].[EmailAddressID] AS [EmailAddressID], 
        [Extent16].[EmailAddress] AS [EmailAddress], 
        [Extent16].[rowguid] AS [rowguid4], 
        [Extent16].[ModifiedDate] AS [ModifiedDate4], 
        [Extent16].[BusinessEntityID] AS [BusinessEntityID13], 
        CAST(NULL AS int) AS [C8], 
        CAST(NULL AS int) AS [C9], 
        CAST(NULL AS int) AS [C10], 
        CAST(NULL AS int) AS [C11], 
        CAST(NULL AS varchar(1)) AS [C12], 
        CAST(NULL AS uniqueidentifier) AS [C13], 
        CAST(NULL AS datetime2) AS [C14], 
        CAST(NULL AS int) AS [C15], 
        CAST(NULL AS int) AS [C16], 
        CAST(NULL AS datetime2) AS [C17], 
        CAST(NULL AS int) AS [C18], 
        CAST(NULL AS int) AS [C19], 
        CAST(NULL AS varchar(1)) AS [C20], 
        CAST(NULL AS int) AS [C21], 
        CAST(NULL AS datetime2) AS [C22], 
        CAST(NULL AS int) AS [C23]
        FROM   (SELECT TOP (2) [Extent9].[BusinessEntityID] AS [BusinessEntityID13], [Extent9].[PersonType] AS [PersonType2], [Extent9].[NameStyle] AS [NameStyle2], [Extent9].[Title] AS [Title2], [Extent9].[FirstName] AS [FirstName2], [Extent9].[MiddleName] AS [MiddleName2], [Extent9].[LastName] AS [LastName2], [Extent9].[Suffix] AS [Suffix2], [Extent9].[EmailPromotion] AS [EmailPromotion2], [Extent9].[AdditionalContactInfo] AS [AdditionalContactInfo2], [Extent9].[Demographics] AS [Demographics2], [Extent9].[rowguid] AS [rowguid5], [Extent9].[ModifiedDate] AS [ModifiedDate5], [Extent10].[BusinessEntityID] AS [BusinessEntityID8], [Extent10].[NationalIDNumber] AS [NationalIDNumber2], [Extent10].[LoginID] AS [LoginID2], [Extent10].[OrganizationLevel] AS [OrganizationLevel2], [Extent10].[JobTitle] AS [JobTitle2], [Extent10].[BirthDate] AS [BirthDate2], [Extent10].[MaritalStatus] AS [MaritalStatus2], [Extent10].[Gender] AS [Gender2], [Extent10].[HireDate] AS [HireDate2], [Extent10].[SalariedFlag] AS [SalariedFlag2], [Extent10].[VacationHours] AS [VacationHours2], [Extent10].[SickLeaveHours] AS [SickLeaveHours2], [Extent10].[CurrentFlag] AS [CurrentFlag2], [Extent10].[rowguid] AS [rowguid6], [Extent10].[ModifiedDate] AS [ModifiedDate6], [Extent11].[BusinessEntityID] AS [BusinessEntityID9], [Extent11].[PasswordHash] AS [PasswordHash2], [Extent11].[PasswordSalt] AS [PasswordSalt2], [Extent11].[rowguid] AS [rowguid8], [Extent11].[ModifiedDate] AS [ModifiedDate8], [Join12].[BusinessEntityID14], [Join12].[rowguid7], [Join12].[ModifiedDate7], [Join12].[BusinessEntityID12], [Join12].[BusinessEntityID10], [Join12].[BusinessEntityID11]
            FROM    [Person].[Person] AS [Extent9]
            LEFT OUTER JOIN [HumanResources].[Employee] AS [Extent10] ON [Extent9].[BusinessEntityID] = [Extent10].[BusinessEntityID]
            LEFT OUTER JOIN [Person].[Password] AS [Extent11] ON [Extent9].[BusinessEntityID] = [Extent11].[BusinessEntityID]
            LEFT OUTER JOIN  (SELECT [Extent12].[BusinessEntityID] AS [BusinessEntityID14], [Extent12].[rowguid] AS [rowguid7], [Extent12].[ModifiedDate] AS [ModifiedDate7], [Join11].[BusinessEntityID12], [Join11].[BusinessEntityID10], [Join11].[BusinessEntityID11]
                FROM  [Person].[BusinessEntity] AS [Extent12]
                INNER JOIN  (SELECT [Extent13].[BusinessEntityID] AS [BusinessEntityID12], [Extent14].[BusinessEntityID] AS [BusinessEntityID10], [Extent15].[BusinessEntityID] AS [BusinessEntityID11]
                    FROM   [Person].[Person] AS [Extent13]
                    LEFT OUTER JOIN [HumanResources].[Employee] AS [Extent14] ON [Extent13].[BusinessEntityID] = [Extent14].[BusinessEntityID]
                    LEFT OUTER JOIN [Person].[Password] AS [Extent15] ON [Extent13].[BusinessEntityID] = [Extent15].[BusinessEntityID] ) AS [Join11] ON [Extent12].[BusinessEntityID] = [Join11].[BusinessEntityID12] ) AS [Join12] ON [Extent9].[BusinessEntityID] = [Join12].[BusinessEntityID12]
            WHERE (N'Griffin' = [Extent9].[LastName]) AND (N'Abigail' = [Extent9].[FirstName]) ) AS [Limit2]
        INNER JOIN [Person].[EmailAddress] AS [Extent16] ON [Limit2].[BusinessEntityID13] = [Extent16].[BusinessEntityID]
    UNION ALL
        SELECT 
        3 AS [C1], 
        [Limit3].[BusinessEntityID15] AS [BusinessEntityID], 
        [Limit3].[BusinessEntityID16] AS [BusinessEntityID1], 
        [Limit3].[BusinessEntityID15] AS [BusinessEntityID2], 
        [Limit3].[BusinessEntityID17] AS [BusinessEntityID3], 
        [Limit3].[BusinessEntityID18] AS [BusinessEntityID4], 
        [Limit3].[BusinessEntityID19] AS [BusinessEntityID5], 
        [Limit3].[BusinessEntityID16] AS [BusinessEntityID6], 
        [Limit3].[BusinessEntityID20] AS [BusinessEntityID7], 
        [Limit3].[BusinessEntityID20] AS [BusinessEntityID8], 
        [Limit3].[PersonType3] AS [PersonType], 
        [Limit3].[NameStyle3] AS [NameStyle], 
        [Limit3].[Title3] AS [Title], 
        [Limit3].[FirstName3] AS [FirstName], 
        [Limit3].[MiddleName3] AS [MiddleName], 
        [Limit3].[LastName3] AS [LastName], 
        [Limit3].[Suffix3] AS [Suffix], 
        [Limit3].[EmailPromotion3] AS [EmailPromotion], 
        [Limit3].[AdditionalContactInfo3] AS [AdditionalContactInfo], 
        [Limit3].[Demographics3] AS [Demographics], 
        [Limit3].[rowguid9] AS [rowguid], 
        [Limit3].[ModifiedDate9] AS [ModifiedDate], 
        [Limit3].[BusinessEntityID15] AS [BusinessEntityID9], 
        [Limit3].[NationalIDNumber3] AS [NationalIDNumber], 
        [Limit3].[LoginID3] AS [LoginID], 
        [Limit3].[OrganizationLevel3] AS [OrganizationLevel], 
        [Limit3].[JobTitle3] AS [JobTitle], 
        [Limit3].[BirthDate3] AS [BirthDate], 
        [Limit3].[MaritalStatus3] AS [MaritalStatus], 
        [Limit3].[Gender3] AS [Gender], 
        [Limit3].[HireDate3] AS [HireDate], 
        [Limit3].[SalariedFlag3] AS [SalariedFlag], 
        [Limit3].[VacationHours3] AS [VacationHours], 
        [Limit3].[SickLeaveHours3] AS [SickLeaveHours], 
        [Limit3].[CurrentFlag3] AS [CurrentFlag], 
        [Limit3].[rowguid10] AS [rowguid1], 
        [Limit3].[ModifiedDate10] AS [ModifiedDate1], 
        [Limit3].[BusinessEntityID21] AS [BusinessEntityID10], 
        [Limit3].[rowguid11] AS [rowguid2], 
        [Limit3].[ModifiedDate11] AS [ModifiedDate2], 
        [Limit3].[BusinessEntityID16] AS [BusinessEntityID11], 
        [Limit3].[PasswordHash3] AS [PasswordHash], 
        [Limit3].[PasswordSalt3] AS [PasswordSalt], 
        [Limit3].[rowguid12] AS [rowguid3], 
        [Limit3].[ModifiedDate12] AS [ModifiedDate3], 
        CAST(NULL AS int) AS [C2], 
        CAST(NULL AS int) AS [C3], 
        CAST(NULL AS int) AS [C4], 
        CAST(NULL AS uniqueidentifier) AS [C5], 
        CAST(NULL AS datetime2) AS [C6], 
        CAST(NULL AS int) AS [C7], 
        CAST(NULL AS int) AS [C8], 
        CAST(NULL AS int) AS [C9], 
        CAST(NULL AS varchar(1)) AS [C10], 
        CAST(NULL AS uniqueidentifier) AS [C11], 
        CAST(NULL AS datetime2) AS [C12], 
        CAST(NULL AS int) AS [C13], 
        [Extent24].[CustomerID] AS [CustomerID], 
        [Extent24].[PersonID] AS [PersonID], 
        [Extent24].[StoreID] AS [StoreID], 
        [Extent24].[TerritoryID] AS [TerritoryID], 
        [Extent24].[AccountNumber] AS [AccountNumber], 
        [Extent24].[rowguid] AS [rowguid4], 
        [Extent24].[ModifiedDate] AS [ModifiedDate4], 
        CAST(NULL AS int) AS [C14], 
        CAST(NULL AS int) AS [C15], 
        CAST(NULL AS datetime2) AS [C16], 
        CAST(NULL AS int) AS [C17], 
        CAST(NULL AS int) AS [C18], 
        CAST(NULL AS varchar(1)) AS [C19], 
        CAST(NULL AS int) AS [C20], 
        CAST(NULL AS datetime2) AS [C21], 
        CAST(NULL AS int) AS [C22]
        FROM   (SELECT TOP (2) [Extent17].[BusinessEntityID] AS [BusinessEntityID20], [Extent17].[PersonType] AS [PersonType3], [Extent17].[NameStyle] AS [NameStyle3], [Extent17].[Title] AS [Title3], [Extent17].[FirstName] AS [FirstName3], [Extent17].[MiddleName] AS [MiddleName3], [Extent17].[LastName] AS [LastName3], [Extent17].[Suffix] AS [Suffix3], [Extent17].[EmailPromotion] AS [EmailPromotion3], [Extent17].[AdditionalContactInfo] AS [AdditionalContactInfo3], [Extent17].[Demographics] AS [Demographics3], [Extent17].[rowguid] AS [rowguid9], [Extent17].[ModifiedDate] AS [ModifiedDate9], [Extent18].[BusinessEntityID] AS [BusinessEntityID15], [Extent18].[NationalIDNumber] AS [NationalIDNumber3], [Extent18].[LoginID] AS [LoginID3], [Extent18].[OrganizationLevel] AS [OrganizationLevel3], [Extent18].[JobTitle] AS [JobTitle3], [Extent18].[BirthDate] AS [BirthDate3], [Extent18].[MaritalStatus] AS [MaritalStatus3], [Extent18].[Gender] AS [Gender3], [Extent18].[HireDate] AS [HireDate3], [Extent18].[SalariedFlag] AS [SalariedFlag3], [Extent18].[VacationHours] AS [VacationHours3], [Extent18].[SickLeaveHours] AS [SickLeaveHours3], [Extent18].[CurrentFlag] AS [CurrentFlag3], [Extent18].[rowguid] AS [rowguid10], [Extent18].[ModifiedDate] AS [ModifiedDate10], [Extent19].[BusinessEntityID] AS [BusinessEntityID16], [Extent19].[PasswordHash] AS [PasswordHash3], [Extent19].[PasswordSalt] AS [PasswordSalt3], [Extent19].[rowguid] AS [rowguid12], [Extent19].[ModifiedDate] AS [ModifiedDate12], [Join19].[BusinessEntityID21], [Join19].[rowguid11], [Join19].[ModifiedDate11], [Join19].[BusinessEntityID19], [Join19].[BusinessEntityID17], [Join19].[BusinessEntityID18]
            FROM    [Person].[Person] AS [Extent17]
            LEFT OUTER JOIN [HumanResources].[Employee] AS [Extent18] ON [Extent17].[BusinessEntityID] = [Extent18].[BusinessEntityID]
            LEFT OUTER JOIN [Person].[Password] AS [Extent19] ON [Extent17].[BusinessEntityID] = [Extent19].[BusinessEntityID]
            LEFT OUTER JOIN  (SELECT [Extent20].[BusinessEntityID] AS [BusinessEntityID21], [Extent20].[rowguid] AS [rowguid11], [Extent20].[ModifiedDate] AS [ModifiedDate11], [Join18].[BusinessEntityID19], [Join18].[BusinessEntityID17], [Join18].[BusinessEntityID18]
                FROM  [Person].[BusinessEntity] AS [Extent20]
                INNER JOIN  (SELECT [Extent21].[BusinessEntityID] AS [BusinessEntityID19], [Extent22].[BusinessEntityID] AS [BusinessEntityID17], [Extent23].[BusinessEntityID] AS [BusinessEntityID18]
                    FROM   [Person].[Person] AS [Extent21]
                    LEFT OUTER JOIN [HumanResources].[Employee] AS [Extent22] ON [Extent21].[BusinessEntityID] = [Extent22].[BusinessEntityID]
                    LEFT OUTER JOIN [Person].[Password] AS [Extent23] ON [Extent21].[BusinessEntityID] = [Extent23].[BusinessEntityID] ) AS [Join18] ON [Extent20].[BusinessEntityID] = [Join18].[BusinessEntityID19] ) AS [Join19] ON [Extent17].[BusinessEntityID] = [Join19].[BusinessEntityID19]
            WHERE (N'Griffin' = [Extent17].[LastName]) AND (N'Abigail' = [Extent17].[FirstName]) ) AS [Limit3]
        INNER JOIN [Sales].[Customer] AS [Extent24] ON [Limit3].[BusinessEntityID20] = [Extent24].[PersonID]
    UNION ALL
        SELECT 
        4 AS [C1], 
        [Limit4].[BusinessEntityID22] AS [BusinessEntityID], 
        [Limit4].[BusinessEntityID23] AS [BusinessEntityID1], 
        [Limit4].[BusinessEntityID22] AS [BusinessEntityID2], 
        [Limit4].[BusinessEntityID24] AS [BusinessEntityID3], 
        [Limit4].[BusinessEntityID25] AS [BusinessEntityID4], 
        [Limit4].[BusinessEntityID26] AS [BusinessEntityID5], 
        [Limit4].[BusinessEntityID23] AS [BusinessEntityID6], 
        [Limit4].[BusinessEntityID27] AS [BusinessEntityID7], 
        [Limit4].[BusinessEntityID27] AS [BusinessEntityID8], 
        [Limit4].[PersonType4] AS [PersonType], 
        [Limit4].[NameStyle4] AS [NameStyle], 
        [Limit4].[Title4] AS [Title], 
        [Limit4].[FirstName4] AS [FirstName], 
        [Limit4].[MiddleName4] AS [MiddleName], 
        [Limit4].[LastName4] AS [LastName], 
        [Limit4].[Suffix4] AS [Suffix], 
        [Limit4].[EmailPromotion4] AS [EmailPromotion], 
        [Limit4].[AdditionalContactInfo4] AS [AdditionalContactInfo], 
        [Limit4].[Demographics4] AS [Demographics], 
        [Limit4].[rowguid13] AS [rowguid], 
        [Limit4].[ModifiedDate13] AS [ModifiedDate], 
        [Limit4].[BusinessEntityID22] AS [BusinessEntityID9], 
        [Limit4].[NationalIDNumber4] AS [NationalIDNumber], 
        [Limit4].[LoginID4] AS [LoginID], 
        [Limit4].[OrganizationLevel4] AS [OrganizationLevel], 
        [Limit4].[JobTitle4] AS [JobTitle], 
        [Limit4].[BirthDate4] AS [BirthDate], 
        [Limit4].[MaritalStatus4] AS [MaritalStatus], 
        [Limit4].[Gender4] AS [Gender], 
        [Limit4].[HireDate4] AS [HireDate], 
        [Limit4].[SalariedFlag4] AS [SalariedFlag], 
        [Limit4].[VacationHours4] AS [VacationHours], 
        [Limit4].[SickLeaveHours4] AS [SickLeaveHours], 
        [Limit4].[CurrentFlag4] AS [CurrentFlag], 
        [Limit4].[rowguid14] AS [rowguid1], 
        [Limit4].[ModifiedDate14] AS [ModifiedDate1], 
        [Limit4].[BusinessEntityID28] AS [BusinessEntityID10], 
        [Limit4].[rowguid15] AS [rowguid2], 
        [Limit4].[ModifiedDate15] AS [ModifiedDate2], 
        [Limit4].[BusinessEntityID23] AS [BusinessEntityID11], 
        [Limit4].[PasswordHash4] AS [PasswordHash], 
        [Limit4].[PasswordSalt4] AS [PasswordSalt], 
        [Limit4].[rowguid16] AS [rowguid3], 
        [Limit4].[ModifiedDate16] AS [ModifiedDate3], 
        CAST(NULL AS int) AS [C2], 
        CAST(NULL AS int) AS [C3], 
        CAST(NULL AS int) AS [C4], 
        CAST(NULL AS uniqueidentifier) AS [C5], 
        CAST(NULL AS datetime2) AS [C6], 
        CAST(NULL AS int) AS [C7], 
        CAST(NULL AS int) AS [C8], 
        CAST(NULL AS int) AS [C9], 
        CAST(NULL AS varchar(1)) AS [C10], 
        CAST(NULL AS uniqueidentifier) AS [C11], 
        CAST(NULL AS datetime2) AS [C12], 
        CAST(NULL AS int) AS [C13], 
        CAST(NULL AS int) AS [C14], 
        CAST(NULL AS int) AS [C15], 
        CAST(NULL AS int) AS [C16], 
        CAST(NULL AS int) AS [C17], 
        CAST(NULL AS varchar(1)) AS [C18], 
        CAST(NULL AS uniqueidentifier) AS [C19], 
        CAST(NULL AS datetime2) AS [C20], 
        [Extent32].[BusinessEntityID] AS [BusinessEntityID12], 
        [Extent32].[CreditCardID] AS [CreditCardID], 
        [Extent32].[ModifiedDate] AS [ModifiedDate4], 
        [Extent32].[BusinessEntityID] AS [BusinessEntityID13], 
        CAST(NULL AS int) AS [C21], 
        CAST(NULL AS varchar(1)) AS [C22], 
        CAST(NULL AS int) AS [C23], 
        CAST(NULL AS datetime2) AS [C24], 
        CAST(NULL AS int) AS [C25]
        FROM   (SELECT TOP (2) [Extent25].[BusinessEntityID] AS [BusinessEntityID27], [Extent25].[PersonType] AS [PersonType4], [Extent25].[NameStyle] AS [NameStyle4], [Extent25].[Title] AS [Title4], [Extent25].[FirstName] AS [FirstName4], [Extent25].[MiddleName] AS [MiddleName4], [Extent25].[LastName] AS [LastName4], [Extent25].[Suffix] AS [Suffix4], [Extent25].[EmailPromotion] AS [EmailPromotion4], [Extent25].[AdditionalContactInfo] AS [AdditionalContactInfo4], [Extent25].[Demographics] AS [Demographics4], [Extent25].[rowguid] AS [rowguid13], [Extent25].[ModifiedDate] AS [ModifiedDate13], [Extent26].[BusinessEntityID] AS [BusinessEntityID22], [Extent26].[NationalIDNumber] AS [NationalIDNumber4], [Extent26].[LoginID] AS [LoginID4], [Extent26].[OrganizationLevel] AS [OrganizationLevel4], [Extent26].[JobTitle] AS [JobTitle4], [Extent26].[BirthDate] AS [BirthDate4], [Extent26].[MaritalStatus] AS [MaritalStatus4], [Extent26].[Gender] AS [Gender4], [Extent26].[HireDate] AS [HireDate4], [Extent26].[SalariedFlag] AS [SalariedFlag4], [Extent26].[VacationHours] AS [VacationHours4], [Extent26].[SickLeaveHours] AS [SickLeaveHours4], [Extent26].[CurrentFlag] AS [CurrentFlag4], [Extent26].[rowguid] AS [rowguid14], [Extent26].[ModifiedDate] AS [ModifiedDate14], [Extent27].[BusinessEntityID] AS [BusinessEntityID23], [Extent27].[PasswordHash] AS [PasswordHash4], [Extent27].[PasswordSalt] AS [PasswordSalt4], [Extent27].[rowguid] AS [rowguid16], [Extent27].[ModifiedDate] AS [ModifiedDate16], [Join26].[BusinessEntityID28], [Join26].[rowguid15], [Join26].[ModifiedDate15], [Join26].[BusinessEntityID26], [Join26].[BusinessEntityID24], [Join26].[BusinessEntityID25]
            FROM    [Person].[Person] AS [Extent25]
            LEFT OUTER JOIN [HumanResources].[Employee] AS [Extent26] ON [Extent25].[BusinessEntityID] = [Extent26].[BusinessEntityID]
            LEFT OUTER JOIN [Person].[Password] AS [Extent27] ON [Extent25].[BusinessEntityID] = [Extent27].[BusinessEntityID]
            LEFT OUTER JOIN  (SELECT [Extent28].[BusinessEntityID] AS [BusinessEntityID28], [Extent28].[rowguid] AS [rowguid15], [Extent28].[ModifiedDate] AS [ModifiedDate15], [Join25].[BusinessEntityID26], [Join25].[BusinessEntityID24], [Join25].[BusinessEntityID25]
                FROM  [Person].[BusinessEntity] AS [Extent28]
                INNER JOIN  (SELECT [Extent29].[BusinessEntityID] AS [BusinessEntityID26], [Extent30].[BusinessEntityID] AS [BusinessEntityID24], [Extent31].[BusinessEntityID] AS [BusinessEntityID25]
                    FROM   [Person].[Person] AS [Extent29]
                    LEFT OUTER JOIN [HumanResources].[Employee] AS [Extent30] ON [Extent29].[BusinessEntityID] = [Extent30].[BusinessEntityID]
                    LEFT OUTER JOIN [Person].[Password] AS [Extent31] ON [Extent29].[BusinessEntityID] = [Extent31].[BusinessEntityID] ) AS [Join25] ON [Extent28].[BusinessEntityID] = [Join25].[BusinessEntityID26] ) AS [Join26] ON [Extent25].[BusinessEntityID] = [Join26].[BusinessEntityID26]
            WHERE (N'Griffin' = [Extent25].[LastName]) AND (N'Abigail' = [Extent25].[FirstName]) ) AS [Limit4]
        INNER JOIN [Sales].[PersonCreditCard] AS [Extent32] ON [Limit4].[BusinessEntityID27] = [Extent32].[BusinessEntityID]
    UNION ALL
        SELECT 
        5 AS [C1], 
        [Limit5].[BusinessEntityID29] AS [BusinessEntityID], 
        [Limit5].[BusinessEntityID30] AS [BusinessEntityID1], 
        [Limit5].[BusinessEntityID29] AS [BusinessEntityID2], 
        [Limit5].[BusinessEntityID31] AS [BusinessEntityID3], 
        [Limit5].[BusinessEntityID32] AS [BusinessEntityID4], 
        [Limit5].[BusinessEntityID33] AS [BusinessEntityID5], 
        [Limit5].[BusinessEntityID30] AS [BusinessEntityID6], 
        [Limit5].[BusinessEntityID34] AS [BusinessEntityID7], 
        [Limit5].[BusinessEntityID34] AS [BusinessEntityID8], 
        [Limit5].[PersonType5] AS [PersonType], 
        [Limit5].[NameStyle5] AS [NameStyle], 
        [Limit5].[Title5] AS [Title], 
        [Limit5].[FirstName5] AS [FirstName], 
        [Limit5].[MiddleName5] AS [MiddleName], 
        [Limit5].[LastName5] AS [LastName], 
        [Limit5].[Suffix5] AS [Suffix], 
        [Limit5].[EmailPromotion5] AS [EmailPromotion], 
        [Limit5].[AdditionalContactInfo5] AS [AdditionalContactInfo], 
        [Limit5].[Demographics5] AS [Demographics], 
        [Limit5].[rowguid17] AS [rowguid], 
        [Limit5].[ModifiedDate17] AS [ModifiedDate], 
        [Limit5].[BusinessEntityID29] AS [BusinessEntityID9], 
        [Limit5].[NationalIDNumber5] AS [NationalIDNumber], 
        [Limit5].[LoginID5] AS [LoginID], 
        [Limit5].[OrganizationLevel5] AS [OrganizationLevel], 
        [Limit5].[JobTitle5] AS [JobTitle], 
        [Limit5].[BirthDate5] AS [BirthDate], 
        [Limit5].[MaritalStatus5] AS [MaritalStatus], 
        [Limit5].[Gender5] AS [Gender], 
        [Limit5].[HireDate5] AS [HireDate], 
        [Limit5].[SalariedFlag5] AS [SalariedFlag], 
        [Limit5].[VacationHours5] AS [VacationHours], 
        [Limit5].[SickLeaveHours5] AS [SickLeaveHours], 
        [Limit5].[CurrentFlag5] AS [CurrentFlag], 
        [Limit5].[rowguid18] AS [rowguid1], 
        [Limit5].[ModifiedDate18] AS [ModifiedDate1], 
        [Limit5].[BusinessEntityID35] AS [BusinessEntityID10], 
        [Limit5].[rowguid19] AS [rowguid2], 
        [Limit5].[ModifiedDate19] AS [ModifiedDate2], 
        [Limit5].[BusinessEntityID30] AS [BusinessEntityID11], 
        [Limit5].[PasswordHash5] AS [PasswordHash], 
        [Limit5].[PasswordSalt5] AS [PasswordSalt], 
        [Limit5].[rowguid20] AS [rowguid3], 
        [Limit5].[ModifiedDate20] AS [ModifiedDate3], 
        CAST(NULL AS int) AS [C2], 
        CAST(NULL AS int) AS [C3], 
        CAST(NULL AS int) AS [C4], 
        CAST(NULL AS uniqueidentifier) AS [C5], 
        CAST(NULL AS datetime2) AS [C6], 
        CAST(NULL AS int) AS [C7], 
        CAST(NULL AS int) AS [C8], 
        CAST(NULL AS int) AS [C9], 
        CAST(NULL AS varchar(1)) AS [C10], 
        CAST(NULL AS uniqueidentifier) AS [C11], 
        CAST(NULL AS datetime2) AS [C12], 
        CAST(NULL AS int) AS [C13], 
        CAST(NULL AS int) AS [C14], 
        CAST(NULL AS int) AS [C15], 
        CAST(NULL AS int) AS [C16], 
        CAST(NULL AS int) AS [C17], 
        CAST(NULL AS varchar(1)) AS [C18], 
        CAST(NULL AS uniqueidentifier) AS [C19], 
        CAST(NULL AS datetime2) AS [C20], 
        CAST(NULL AS int) AS [C21], 
        CAST(NULL AS int) AS [C22], 
        CAST(NULL AS datetime2) AS [C23], 
        CAST(NULL AS int) AS [C24], 
        [Extent40].[BusinessEntityID] AS [BusinessEntityID12], 
        [Extent40].[PhoneNumber] AS [PhoneNumber], 
        [Extent40].[PhoneNumberTypeID] AS [PhoneNumberTypeID], 
        [Extent40].[ModifiedDate] AS [ModifiedDate4], 
        [Extent40].[BusinessEntityID] AS [BusinessEntityID13]
        FROM   (SELECT TOP (2) [Extent33].[BusinessEntityID] AS [BusinessEntityID34], [Extent33].[PersonType] AS [PersonType5], [Extent33].[NameStyle] AS [NameStyle5], [Extent33].[Title] AS [Title5], [Extent33].[FirstName] AS [FirstName5], [Extent33].[MiddleName] AS [MiddleName5], [Extent33].[LastName] AS [LastName5], [Extent33].[Suffix] AS [Suffix5], [Extent33].[EmailPromotion] AS [EmailPromotion5], [Extent33].[AdditionalContactInfo] AS [AdditionalContactInfo5], [Extent33].[Demographics] AS [Demographics5], [Extent33].[rowguid] AS [rowguid17], [Extent33].[ModifiedDate] AS [ModifiedDate17], [Extent34].[BusinessEntityID] AS [BusinessEntityID29], [Extent34].[NationalIDNumber] AS [NationalIDNumber5], [Extent34].[LoginID] AS [LoginID5], [Extent34].[OrganizationLevel] AS [OrganizationLevel5], [Extent34].[JobTitle] AS [JobTitle5], [Extent34].[BirthDate] AS [BirthDate5], [Extent34].[MaritalStatus] AS [MaritalStatus5], [Extent34].[Gender] AS [Gender5], [Extent34].[HireDate] AS [HireDate5], [Extent34].[SalariedFlag] AS [SalariedFlag5], [Extent34].[VacationHours] AS [VacationHours5], [Extent34].[SickLeaveHours] AS [SickLeaveHours5], [Extent34].[CurrentFlag] AS [CurrentFlag5], [Extent34].[rowguid] AS [rowguid18], [Extent34].[ModifiedDate] AS [ModifiedDate18], [Extent35].[BusinessEntityID] AS [BusinessEntityID30], [Extent35].[PasswordHash] AS [PasswordHash5], [Extent35].[PasswordSalt] AS [PasswordSalt5], [Extent35].[rowguid] AS [rowguid20], [Extent35].[ModifiedDate] AS [ModifiedDate20], [Join33].[BusinessEntityID35], [Join33].[rowguid19], [Join33].[ModifiedDate19], [Join33].[BusinessEntityID33], [Join33].[BusinessEntityID31], [Join33].[BusinessEntityID32]
            FROM    [Person].[Person] AS [Extent33]
            LEFT OUTER JOIN [HumanResources].[Employee] AS [Extent34] ON [Extent33].[BusinessEntityID] = [Extent34].[BusinessEntityID]
            LEFT OUTER JOIN [Person].[Password] AS [Extent35] ON [Extent33].[BusinessEntityID] = [Extent35].[BusinessEntityID]
            LEFT OUTER JOIN  (SELECT [Extent36].[BusinessEntityID] AS [BusinessEntityID35], [Extent36].[rowguid] AS [rowguid19], [Extent36].[ModifiedDate] AS [ModifiedDate19], [Join32].[BusinessEntityID33], [Join32].[BusinessEntityID31], [Join32].[BusinessEntityID32]
                FROM  [Person].[BusinessEntity] AS [Extent36]
                INNER JOIN  (SELECT [Extent37].[BusinessEntityID] AS [BusinessEntityID33], [Extent38].[BusinessEntityID] AS [BusinessEntityID31], [Extent39].[BusinessEntityID] AS [BusinessEntityID32]
                    FROM   [Person].[Person] AS [Extent37]
                    LEFT OUTER JOIN [HumanResources].[Employee] AS [Extent38] ON [Extent37].[BusinessEntityID] = [Extent38].[BusinessEntityID]
                    LEFT OUTER JOIN [Person].[Password] AS [Extent39] ON [Extent37].[BusinessEntityID] = [Extent39].[BusinessEntityID] ) AS [Join32] ON [Extent36].[BusinessEntityID] = [Join32].[BusinessEntityID33] ) AS [Join33] ON [Extent33].[BusinessEntityID] = [Join33].[BusinessEntityID33]
            WHERE (N'Griffin' = [Extent33].[LastName]) AND (N'Abigail' = [Extent33].[FirstName]) ) AS [Limit5]
        INNER JOIN [Person].[PersonPhone] AS [Extent40] ON [Limit5].[BusinessEntityID34] = [Extent40].[BusinessEntityID]) AS [UnionAll4]
    ORDER BY [UnionAll4].[BusinessEntityID] ASC, [UnionAll4].[BusinessEntityID1] ASC, [UnionAll4].[BusinessEntityID2] ASC, [UnionAll4].[BusinessEntityID3] ASC, [UnionAll4].[BusinessEntityID4] ASC, [UnionAll4].[BusinessEntityID5] ASC, [UnionAll4].[BusinessEntityID6] ASC, [UnionAll4].[BusinessEntityID8] ASC, [UnionAll4].[BusinessEntityID10] ASC, [UnionAll4].[C1] ASC

So what is the issue with this query?

There are a few things that are wrong with this query (other than it being an unreadable mess thanks to the ORM).

  1. The physical size of the query is massive for what it is doing.
  2. The number of records is more than we need.
  3. The number of tables joined is more than we need.

The Business Scenario & Issue

So as the application has become more popular, the development team has found that the request to pull back the person information is slower than the end user would like.

With a smaller number of users, this wasn’t an issue since the database had plenty of head room available so it would tackle the request and no one had any trouble.  But with the addition of more end users, we are now getting to a point where the database is struggling to keep up.

Investigation

So how do we know that this query is the issue?

Before we start performance tuning on the database, it’s very helpful to determine if that really is the bottle neck.  If you are able to debug the application locally and reproduce the issue, then that’s fantastic because then you can determine just how much time is being spent executing the query using Intellitrace and other such tools.

Once the database query is identified as a suspect of the performance problems, the next step would be to see what the query is doing.  To do this with EF, you can use SQL Profiler which will usually give you the information you require but you will need elevated trace permissions to work with a SQL trace if you wish to use this method.  The other issue is that if you have a query that is extremely large (typically anything over 530kb in size) then the profiler GUI will just show “Skipped Records” and you will be stuck.  A server side trace is not subject to this GUI limitation so if you run a server side trace then you can get the information using this way.

So if the trace & profiler method isn’t for you or doesn’t work for whatever reason and you are using EF for your ORM then you can use this little bit of code which will output the query to the output window so you can view & re-run it.

if (System.Diagnostics.Debugger.IsAttached)
    context.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

Debug Output

If you put a breakpoint at the point where the EF query runs and you have that debug statement included before you run the query (as shown in the example above) then you will see the query output in the Output window.

Diagnostic Tools

As noted above, there are other tools within Visual Studio that will give you great information around where the pain points in your application are as well such as the Diagnostic Tools window.
 
 
As you can see in the screenshots, the query that is running to get the person data is taking longer than we would like so that is where we will focus our attention.
 
 

Resolution

Once we have identified the culprit for performance woes within a specific part of the application, we are ready to go to the next step and resolve it. In some cases as with this one, there are a few ways to resolve an issue. I will outline them below.

You will want to check the performance of the query or queries using the exeuction plan, SQL Profiler, or another tool of your choosing. You want the overall impact to be as small as possible on the database so that we can speed things up.

Application Updates

With EF, there is likely a way you can restructure the code such that the query that is generated is different & perhaps more performance oriented. In our case we have a few ways we can accomplish this. Two main ways that I typically use would be to limit the data by reducing the object we get back to only the things we need or by extending the context such that the data we need will be lazy loaded as necessary. Each way will have their own pros and cons and depending on the scenario one or the other may be more beneficial for your needs.
Smaller Query
With this method, we have identified that we only need the phone number(s) of a given person so we include that in our original request to the database which still yields a smaller request, only hits the database once, and gives us the data we need. It depends on the circumstance but typically I find that the performance will be better in this method or the method below instead of the large object way of pulling back data.

            Person person;

            using (var context = new AdventureWorks2014Context())
            {
                // Write out the query & parameters so we can view everything if the debugger is attached
                if (System.Diagnostics.Debugger.IsAttached) context.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

                person = context.People
                    .Include(p => p.PersonPhones)
                    .Single(p => p.LastName == lastName && p.FirstName == firstName);
            }

            Console.WriteLine($"Person: {person.LastName}, {person.FirstName}");
            Console.WriteLine("Phone Numbers:");
            foreach (var phone in person.PersonPhones)
                Console.WriteLine($"....{phone.PhoneNumber}");

The queries that get generated with this way look like this:

exec sp_executesql N'SELECT 
    [Project2].[BusinessEntityID] AS [BusinessEntityID], 
    [Project2].[PersonType] AS [PersonType], 
    [Project2].[NameStyle] AS [NameStyle], 
    [Project2].[Title] AS [Title], 
    [Project2].[FirstName] AS [FirstName], 
    [Project2].[MiddleName] AS [MiddleName], 
    [Project2].[LastName] AS [LastName], 
    [Project2].[Suffix] AS [Suffix], 
    [Project2].[EmailPromotion] AS [EmailPromotion], 
    [Project2].[AdditionalContactInfo] AS [AdditionalContactInfo], 
    [Project2].[Demographics] AS [Demographics], 
    [Project2].[rowguid] AS [rowguid], 
    [Project2].[ModifiedDate] AS [ModifiedDate], 
    [Project2].[C1] AS [C1], 
    [Project2].[BusinessEntityID1] AS [BusinessEntityID1], 
    [Project2].[PhoneNumber] AS [PhoneNumber], 
    [Project2].[PhoneNumberTypeID] AS [PhoneNumberTypeID], 
    [Project2].[ModifiedDate1] AS [ModifiedDate1]
    FROM ( SELECT 
        [Limit1].[BusinessEntityID] AS [BusinessEntityID], 
        [Limit1].[PersonType] AS [PersonType], 
        [Limit1].[NameStyle] AS [NameStyle], 
        [Limit1].[Title] AS [Title], 
        [Limit1].[FirstName] AS [FirstName], 
        [Limit1].[MiddleName] AS [MiddleName], 
        [Limit1].[LastName] AS [LastName], 
        [Limit1].[Suffix] AS [Suffix], 
        [Limit1].[EmailPromotion] AS [EmailPromotion], 
        [Limit1].[AdditionalContactInfo] AS [AdditionalContactInfo], 
        [Limit1].[Demographics] AS [Demographics], 
        [Limit1].[rowguid] AS [rowguid], 
        [Limit1].[ModifiedDate] AS [ModifiedDate], 
        [Extent2].[BusinessEntityID] AS [BusinessEntityID1], 
        [Extent2].[PhoneNumber] AS [PhoneNumber], 
        [Extent2].[PhoneNumberTypeID] AS [PhoneNumberTypeID], 
        [Extent2].[ModifiedDate] AS [ModifiedDate1], 
        CASE WHEN ([Extent2].[BusinessEntityID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
        FROM   (SELECT TOP (2) 
            [Extent1].[BusinessEntityID] AS [BusinessEntityID], 
            [Extent1].[PersonType] AS [PersonType], 
            [Extent1].[NameStyle] AS [NameStyle], 
            [Extent1].[Title] AS [Title], 
            [Extent1].[FirstName] AS [FirstName], 
            [Extent1].[MiddleName] AS [MiddleName], 
            [Extent1].[LastName] AS [LastName], 
            [Extent1].[Suffix] AS [Suffix], 
            [Extent1].[EmailPromotion] AS [EmailPromotion], 
            [Extent1].[AdditionalContactInfo] AS [AdditionalContactInfo], 
            [Extent1].[Demographics] AS [Demographics], 
            [Extent1].[rowguid] AS [rowguid], 
            [Extent1].[ModifiedDate] AS [ModifiedDate]
            FROM [Person].[Person] AS [Extent1]
            WHERE ([Extent1].[LastName] = @p__linq__0) AND ([Extent1].[FirstName] = @p__linq__1) ) AS [Limit1]
        LEFT OUTER JOIN [Person].[PersonPhone] AS [Extent2] ON [Limit1].[BusinessEntityID] = [Extent2].[BusinessEntityID]
    )  AS [Project2]
    ORDER BY [Project2].[BusinessEntityID] ASC, [Project2].[C1] ASC',N'@p__linq__0 nvarchar(4000),@p__linq__1 nvarchar(4000)',@p__linq__0=N'Griffin',@p__linq__1=N'Abigail'

Multiple Simple Queries
When using this way, we need to leave the context available so that when the application needs the other data, the context is still available for another query to be passed to the database. The queries that get generated using this method are very small and simple however there will be multiple round trips to the database which may not be ideal.

            using (var context = new AdventureWorks2014Context())
            {
                // Write out the query & parameters so we can view everything if the debugger is attached
                if (System.Diagnostics.Debugger.IsAttached) context.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

                // Note that we aren't including any tables in this query
                var person = context.People
                    .Single(p => p.LastName == lastName && p.FirstName == firstName);

                // As a result of not including the PersonPhones table, we need to run this part of the logic within the context so that it will not fail since it will make a repeat trip to the database.
                Console.WriteLine($"Person: {person.LastName}, {person.FirstName}");
                Console.WriteLine("Phone Numbers:");
                foreach (var phone in person.PersonPhones)
                    Console.WriteLine($"....{phone.PhoneNumber}");
            }

The queries that get generated with this way look like this:

exec sp_executesql N'SELECT TOP (2) 
    [Extent1].[BusinessEntityID] AS [BusinessEntityID], 
    [Extent1].[PersonType] AS [PersonType], 
    [Extent1].[NameStyle] AS [NameStyle], 
    [Extent1].[Title] AS [Title], 
    [Extent1].[FirstName] AS [FirstName], 
    [Extent1].[MiddleName] AS [MiddleName], 
    [Extent1].[LastName] AS [LastName], 
    [Extent1].[Suffix] AS [Suffix], 
    [Extent1].[EmailPromotion] AS [EmailPromotion], 
    [Extent1].[AdditionalContactInfo] AS [AdditionalContactInfo], 
    [Extent1].[Demographics] AS [Demographics], 
    [Extent1].[rowguid] AS [rowguid], 
    [Extent1].[ModifiedDate] AS [ModifiedDate]
    FROM [Person].[Person] AS [Extent1]
    WHERE ([Extent1].[LastName] = @p__linq__0) AND ([Extent1].[FirstName] = @p__linq__1)',N'@p__linq__0 nvarchar(4000),@p__linq__1 nvarchar(4000)',@p__linq__0=N'Griffin',@p__linq__1=N'Abigail'
exec sp_executesql N'SELECT 
    [Extent1].[BusinessEntityID] AS [BusinessEntityID], 
    [Extent1].[PhoneNumber] AS [PhoneNumber], 
    [Extent1].[PhoneNumberTypeID] AS [PhoneNumberTypeID], 
    [Extent1].[ModifiedDate] AS [ModifiedDate]
    FROM [Person].[PersonPhone] AS [Extent1]
    WHERE [Extent1].[BusinessEntityID] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=3986

Indexes

Let’s assume that the “Multiple Simple Queries” method above was the fastest way to query data. Now you want to take action against the database so that queries like that will be quicker. So now we will take the queries out of the profiler and we will use SQL Server Management Studio so that we can identify bottle necks.

When we run the queries in management studio, we will want to include the Actual Execution Plan so that we can see exactly what it’s doing. And when we do so, we can see that the first query is taking up a majority of the time and there is room for improvement since it’s doing a key lookup whereas the second query is just doing a clustered index seek which is pretty ideal as far as queries are concerned.

Execution Plan

The first query has a key lookup so we will want to evaluate existing indexes to see if we can change one of the indexes to be a covering index to pick up those extra fields. In this example there is an existing index called “IX_Person_LastName_FirstName_MiddleName” which we may be able to change around for the needs of this query but for the sake of learning how to create a new index we will ignore it for now. Now we look at the columns we are using to find the record which are FirstName and LastName. And then we have the primary key which is BusinessEntityId. Those will likely be the columns we need to index. But then we also need to return back various other information about the record which will likely be included columns. From here we will typically create an index & verify that it gets used. And if not we will modify it to fit the query until it does. we would suggest not using index hints though. Those typically end poorly because what will happen is that the development team will forget about that hint being there and make changes later that suit new business needs and now that hint will either break or become antiquated causing a decrease in performance.

Here is the index that we came up with for this query based on the columns being queried and the columns being returned:

create nonclustered index IX_Person_FirstName_LastName_BusinessEntityId on Person.Person (
	FirstName asc,
	LastName asc,
	BusinessEntityID asc
)
include (
	PersonType,
	NameStyle,
	Title,
	MiddleName,
	Suffix,
	EmailPromotion,
	AdditionalContactInfo,
	Demographics,
	rowguid,
	ModifiedDate
)

And that index does in fact yield the result we are looking for be because now both queries being executed are doing index seeks as you can see in the screenshot.

Execution Plan After Index Change

At this point, you will want to go back to the application and re-run the test scenarios to review the impact you have made to the performance of the application. If possible, it would be ideal to push load against the application so that you can evaluate if the bottleneck is in fact resolved or not. If you are not able to do that locally then you will want to just verify that the application is running quicker than before. To help with this, SQL Profiler can give you total duration metrics for SQL queries. And Intellitrace and Diagnostic Tools in Visual Studio can give you overall run time metrics to use before deploying your code.

If you are having trouble trying to determine what to create for your index, you could use the Database Tuning Advisor tool but any recommendations that it gives should be taken with a grain of salt because it doesn’t look to see if existing schema can be modified to fit the needs of the new query so you could end up creating indexes that are extremely close to exisitng indexes which is not ideal.

When to stop?

When doing any kind of performance optimization, it’s always important to know what your goal is.  Typically, it’s unlikely you will have a documented SLA for the one particular area of the application you are working with.  That said, you will likely need to determine what is “good enough” to complete the task of resolving the slow down.

There is no definitive answer here and your mileage will vary. The reason for that is because your application & user expectations will differ drastically depending on the need and other factors.  For example, if we are talking about a web application which will have many end users, we will want to make database traffic as quick as reasonably possible so that it will scale out without having users wait for a heavily loaded database to return results.  But on the other hand, if we are talking about a background job that runs once a week then making the database call only take 5 milliseconds to run isn’t quite so important anymore.

My general rule of thumb that I try to strive for in this area is to cut the run time down by 90% if at all possible. In this example, we were able to cut down the run time signifigantly so we were able to meet the need. That said, if we needed to take it a step further the next step(s) I would take would be to start reviewing the statistics of the data we are querying and then we could take further action. After that, then we could start to take more drastic steps like restructing portions of the schema or using a custom stored procedure in place of EF or a host of other avenues we could explore.

Profiler Results

Using SQL Server Profiler we can see our changes made the impact we were looking for and we got an overall performance gain of over 90%. So at this point we are done with our optimizations.

Conclusion

That is a very brief introduction into how I go about working on SQL performance issues as a .Net developer.  In the examples I was very specific with the use of an ORM but the concepts apply elsewhere.  The resolution was also reasonably simple and things can get more complex from here. The general flow that you run through would still be similar regardless of the scenario.  We will explore more SQL related topics in future blog posts as well.

All of the code used for this example can be downloaded from GitHub.

Leave a Reply

You must be logged in to post a comment.

To get started on your custom software solution, call 1-888-421-1155.