Planning a Microsoft SQL Server installation

This blog post is a guideline and checklist about installing a Microsoft SQL Server database server.

Evaluation of the installation and the hardware requirements

Choose the SQL Server version which supports the features you need.

Hardware requirements:

Choosing the right hardware size for database servers is in my opinion challenging. My advice is to choose an extensible system and to start modest, but realistic. Usually you can take a look at the data volume that needs to be served through the database, to get a first impression. If you have less than 50GB of data you can probably keep your server pretty small, when you have TB’s of data you probably have to scale out or use a very high end machine.

When you have big loads of data you of course need memory and CPU power to work with that data, but more importantly you want to spread this data out over multiple disks to reduce your read & write bottleneck. It is better to use multiple small disk than a few giant disks. Choosing the right ‘raid’ disk type can be important as well, as the influence not only your safety against disk failure, but also your read and write speed.

Memory and CPU become more important when you have a lot of concurrent users. CPU in order to serve them simultaneously, and memory to keep results in cache so you can reuse results over multiple users.

Software requirements:

  • .NET Framework 3.5 SP1. Used by the Database Engine, Reporting Services, Replication, Master Data Services, and SQL Server Management Studio. This software is not installed by the SQL Server setup.
  • .NET Framework 4.0. Required for SQL Server 2012 in general. This software is included in the SQL Server setup.
  • Windows PowerShell 2.0. Required for SQL Server 2012 in general. This software is not installed by the SQL Server setup. But is included in the Windows Server installation by default (since 2008 R2 version).
  • Internet Explorer 7 or later: Required for Microsoft Management Console, SQL Server Data Tools and HTML help. This software is included in the Windows Server installation (since 2008 version).

Preinstall checks

  • Review if the right hardware is installed in the server.
  • Review OS and driver versions.
  • Check the Windows event viewer for recent errors and warnings.

Design the right installation

During installation:

  • Install just enough components. Installing more than you need means you are using up more disk space, you will have to update components that you will not use (which might require you to reboot) and more importantly you can create unnecessary security leaks (a door that not exists cannot be opened).
  • Choose a right collation. Use the default unless you have a reason to go different. Changing collation afterwards is painful. Usually you also want your databases and servers to use the same collation.
  • Choose the right service accounts for the components with just enough rights. Running every service with a different account is a secure practice.
  • Choose the right location for the SQL Server files. SQL Server system files can be on the same disk as the OS, they are only accessed when you started SQL Server. Place the database log file on a disk that is just used for that log. Place the database files on a disk that is just used for database files. Place the TempDB one of your fastest disks, and just use that disk for the TempDB (the TempDB is used in a lot of operations).

Post install checks

  • Review available updates for SQL Server. Get the latest service pack. Review cumulative updates and hotfixes and decide if they are worth it.
  • Configure SQL Server. Configure the maximum memory usage. Set the TempDB size large enough so it does not have to grow (often). Create multiple TempDB files. Configure the initial size, auto-growth settings and recovery model of the model database Configure a default fill factor for indexes.
  • Run the best practice analyzer.
  • Enable your backup plans.
  • Document the installation.

,

Leave a comment

Dynamic arbitrary value banding

In this post I will describe how you can implement dynamic arbitrary value banding.

What is arbitrary value bandings?

Sometimes users want to slice or filter their data based on numeric (fact) values. But if you would slice a fact table based on a fact that is a continues number you will get a result like this:

 

 

 

 

 

 

 

 

 

This is ofcourse not verry useful. This is solved with arbitrary value bandings:

 

 

 

 

Now I will elaborate on how you can populate a value banding dimension table and link it with a fact table on a dynamic way.

1. Fill a dimension table with banding values

First you have to populate the value banding dimension. You should let a user define the banding groups (for example using an Excel sheet, SharePoint list or Master Data Services model) and load it into your dimension. You will have to define atleast the name of the banding group, a minimum range and a maximum range.

My table has the folowing structure and data:


 

 

 

 

2. Set the foreign key inside your fact table.

In order to set the correct foreign key relationships, from the fact table to the banding dimension, you will have to load the fact table with a placeholder as foreign key, and after that update the foreign key to the correct banding range.

I use this model for the example:

 

 

 

 

 

 

 

 

 

In order to set the right value banding foreign key I wrote the folowing SQL algorithm:

/* We need the individual sales order. This requires us to aggregate the order lines */

SELECT FK_SalesOrderInfo, ROUND(SUM(GrossProfit),0) AS SumOfGrossProfit

INTO #TempSalesOrders

FROM dbo.FactSales

GROUP BY FK_SalesOrderInfo

/* Use this query to view intermediate results */

–SELECT FK_SalesOrderInfo, V.PK_ValueBanding, SumOfGrossProfit

–FROM #TempSalesOrders AS S INNER JOIN DimValueBanding AS V

–ON (S.SumOfGrossProfit >= V.BandingMinRange AND S.SumOfGrossProfit <= V.BandingMaxRange)

/* Here we do the following:

1. Use the SalesOrders #TempTable and DimValueBanding to add a Value Band key to each sales order

2. Update the foreign key to the DimValueBanding table in the FactSales table based on the set build in step 1 */

UPDATE

[dbo].[FactSales]

SET

FactSales.[FK_ValueBanding]=ValueBands.PK_ValueBanding

FROM FactSales INNER JOIN

( SELECT FK_SalesOrderInfo,V.PK_ValueBanding

FROM #TempSalesOrders AS S INNER JOIN DimValueBanding AS V

ON S.SumOfGrossProfit >= V.BandingMinRange AND S.SumOfGrossProfit <= V.BandingMaxRange) AS ValueBands

ON FactSales.FK_SalesOrderInfo=ValueBands.FK_SalesOrderInfo

DROP TABLE #TempSalesOrders     

GO

Now you are done!

, , ,

1 Comment

Market Basket Analysis with SQL

I recently read about ‘affinity grouping’ (populairly known as market basket analysis) in The Data Warehouse Toolkit by Ralph Kimball. This interested me into finding an algorithm in SQL to get your usual fact table data into a affinity grouping table.

Affinity grouping gives you insight into what events correlate together. In my example I will try to get insight into what products are often sold together in the AdventureWorks example database.

As a starting point I have a transaction fact table:

 

 

 

 

 

 

 

 

 

 

This fact table measures sales quantity and gross profit per sold item. The dimensions are pretty straight forward, but it’s important to emphasise that the Sales Order Info dimension containts the sales order numbers and sales order lines.

Our goal is to get the data inside the following affinity grouping model:

 

 

 

 

 

 

 

 

 

 

This model will tell us how many a product(A) is sold in combination with product(B). The model is a daily snapshot and can also be sliced  and rolled up by it’s dimension attributes.

To get my data from the transaction fact table into the affinity grouping table I thought out the following algorithm:

1. Select the order lines of a single order. Which should generate a set like this:

FK_OrderDate FK_SalesChannel FK_SpecialOffer FK_Product FK_SalesOrderInfo OrderQty GrossProfit
20050701 1 -1 270 8 3 1258.376700
20050701 1 -1 268 8 1 419.458900
20050701 1 -1 259 8 1 874.794000
20050701 1 -1 230 8 1 183.938200

2.Select a single product from the set.  In this example we take ProductID 270.

3. Correlate the product with all the other products from the order set. This should result into the following set:

FK_OrderDate FK_SalesChannel FK_SalesOrderInfo FK_SpecialOffer FK_ProductA FK_ProductB Order Qty A Order Qty B Gross   Profit A Gross   Profit B
20050701 1 8 -1 270 268 3 1 1258.376700 419.458900
20050701 1 8 -1 270 259 3 1 1258.376700 874.794000
20050701 1 8 -1 270 230 3 1 1258.376700 183.938200

Now we have a set of products(B) that are sold in combination with product A. We have registered the sales quantity and gross profit. This gives us the ability to find the combinations that are the most profitable.

4. Save this result set.

5. Repeat step 2-4 for all products in the order.

6.Repeat steps 1-5 for all other orders.

7. Sum the Order Qty A, Order Qty B, Gross Profit A, Gross Profit B of the entire set grouped by order date, sales channel, special offer, product A, product B and save it as a final result into your affinity grouping model.

I wrote step 1-6 in T-SQL like this:


--Declare variables
DECLARE @FK_SalesOrderInfo AS INT
DECLARE @OrientationProductID AS INT


--Build a list of baskets that we will loop
SELECT DISTINCT FK_SalesOrderInfo
INTO #SalesOrderOrientation
FROM FactSales


--Every time the first loop iterates it will take one salesorder out of the collection
SET @FK_SalesOrderInfo = (SELECT TOP(1) FK_SalesOrderInfo FROM #SalesOrderOrientation)
DELETE TOP(1) FROM #SalesOrderOrientation


While (@FK_SalesOrderInfo IS NOT NULL)
Begin


--Get the data of this basket
SELECT * into #tempBasket FROM
(
SELECT FK_OrderDate, FK_SalesChannel, FK_SpecialOffer, FK_Product, FK_SalesOrderInfo, OrderQty, GrossProfit FROM FactSales
WHERE FK_SalesOrderInfo = @FK_SalesOrderInfo
) AS Basket


--Get a list of products that are inside this basket.
--We use this list of products to determine what products from the basket we still have to process.
SELECT FK_Product INTO #ProductOrientation
FROM #tempBasket


--Every time the second loops interates it will take one product out of the collection. The delete happens at the end of the loop.
SET @OrientationProductID = (SELECT TOP(1) FK_Product FROM #ProductOrientation)


While @OrientationProductID IS NOT NULL
Begin


--This query joins the product that is in the @OrientationProductID variable with all other products inside the basket.
--On this way it creates a set of correlated products. This set is inserted into a table
INSERT INTO ProductCorrelations (FK_OrderDate, FK_SalesChannel, FK_SpecialOffer, PO.FK_SalesOrderInfo, FK_ProductA, OrderQtyA, GrossProfitA, CP.FK_ProductB, CP.OrderQtyB, CP.GrossProfitB)
SELECT LeadingProduct.FK_OrderDate, LeadingProduct.FK_SalesChannel, LeadingProduct.FK_SpecialOffer, CorrelatedProducts.FK_SalesOrderInfo,
LeadingProduct.FK_Product AS FK_ProductA, LeadingProduct.OrderQty AS OrderQtyA, LeadingProduct.GrossProfit AS GrossProfitA,
CorrelatedProducts.FK_Product AS FK_Product, CorrelatedProducts.OrderQty AS OrderQtyB, CorrelatedProducts.GrossProfit AS GrossProfitB
FROM #tempBasket AS LeadingProduct INNER JOIN #tempBasket AS CorrelatedProducts
ON LeadingProduct.FK_SalesOrderInfo = CorrelatedProducts.FK_SalesOrderInfo
WHERE LeadingProduct.FK_Product = @OrientationProductID AND CorrelatedProducts.FK_Product != @OrientationProductID


DELETE FROM #ProductOrientation WHERE FK_Product = @OrientationProductID
SET @OrientationProductID = (SELECT TOP(1) FK_Product FROM #ProductOrientation)
End


SET @FK_SalesOrderInfo = (SELECT TOP(1) FK_SalesOrderInfo FROM #SalesOrderOrientation)
DELETE TOP(1) FROM #SalesOrderOrientation
DROP TABLE #tempBasket
DROP TABLE #ProductOrientation
END

DROP TABLE #SalesOrderOrientation

You now have have a set of all products that are sold together. You now just have to aggregate the results before inserting them into your final MarketBasketAnalysis table.

We do this with the following T-SQL statement:

TRUNCATE TABLE MarketBasketAnalysis
GO
INSERT INTO MarketBasketAnalysis ([FK_OrderDate], [FK_SalesChannel], [FK_SpecialOffer], [FK_ProductA], [FK_ProductB], [OrderQtyA], [OrderQtyB], [GrossProfitA], [GrossProfitB])
SELECT [FK_OrderDate]
,[FK_SalesChannel]
,[FK_SpecialOffer]
,[FK_ProductA]
,[FK_ProductB]
,SUM([OrderQtyA]) AS OrderQtyA
,SUM([OrderQtyB]) AS OrderQtyB
,SUM([GrossProfitA]) AS GrossProfitA
,SUM([GrossProfitB]) AS GrossProfitB
FROM [dbo].[ProductCorrelations]
GROUP BY
[FK_OrderDate]
,[FK_SalesChannel]
,[FK_SpecialOffer]
,[FK_ProductA]
,[FK_ProductB]

And we are done! We can now see what products combinations are selling most often together. This information can give you better judgment on what the effect of special offers will be, what products go well into packaged deals, how to arange your store layout, or how to advertise products on your webshop.

Concerns about the algorithm

The algorithm took about 12 minutes to complete on my laptop, which is acceptable. But the product catalogue and sales data set of AdventureWorks is not that big, I can imagine that this algorithm might take to long for the data of example a supermarket.  The AdventureWorks database has 500+ products and 120.000+ order lines. This resultat into 1.984.276 sales combinations. As you either increase the number of products or the number of order lines the number of sales combinations will increase significantly.

Performance gains can be reached by reducing disk I/O by keeping more data in memory, do incremental loads,  reduce the amount of products you will evaluate (take the most profitable products) or make a smarter algorithm :-).

If you have any suggestions about this feel free to post a comment!

, , , ,

1 Comment

Append data to a raw file using a for each loop container in SSIS

Recently I had an interesting problem in Microsoft SQL Server Integration Services (SSIS). I had to append data to a raw file in a for each loop. A raw file destination component can be configured to have the following behavior: Append, Create always, Create once, Truncate and append. None of these options will let you truncate the file the first time the loop runs and after it only append to the file. Unfortunately SSIS has no task to truncate a raw file without writing to it. But there is a work around! I found it after spending some time doing Google searches. Because the work around is not so well know or easy to find I decided to blog about it.

How to do it (short)?

Create a Data Flow Task (DFT) before the For Each Loop Container. In the DFT create either a flat file source or database source with the same metadata as the raw file has to get. Connect the source to a Raw File Destination that writes to the raw file and set it on ‘Create always’. Now the Raw File will always be empty before the For Each Loop and the For Each Loop can append to it.

How to do it (long)?

For example I want to load data from all sales tables in the AdventureWorks database into a raw file using a for each loop.

1. Create a database with two tables were you will prepare your metadata.

2. Populate the SalesTables table with tables which you want to query in the for each loop. Keep the RawFileSalesMeta table empty, we only want to prepare the right metadata here (column names and datatype).

3. Load the content in the TableNames table into a variable in SSIS. To do this you need to create an variable of the type Object and query to data into it with an Execute SQL Task.

Create the SSIS variable:

Write the following query:

SELECT TableName FROM SalesTables

Set the result set of the Execute SQL Task on Full result set. And set up the right Result Set – Variable mapping.

4. Create a DFT, we will prepare an empty raw file in this step.

Add an OLE DB Source component with the following query (I use TOP (0) to be sure no actual data gets loaded, I just want the metadata here):

SELECT TOP(0) [ProductKey]
,[OrderDateKey]
,[DueDateKey]
,[ShipDateKey]
,[PromotionKey]
,[CurrencyKey]
,[SalesTerritoryKey]
,[SalesOrderNumber]
,[SalesOrderLineNumber]
,[RevisionNumber]
,[OrderQuantity]
,[UnitPrice]
,[ExtendedAmount]
,[UnitPriceDiscountPct]
,[DiscountAmount]
,[ProductStandardCost]
,[TotalProductCost]
,[SalesAmount]
,[TaxAmt]
,[Freight]
,[CarrierTrackingNumber]
,[CustomerPONumber]
FROM [AdventureWorksMetadata].[dbo].[RawFileSalesMeta]

Add a Raw File Destination component and set the Write Option on Create Always. Go to the columns tab and make sure all columns are checked.

Execute this DFT once to create the Raw File now. We will need it’s metadata definition later on.

5. Set up the For Each Loop container and create a dynamic query.

Create a SSIS variable called Table.

Add a for each loop container to your control flow and set up the Collection tab like this:

Set up the Variable Mappings to write a table name to the variable each time the loop enumerates.

Create a SSIS variable of the data type string. This variable which will hold the query. Add the following expression to the variable:

“SELECT [ProductKey]
,[OrderDateKey]
,[DueDateKey]
,[ShipDateKey]
,[PromotionKey]
,[CurrencyKey]
,[SalesTerritoryKey]
,[SalesOrderNumber]
,[SalesOrderLineNumber]
,[RevisionNumber]
,[OrderQuantity]
,[UnitPrice]
,[ExtendedAmount]
,[UnitPriceDiscountPct]
,[DiscountAmount]
,[ProductStandardCost]
,[TotalProductCost]
,[SalesAmount]
,[TaxAmt]
,[Freight]
,[CarrierTrackingNumber]
,[CustomerPONumber]
FROM [AdventureWorksDW2008R2].[dbo].” + @[User::Table]

Assign the value ‘FactInternetSales’ to the variable Table, so we can validate the external metadata with a real query (that is prepared in the query variable).

Now add a DFT to the For Each Loop container

Add an OLE DB Source component in the new DFT and configure it so it gets the query from the variable.

Add a Raw File Destination to the DFT and configure it to append.

Now everything is set. The package will query each table you add to the SalesTables table (though the metadata has to be the same).

, ,

Leave a comment

Hello world!

I decided to start blogging about things that i find interesting in the IT world. This can mean any subject from the IT, but as I work as a BI/DWH consultant that will naturally be the main subject.

1 Comment

Create your own website, free on WordPress.com.Create your own website.
Start free