Wednesday, February 11, 2015

SQL: WHERE Clause

In SQL the WHERE clause is the most common join you will see, it relates one or more tables together. For example you want to get the employeeis territory information in the Northwind database but you there are all in different tables.

As you can see from the above diagram the employee information is in the Employees table, while a linking table is used to link the employee to the territory in the EmployeeTerritories, and then there's the Territories table which contains the actual name of the territory in the Territory. How do we proceed to retrieve this information? With a WHERE clause of course. The WHERE clause allows us to retrieve information from all these tables and combine them into one result set. Here is the query that you would write with the WHERE clause:

SELECT e.FirstName + ' ' + e.LastName AS Name, t.TerritoryDescription,t.TerritoryID
FROM Employees e,Territories t, EmployeeTerritories et
WHERE e.EmployeeID = et.EmployeeID
AND et.TerritoryID = t.TerritoryID
The query above joins the Employees table to the EmployeesTerritories table matching the two tables by the column EmployeeID, then after we get the records with matching records between those two tables, we and the word "AND" to add additional joins based on our first join. This time we want to match the TerritoryID in the EmployeesTerritories table with the TerritoryID column in the Territories which contains the TerritoryDescription field that we wanted. So with the WHERE clause we were able to work with three tables at once in one query.

You can filter the results even more by looking adding more filtering conditions in the WHERE clause.
Let's say you want to get only employees who belongs to the Boston territory, from the first query you know that Boston has a TerritoryID of 02116. So to get the employees who belongs to the Boston territory you would write the query like the one below:


SELECT e.FirstName + ' ' + e.LastName AS Name, t.TerritoryDescription,t.TerritoryID
FROM Employees e,Territories t, EmployeeTerritories et
WHERE e.EmployeeID = et.EmployeeID
AND et.TerritoryID = t.TerritoryID
AND t.TerritoryID = 02116
Here are the results:

ASP.NET : Stored Procedures (INSERT), Insert a new Northwind Product Part 2

Today we will be calling a stored procedure in SQL Server that we've created earlier in this blog call addProduct.  The stored procedure takes the following input parameters.


1.  First you need the namespaces

using System.Web.Configuration;
using System.Data.SqlClient;
using System.Data;

2. Then get the Northwind connection string value from the Web.config file
string connectString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].
ConnectionString;

3. Now call the stored procedure and output the result from the SqlDataReader
  using (SqlConnection conn = new SqlConnection(connectString))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "addProduct";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;

SqlParameter productName = new SqlParameter("@ProductName", "Teh");
productName.SqlDbType = SqlDbType.NVarChar;
productName.Direction = ParameterDirection.Input;
cmd.Parameters.Add(productName);

SqlParameter supplerID = new SqlParameter("@SupplierID", 1);
supplerID.SqlDbType = SqlDbType.Int;
supplerID.Direction = ParameterDirection.Input;
cmd.Parameters.Add(supplerID);

SqlParameter categoryID = new SqlParameter("@CategoryID", 1);
categoryID.SqlDbType = SqlDbType.Int;
categoryID.Direction = ParameterDirection.Input;
cmd.Parameters.Add(categoryID);

SqlParameter quantityPerUnit = new SqlParameter("@QuantityPerUnit", "20 boxes of 12 oz.");
quantityPerUnit.SqlDbType = SqlDbType.NVarChar;
quantityPerUnit.Direction = ParameterDirection.Input;
cmd.Parameters.Add(quantityPerUnit);

SqlParameter unitPrice = new SqlParameter("@UnitPrice", 12.99);
unitPrice.SqlDbType = SqlDbType.Money;
unitPrice.Direction = ParameterDirection.Input;
cmd.Parameters.Add(unitPrice);

SqlParameter unitsInStock = new SqlParameter("@UnitsInStock", 6);
unitsInStock.SqlDbType = SqlDbType.SmallInt;
unitsInStock.Direction = ParameterDirection.Input;
cmd.Parameters.Add(unitsInStock);

SqlParameter reorderLevel = new SqlParameter("@ReorderLevel", 2);
reorderLevel.SqlDbType = SqlDbType.SmallInt;
reorderLevel.Direction = ParameterDirection.Input;
cmd.Parameters.Add(reorderLevel);

SqlParameter discontinued = new SqlParameter("@Discontinued", false);
discontinued.SqlDbType = SqlDbType.Bit;
discontinued.Direction = ParameterDirection.Input;
cmd.Parameters.Add(discontinued);

int rowsAffected = cmd.ExecuteNonQuery();

Response.Write(rowsAffected);
}
In the above code you add the parameters required by the addProduct stored procedure. You specify the name, type, and value. Then add it to command object's parameters list. Then you execute the ExecuteNonQuery() method because you are not get a resultset back or a scalar value. The ExecuteNonQuery() method returns an int value, usually the rows that were affected value.

Blogs In the T-SQL Series:

Tuesday, February 10, 2015

SQL: Subqueries













The easiest and simplest way to explain what a subquery is to say that it's a query within a query. For example if you want to get the employee that belongs to specific territory in the Northwind database without a join, you would have to use a subquery. Like the following subquery.

SELECT EmployeeID, (FirstName + ' ' + LastName) AS Name
FROM Employees
WHERE EmployeeID IN (SELECT EmployeeID
FROM EmployeeTerritories
WHERE TerritoryID=01581)


Things You Should Know About Subqueries:
  • They are not the most efficient performance wise
  • You can only retrieve a single column in the subquery, retrieving multiple columns will throw an error
Another way to use subqueries is to use it with Aggregate functions like the query below, which gets the average price for the category with ID value of 1:

SELECT CategoryName,
(SELECT AVG(UnitPrice)
FROM Products WHERE CategoryID = 1) AS AvgPrice
FROM Categories
WHERE CategoryID = 1






SQL: Subqueries

The easiest and simplest way to explain what a subquery is to say that it's a query within a query. For example if you want to get the employee that belongs to specific territory in the Northwind database without a join, you would have to use a subquery. Like the following subquery.

SELECT EmployeeID, (FirstName + ' ' + LastName) AS Name
FROM Employees
WHERE EmployeeID IN (SELECT EmployeeID
FROM EmployeeTerritories
WHERE TerritoryID=01581)

Things You Should Know About Subqueries:
  • They are not the most efficient performance wise
  • You can only retrieve a single column in the subquery, retrieving multiple columns will throw an error
Another way to use subqueries is to use it with Aggregate functions like the query below, which gets the average price for the category with ID value of 1:

SELECT CategoryName,
(SELECT AVG(UnitPrice)
FROM Products WHERE CategoryID = 1) AS AvgPrice
FROM Categories
WHERE CategoryID = 1


T-SQL: Stored Procedure (INSERT), INSERT A New Product In Northwind Part 1

Here is how you would create a stored procedure to insert a new record into the Products table in the Northwind database.

USE Northwind
GO
CREATE PROCEDURE dbo.addProduct(
@ProductName nvarchar(40),
@SupplierID int = null, --default is null
@CategoryID int = null,
@QuantityPerUnit nvarchar(20) = null,
@UnitPrice money = null,
@UnitsInStock smallint = null,
@UnitsOnOrder smallint = null,
@ReorderLevel smallint = null,
@Discontinued bit)
AS
INSERT INTO Products(ProductName,
SupplierID,
CategoryID,
QuantityPerUnit,
UnitPrice,
UnitsInStock,
UnitsOnOrder,
ReorderLevel,
Discontinued)
VALUES(@ProductName,
@SupplierID,
@CategoryID,
@QuantityPerUnit,
@UnitPrice,
@UnitsInStock,
@UnitsOnOrder,
@ReorderLevel,
@Discontinued)
GO

When you see a parameter with the = null, it means the field can have a null value. Since the ProductID is auto incremented you don't include it. The data types must match the fields in the database.
Here is how you would execute the stored procedure
EXEC dbo.addProduct @ProductName ='Teh',
@SupplierID = DEFAULT,
@CategoryID = DEFAULT,
@QuantityPerUnit ='20 boxes x 12 oz.',
@UnitPrice = 12.99,
@UnitsInStock = 5,
@UnitsOnOrder = 6,
@ReorderLevel = DEFAULT,
@Discontinued = 0

When you see a parameter with = DEFAULT it means to assign the DEFAULT value to the field, if the execution is completed successfully you should see the message.

(1 row(s) affected)

Blogs In the T-SQL Series:

Monday, February 9, 2015

SQL: GROUP BY And HAVING














SQL GROUPING allows you to segregate data into groups so that you can work on it separately from the rest of the table records. Let's say you want to get the number of products in a category in the Northwind database Products table. You would write the following query:
 SELECT COUNT(*) NumberOfProductsByCategory
FROM Products
GROUP BY CategoryID
The query above gives you the following results:

The query gives you the number of products in each category, however it's not very useful. You don't really know what category the count is for in each record. You might want to try to change the query into something like this:
SELECT CategoryID,COUNT(*) NumberOfProductsByCategory
FROM Products
GROUP BY CategoryID

The above query is more useful the preceding one, however it only gives you the CategoryID number not the CategoryName in the Categories table. Being the perfectionist that you are you say to yourself, I can do better. "Yes, I can". I think that was a campaign slogan. So you try a join like this:
SELECT c.CategoryName,c.CategoryID
RIGHT JOIN Categories AS c ON c.CategoryID = p.CategoryID
The above query joins the Categories table with the Products table to be able to select from both tables therefore giving the ability to select the CategoryName field.
You probably think to yourself, hey if I can get the CategoryName with the RIGHT JOIN I can just add the GROUP BY filter and be done with it. Yah, my Shaolin Master from the SQL Wing will be proud. So you write the following query:
SELECT c.CategoryName,p.CategoryID,COUNT(*) AS NumberOfProductsByCategory
FROM Products p
RIGHT JOIN Categories AS c ON p.CategoryID = c.CategoryID
GROUP BY c.CategoryID
But behold you get an error! OMG! !@@##$%##$% Luckily your Shaolin Master walked into your room and saw that you were distraught. Your master ask you why you so distraught? You tell the Master, I don't understand, the join was working by itself but when I add the GROUP BY it throws me this stupid SQL error:

Column 'Categories.CategoryName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Your master says, if the expression is used in the SELECT statement then the same expression must be used in the GROUP BY part of the statement. You think ah ha! I can just add the columns in the SELECT list of columns to the GROUP BY filtering in the query. So you write:
SELECT c.CategoryID,c.CategoryName,COUNT(*) AS NumberOfProductsByCategory 
FROM Products p
RIGHT JOIN Categories AS c ON c.CategoryID = p.CategoryID
GROUP BY c.CategoryID,c.CategoryName
And like magic the result came to your screen. Tears of joy were streaming down your face because you've gotten the results that you were looking for.


Option 2: You can select what you want from the Products table and then use the GROUP BY in another select in a RIGHT JOIN to the get the COUNT() for each category. You will get the correct results with this query as well.
SELECT c.CategoryID,c.CategoryName,NumberOfProductsByCategory
FROM Categories AS c
RIGHT JOIN (SELECT CategoryID, COUNT(*) AS NumberOfProductsByCategory
FROM Products GROUP BY CategoryID) AS p ON p.CategoryID = c.CategoryID


As you have noticed the GROUP BY queries are missing the WHERE clause. What happened to the powerful WHERE clause? The reason we don't have a where clause is because WHERE does not work with GROUP BY results. That's where HAVING comes in. HAVING takes care of the filtering of the GROUP BY, while the WHERE clause takes care of the non GROUP BY results. For example let's say you want to get the categories with the most expensive products you can write a query that filters the product price with the WHERE clause and then filter the group data with the HAVING clause. You can write the following query to get the expensive products and their categories:
SELECT c.CategoryID,c.CategoryName,COUNT(*) AS NumberOfProductsByCategory 
FROM Products p
RIGHT JOIN Categories AS c ON c.CategoryID = p.CategoryID
WHERE p.UnitPrice > 10
GROUP BY c.CategoryID,c.CategoryName
HAVING COUNT(*) >=5
ORDER BY NumberOfProductsByCategory DESC
The query above gets products that are more than $10, and gets the categories that has more than 9 products. The two filters are separate but they work together nicely with the WHERE and HAVING clause.

SQL: GROUP BY And HAVING

SQL GROUPING allows you to segregate data into groups so that you can work on it separately from the rest of the table records. Let's say you want to get the number of products in a category in the Northwind database Products table. You would write the following query:
 SELECT COUNT(*) NumberOfProductsByCategory
FROM Products
GROUP BY CategoryID
The query above gives you the following results:

The query gives you the number of products in each category, however it's not very useful. You don't really know what category the count is for in each record. You might want to try to change the query into something like this:
SELECT CategoryID,COUNT(*) NumberOfProductsByCategory
FROM Products
GROUP BY CategoryID

The above query is more useful the preceding one, however it only gives you the CategoryID number not the CategoryName in the Categories table. Being the perfectionist that you are you say to yourself, I can do better. "Yes, I can". I think that was a campaign slogan. So you try a join like this:
SELECT c.CategoryName,c.CategoryID
RIGHT JOIN Categories AS c ON c.CategoryID = p.CategoryID
The above query joins the Categories table with the Products table to be able to select from both tables therefore giving the ability to select the CategoryName field.
You probably think to yourself, hey if I can get the CategoryName with the RIGHT JOIN I can just add the GROUP BY filter and be done with it. Yah, my Shaolin Master from the SQL Wing will be proud. So you write the following query:
SELECT c.CategoryName,p.CategoryID,COUNT(*) AS NumberOfProductsByCategory
FROM Products p
RIGHT JOIN Categories AS c ON p.CategoryID = c.CategoryID
GROUP BY c.CategoryID
But behold you get an error! OMG! !@@##$%##$% Luckily your Shaolin Master walked into your room and saw that you were distraught. Your master ask you why you so distraught? You tell the Master, I don't understand, the join was working by itself but when I add the GROUP BY it throws me this stupid SQL error:

Column 'Categories.CategoryName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Your master says, if the expression is used in the SELECT statement then the same expression must be used in the GROUP BY part of the statement. You think ah ha! I can just add the columns in the SELECT list of columns to the GROUP BY filtering in the query. So you write:
SELECT c.CategoryID,c.CategoryName,COUNT(*) AS NumberOfProductsByCategory 
FROM Products p
RIGHT JOIN Categories AS c ON c.CategoryID = p.CategoryID
GROUP BY c.CategoryID,c.CategoryName
And like magic the result came to your screen. Tears of joy were streaming down your face because you've gotten the results that you were looking for.


Option 2: You can select what you want from the Products table and then use the GROUP BY in another select in a RIGHT JOIN to the get the COUNT() for each category. You will get the correct results with this query as well.
SELECT c.CategoryID,c.CategoryName,NumberOfProductsByCategory
FROM Categories AS c
RIGHT JOIN (SELECT CategoryID, COUNT(*) AS NumberOfProductsByCategory
FROM Products GROUP BY CategoryID) AS p ON p.CategoryID = c.CategoryID


As you have noticed the GROUP BY queries are missing the WHERE clause. What happened to the powerful WHERE clause? The reason we don't have a where clause is because WHERE does not work with GROUP BY results. That's where HAVING comes in. HAVING takes care of the filtering of the GROUP BY, while the WHERE clause takes care of the non GROUP BY results. For example let's say you want to get the categories with the most expensive products you can write a query that filters the product price with the WHERE clause and then filter the group data with the HAVING clause. You can write the following query to get the expensive products and their categories:
SELECT c.CategoryID,c.CategoryName,COUNT(*) AS NumberOfProductsByCategory 
FROM Products p
RIGHT JOIN Categories AS c ON c.CategoryID = p.CategoryID
WHERE p.UnitPrice > 10
GROUP BY c.CategoryID,c.CategoryName
HAVING COUNT(*) >=5
ORDER BY NumberOfProductsByCategory DESC
The query above gets products that are more than $10, and gets the categories that has more than 9 products. The two filters are separate but they work together nicely with the WHERE and HAVING clause.

Sunday, February 8, 2015

SQL: Wildcard Search With The LIKE Operator













Equality searches are great and efficient when you want exact matches or range of values. However, there will be times when you need to search a text field for not so perfect matches, perhaps a partial match is needed. Certain scenarios requires to search for patterns, such as an email address. That's when the LIKE operator is useful in SQL. The only caveat is that LIKE operators can only work with text fields. Examples: 1. A word/text with a % at the end, searches for all the records that begins with the letters before the percent sign

SELECT ProductName,UnitPrice
FROM Products
WHERE ProductName LIKE 'Chef%'

The query above returns all the records in the Products table that begins with the word "Chef"



 2. A word with % sign on both ends, means that the result will be any records that contains the enclosed word/text within the % sign

SELECT ProductName,UnitPrice
FROM Products
WHERE ProductName LIKE '%Hot%'

The query above searches for any records that contains the word "Hot" in the ProductName field. It brings back all the records that contains the word "Hot" regardless of the position that it resides in.



3. A word/text with a % at the beginning, searches for all the records that ends with the word/text after the percent sign. It's works in kind of the reverse of what you think will happen

SELECT ProductName,UnitPrice
FROM Products
WHERE ProductName LIKE '%Sauce'

The above query searches for all the records that ends with the word/text "Sauce" in the ProductName field in the Products table



 4. Let's try something a little bit tricky. Let's say your boss wants you to search for a spread that he likes, but does not know the exact spelling for. He would tell you it's call something like a "boys" n "berry" spread. To get that .00001% raise that you've always wanted you told your boss, I can do it!. So how will you search for such a spread?

SELECT ProductName,UnitPrice
FROM Products
WHERE ProductName LIKE '%Boy%y%'



The above query searches for a word that contains the text "Boy" and ends with the letter "y", and the result is, ta da! "Grandma's Boysenberry Spread" with that result you were able to get your .00001% raise and is finally able to afford half a Popsicle that you've been eyeing all week. All is well in the IT land once again.

Conclusion: The LIKE operator comes in handy when you need to match a text pattern in a text field. However, it takes longer to execute than an equality match. So use it sparingly, only when needed.

SQL: Wildcard Search With The LIKE Operator

Equality searches are great and efficient when you want exact matches or range of values. However, there will be times when you need to search a text field for not so perfect matches, perhaps a partial match is needed. Certain scenarios requires to search for patterns, such as an email address. That's when the LIKE operator is useful in SQL. The only caveat is that LIKE operators can only work with text fields.

Examples:

1. A word/text with a % at the end, searches for all the records that begins with the letters before the percent sign


SELECT ProductName,UnitPrice
FROM Products
WHERE ProductName LIKE 'Chef%'
The query above returns all the records in the Products table that begins with the word "Chef"

2. A word with % sign on both ends, means that the result will be any records that contains the enclosed word/text within the % sign


SELECT ProductName,UnitPrice
FROM Products
WHERE ProductName LIKE '%Hot%'

The query above searches for any records that contains the word "Hot" in the ProductName field. It brings back all the records that contains the word "Hot" regardless of the position that it resides in.


3. A word/text with a % at the beginning, searches for all the records that ends with the word/text after the percent sign. It's works in kind of the reverse of what you think will happen


SELECT ProductName,UnitPrice
FROM Products
WHERE ProductName LIKE '%Sauce'
The above query searches for all the records that ends with the word/text "Sauce" in the ProductName field in the Products table


4. Let's try something a little bit tricky. Let's say your boss wants you to search for a spread that he likes, but does not know the exact spelling for. He would tell you it's call something like a "boys" n "berry" spread. To get that .00001% raise that you've always wanted you told your boss, I can do it!. So how will you search for such a spread?


SELECT ProductName,UnitPrice
FROM Products
WHERE ProductName LIKE '%Boy%y%'

The above query searches for a word that contains the text "Boy" and ends with the letter "y", and the result is, ta da! "Grandma's Boysenberry Spread" with that result you were able to get your .00001% raise and is finally able to afford half a Popsicle that you've been eyeing all week. All is well in the IT land once again.

Conclusion: The LIKE operator comes in handy when you need to match a text pattern in a text field. However, it takes longer to execute than an equality match. So use it sparingly, only when needed.

Saturday, February 7, 2015

SQL: Querying NULL Records in SQL Server













As a developer we always forget how to query for records with NULL values, no matter how many times we do it. It's just weird. Our first instinct is to write the query as such

   SELECT CompanyName, ContactName, ContactTitle,Region
FROM Customers
WHERE Region = NULL

But that will not return any results. The funny thing is there's no SQL error so you think that there's no results. However if you change the query to this

   SELECT CompanyName, ContactName, ContactTitle,Region
FROM Customers
WHERE Region IS NULL

You see there's plenty of records with Region IS NULL



The reverse is true if you want records that are not NULL you would not write the query like this

   SELECT CompanyName, ContactName, ContactTitle,Region
FROM Customers
WHERE Region != NULL

But you want to write the query like this instead

   SELECT CompanyName, ContactName, ContactTitle,Region
FROM Customers
WHERE Region IS NOT NULL


SQL: Querying NULL Records in SQL Server

As a developer we always forget how to query for records with NULL values, no matter how many times we do it. It's just weird. Our first instinct is to write the query as such

SELECT CompanyName, ContactName, ContactTitle,Region
FROM Customers
WHERE Region = NULL
But that will not return any results. The funny thing is there's no SQL error so you think that there's no results. However if you change the query to this

SELECT CompanyName, ContactName, ContactTitle,Region
FROM Customers
WHERE Region IS NULL
You see there's plenty of records with Region IS NULL

The reverse is true if you want records that are not NULL you would not write the query like this

SELECT CompanyName, ContactName, ContactTitle,Region
FROM Customers
WHERE Region != NULL
But you want to write the query like this instead

SELECT CompanyName, ContactName, ContactTitle,Region
FROM Customers
WHERE Region IS NOT NULL


Friday, February 6, 2015

SQL: Sort By Multiple Columns













SELECT UnitPrice, ProductName
FROM Products
ORDER BY UnitPrice DESC, ProductName


The query above sorts the results based on the most expensive products, and then the product name. Useful if you want a secondary sort criteria. For example if there are multiple products that are $14.00 then those products will be sorted by their names after the price has been sorted.

SQL: Sort By Multiple Columns

SELECT UnitPrice, ProductName
FROM Products
ORDER BY UnitPrice DESC, ProductName


The query above sorts the results based on the most expensive products, and then the product name. Useful if you want a secondary sort criteria. For example if there are multiple products that are $14.00 then those products will be sorted by their names after the price has been sorted.

Wednesday, October 8, 2014

HTML5: Mark Element














The <mark> element is used to highlight a text by assigning a background-color attribute

Example:


This is an example of the <mark style="background-color:yellow;">mark</mark> element

This is an example of the mark element

HTML5: Mark Element

The <mark> element is used to highlight a text by assigning a background-color attribute

Example:


This is an example of the <mark style="background-color:yellow;">mark</mark> element

This is an example of the mark element

Tuesday, October 7, 2014

HTML5 : Progress Element











<progress> element represents the progress of a task or goals and objectives, there are two ways that you can set this element, they are the following

  • Determinate - know in advance the starting and ending values
  • Indeterminate - end value is unknown in advance (remove value attribute)
Determinate Example:
<p>Our goal is to have 500 runners: </p>
0
<progress value=”250” max=”500”></progress>
500

Our goal is to have 500 runners:

0 500


Indeterminate Example:

<p>Please wait while we download your TPS Report!</p>
<progress></progress>

Please wait while we download your TPS Report!

HTML5 : Progress Element

<progress> element represents the progress of a task or goals and objectives, there are two ways that you can set this element, they are the following

  • Determinate - know in advance the starting and ending values
  • Indeterminate - end value is unknown in advance (remove value attribute)
Determinate Example:
<p>Our goal is to have 500 runners: </p>
0
<progress value=”250” max=”500”></progress>
500

Our goal is to have 500 runners:

0 500


Indeterminate Example:

<p>Please wait while we download your TPS Report!</p>
<progress></progress>

Please wait while we download your TPS Report!

Wednesday, August 13, 2014

Installing AdventureWorks Sample Databases from Microsoft

1. Type in the following URL into your browser's address bar

     http://msftdbprodsamples.codeplex.com/

2.  Click on the "Download" button on page

AdventureWorks download button


3.  Click on the recommended download link

Adventure Works 2014 Sample Databases

4.  Unizp the file you just downloaded

5.  Open the SQL Server Management Studio, then right click on "Databases" and then select "Restore Database"
SQL Server Manager Studio


6.  Select "Device" under "Source"

SQL Server Device

7.  Click on the "..." button, and the "Select" backup devices will appear, select "File" for "Backup media type"

Select backup devices


8.  Click on the "Add" button, and select the "AdventureWorks2014.bak" file, then click "OK"

AdventureWorks2014.bak

8.  Click "OK" on the "Select backup devices" screen

Select backup devices

9.  Click "OK" on "Restore Database" window

Restore database

10.  A message will pop up that says you have successfully restored the AdventureWorks2014 database

Database 'AdventureWorks2014' restored successfully.

11.  The "AdventureWorks2014" database is now added to your SQL Server instance

AdventureWorks2014


Installing AdventureWorks Sample Databases from Microsoft

1. Type in the following URL into your browser's address bar
     http://msftdbprodsamples.codeplex.com/

2.  Click on the "Download" button on page
AdventureWorks download button


3.  Click on the recommended download link

Adventure Works 2014 Sample Databases

4.  Unizp the file you just downloaded

5.  Open the SQL Server Management Studio, then right click on "Databases" and then select "Restore Database"
SQL Server Manager Studio


6.  Select "Device" under "Source"

SQL Server Device

7.  Click on the "..." button, and the "Select" backup devices will appear, select "File" for "Backup media type"

Select backup devices


8.  Click on the "Add" button, and select the "AdventureWorks2014.bak" file, then click "OK"

AdventureWorks2014.bak

8.  Click "OK" on the "Select backup devices" screen

Select backup devices

9.  Click "OK" on "Restore Database" window

Restore database

10.  A message will pop up that says you have successfully restored the AdventureWorks2014 database

Database 'AdventureWorks2014' restored successfully.

11.  The "AdventureWorks2014" database is now added to your SQL Server instance

AdventureWorks2014