You are on page 1of 24

MTA : Database Fundamentals

Lab Exercises & Notes





Lab Exercise 1

Task 1: Exploring SQL Server Management Studio (SSMS)

1. On the virtual machine’s Windows task bar of your Virtual Machine, start SQL Server
Management Studio.

2. At the “SQL Server” Window, connect to MIA-SQL database engine using Windows
Authentication as follows:


3. If the Object Explorer is not visible, on the View menu, click Object Explorer.

4. In the Object Explorer, under MIA-SQL , expand Databases and note the databases that are
hosted on this database engine instance :

a. System Databases are created by default:
master, model, msdb and tempdb.
These databases are used by SQL Server for its own maintenance and management.

b. The rest are user-defined databases. We will be using the AdventureWorks


database for our course.

1) Expand the AdventureWorks database.
You will see the database objects in that database.

2) Expand the Tables to see the list of tables that are in the database.
You will see tables like:
- HumanResources.Department
- HumanResources.Employee
- Person.Address
- …

Note that the AdventureWorks naming convention is schema_name.table_name

3) Look for the Person.Person table. Right-click on it and choose Select Top 1000
Rows.

4) You will see 2 new windows: SQL Query window and the Results window that
displays the data in the Person.Person table.

5) Minimize the AdventureWorks database.

Task 2: Create a Database with the SSMS interface

1. Under MIA-SQL, right click Databases and select New Database.

2. Enter LabDatabase. Click OK.

3. Verify that the new database has been created in the Object Explorer.


Task 3: Delete a Database with the SSMS interface

1. Under Databases, select LabDatabase and right-click Delete.

2. Select Close Existing Connections then click OK.

3. Verify that the LabDatabase is no longer listed in the Object Explorer.

Note: Click Databases and right-click Refresh if necessary.
Lab Exercise 2

Task 1: Create a “LabDatabase” database using SSMS

1. Under MIA-SQL, right click Databases and select New Database.
2. Enter LabDatabase. Click OK.
3. Verify that the new database has been created in the Object Explorer.


Task 2: Create a table using SSMS

Create a new Table Planets with the following fields :



1. Expand the LabDatabase.

2. Right-click the Table folder and select New Table.

3. Enter details for Column Name, Data type and Length. Indicate on Allow Nulls accordingly:

For IndividualID column:
• Right-click the ► icon and click Set Primary Key.
• Expand (click > ) the IdentitySpecification in the Column Properties window below.
• Set (Is Identity) to Yes
• Check that Identity Increment and Identity Seed has been set to 1.
This will insert an auto-increment number for each new record starting from 1.

For DateCreated column:
• In the Column Properties window below, expand (General).
• Under Default Value or Binding, enter getdate() – this will insert the current date for
each new record.

4. Save your table by selecting File > Save Table_1. Enter name of table as Planets and click
OK.

5. Do a Refresh on LabDatabase. Verify that your table has been created in the Object
Explorer.

1
Task 3: Alter Table using SSMS

You realized the data type for Radius should be float instead of varchar(50). Modify its data type
as follows:
1. Select the Planets table within the LabDatabase database.
2. Right-click Design
3. Amend the data type of Radius to float.
4. Save your changes by clicking the “Save” icon.

Note:
If you encounter a “Savings changes not permitted” error, follow these steps:
• On the Tools menu, click Options.
• In the navigation pane of the Options window, click Designers.
• Uncheck “Prevent saving changes that require the table re-creation” check box. Click OK.


Task 4: Drop Table using SSMS
To delete a selected table, simply right-click and select “Delete”.


Task 5: Create a table using TRANSACT-SQL commands

1. Click the “New Query” icon .

Tip : Change the font size of the SQL Query Editor
1. Click on Tools menu, select Options….
2. Expand Environment (click on >) and then click Fonts and Colors.
3. In the Show settings for list, select Text Editor.
4. Change the font and size as desired.
5. Click OK.


2. Enter the following SQL commands in the SQLQuery window:


2

3. Click on the “Execute” icon.

4. Do a Refresh on LabDatabase. Verify that your table Planets1 has been created in the Object
Explorer.

5. Save your SQL commands in a script file as follows:
- Click File > Save SQLQuery.sql As…
- Click the desktop folder and enter “Lab2_CreateTable.sql” for the file name.


Task 6: Alter Table using TRANSACT-SQL commands

The data type for Radius should be float instead of varchar(50). Modify its data type as follows:

1. Enter the following SQL commands in the SQLQuery window:

ALTER TABLE Planets1


ALTER COLUMN Radius float;


2. Highlight what you have edited and click on the “Execute” icon.

3. Click Planets1 on the Object Explorer then right-click Design. Verify that the Radius column has
been set to the float data type. (Do a Refresh on the database if necessary)


Task 7: Drop Table using TRANSACT-SQL commands

If you need to remove the Planets1 table, you can run the following TRANSACT-SQL commands:

DROP TABLE Planets1;





3

SETUP to use “Adventureworks” Database for exercises

1. Click the “New Query” icon.

2. Enter the following SQL commands in the SQLQuery window:

ALTER AUTHORIZATION ON DATABASE::AdventureWorks TO sa ;


Task 8: Create a View using SSMS

Create a new view vwCustomer from the Sales.Customer table of the AdventureWorks database
with the following fields : CustomerID, StoreID, AccountNumber.

1. Select View under the AdventureWorks database.

2. Right-click New View

3. Select the table Customer(Sales). Click Add then Close the window.

4. Select the following columns:
• CustomerID
• StoreID
• AccountNumber

5. Click the Save icon to save your view.

6. Enter vwCustomer for the view name. Click OK.

7. Do a Refresh on AdventureWorks.

8. Verify that your view has been created in the Object Explorer. Use SSMS’s “Select top 1000
rows” or write a simple SQL Select query to see the contents of the vwCustomer.


Task 9: Delete a View using SSMS

To delete a selected view, simply right-click and select “Delete”.

4
Task 10: Create a View using TRANSACT-SQL commands

Create a new view vwIndividual from the Person.Person table of the AdventureWorks database
with the following fields : FirstName, LastName, PersonType.

1. Click the “New Query” icon .

2. Enter the following SQL commands in the SQLQuery window:

USE AdventureWorks;

CREATE VIEW vwIndividual AS


SELECT FirstName, LastName, PersonType
FROM person.person
WHERE PersonType = 'IN';

3. Click on the “Execute” icon.

4. Do a Refresh on AdventureWorks database. Verify that your view vwIndividual has been
created in the Object Explorer.

5. Write a simple SQL Select query to see the contents of vwIndividual.


Task 11: Drop View using TRANSACT-SQL commands

If you need to remove the vwIndividual view, you can run the following TRANSACT-SQL
commands:

DROP VIEW vwIndividual;






5
Task 12: Create Stored Procedure using SSMS

Create a new stored procedure to retrieve the following fields : FirstName, LastName, PersonType
from the Person.Person table of the AdventureWorks database.

1. Expand the Programmability folder under the AdventureWorks database.

2. Expand the Stored Procedure folder. You will see System Stored Procedures which are
provided by Microsoft.

3. Right-click Stored Procedures and choose New Stored Procedure.

4. The Text Editor window will open and display a ready-made stored procedure template for
you.

5. As we will be writing a simple stored procedure, we will start with a new SQL query window.
Click the “New Query” icon.

6. Enter the following in the SQL Query window:

CREATE PROCEDURE uspGetPerson


AS
BEGIN
This turns off the “Number of
SET NOCOUNT ON; rows affected” message

SELECT FirstName, LastName, PersonType


FROM person.person
WHERE PersonType = 'IN';
END



7. Click on the “Execute” icon to create the stored procedure.

8. Do a Refresh. Verify that the stored procedure uspGetPerson has been created in the Object
Explorer.

9. To run the stored procedure, open a new SQL Query window and enter:

exec uspGetPerson;



Note : Press Ctrl-Shift-R to refresh the cache if necessary.
6

Lab Exercise 3

Task 1: Using the SELECT statement
Proficiency Assessment : Scenario 2-4 (Pg 42 of Guidebook)

You are a database administrator for the AdventureWorks Corporation and a service manager
needs your help to extract data from the company’s database. Therefore, after opening SSMS
and accessing the AdventureWorks database, specify the basic SELECT statements you would
use to retrieve the required information from the ProductsSubcategory table.

1. What commands would return all the rows and columns in the ProductCategory table?
USE AdventureWorks;
SELECT * FROM Production.ProductCategory;

2. What commands would you type and execute to return only the ProductSubcategoryID,
ProductCategoryID, Name, and ModifiedDate columns?

SELECT ProductSubcategoryID, ProductCategoryID, Name, ModifiedDate


FROM Production.ProductSubcategory;


3. What commands would you type and execute to return rows where the word bike is found
somewhere in the Name column?

SELECT ProductSubcategoryID, ProductCategoryID, Name, ModifiedDate


FROM Production.ProductSubcategory
WHERE Name LIKE '%bike%';


4. In the existing query window, what commands would you use to add a column alias to the
Name column to clarify it as the subcategory name?

SELECT ProductSubcategoryID, ProductCategoryID,


Name AS 'Subcategory Name', ModifiedDate
FROM Production.ProductSubcategory
WHERE Name LIKE '%bike%';


5. In the existing query window, what command would you use to sort the previous result set
by Subcategory Name?

SELECT ProductSubcategoryID, ProductCategoryID,


Name AS 'Subcategory Name', ModifiedDate
FROM Production.ProductSubcategory
WHERE Name LIKE '%bike%'
ORDER BY 'Subcategory Name';

1

Task2 : Create the HumanResources.Employee table
Use either SSMS or TRANSACT-SQL to create the HumanResources.Employee table.

1. Create Click on the “New Query” icon.

2. Enter the following SQL commands in the SQL Query window:

USE LabDatabase;

CREATE TABLE [HumanResources.Employee] (


EmployeeID int NOT NULL PRIMARY KEY,
FirstName varchar(50) NULL,
LastName varchar(50) NULL,
Title varchar(20) NULL,
EmailAddress varchar(100) NULL );


3. Click on the “Execute” icon.

4. Do a Refresh on LabDatabase. Verify that your table HumanResources.Employee has been
created in the Object Explorer.


Task 3: Insert / Update data to HumanResources.Employee table using SSMS
Enter the following rows of data to the HumanResources.Employee table:

EmployeeID FirstName LastName Title EmailAddress
287 Mensa-Annan Tete Mr. MAT@hotmail.com
288 Abbas Syed Mr. SyedAbbas@yahoo.com.sg
289 Valdez Rachel NULL RachelV@NTUC.gov.sg

1. At the Object Explorer, right-click HumanResources.Employee and select “Edit Top 200
Rows”.

2. Enter the data (as shown above) into the table.


Task 4: Insert data using TRANSACT-SQL commands
The other method to insert data is by running a SQL INSERT command.

1. Click on the “New Query” icon.

2. Enter the following SQL commands in the SQL Query window:

INSERT INTO [HumanResources.Employee]


( EmployeeID, FirstName, LastName, Title, EmailAddress )
VALUES (290, 'Karen', 'Yap', 'Dr.', 'DrYapKaren@gmail.com'),
(211, 'Lin Lee', 'Kim','Ms.', NULL);

2

3. Click on the “Execute” icon.

4. Do a Refresh on LabDatabase. Verify that your table HumanResources.Employee has the
correct data inserted.


Task 5: Update data using TRANSACT-SQL commands

You realized that there is a data-entry error in the EmployeeID and an update in EmailAddress
of staff Kim Lin Li. (EmployeeID should be 291 and new EmailAddress is ‘KLL@Tiny.com.sg’).
Make the necessary amendments using the Update command.

1. Click on the “New Query” icon.

2. Enter the following SQL commands in the SQL Query window:

UPDATE [HumanResources.Employee]
SET EmployeeID = 291, EmailAddress = 'KLL@Tiny.com.sg'
WHERE EmployeeID = 211;



Task 6: Delete data (FOR INFO ONLY)

• To remove a specific record of any table using SSMS:
1. At the Object Explorer, right-click the table and select “Edit Top 200 Rows”.
2. Select the entire row to be deleted (left most column ► icon) and right-click Delete.

• To remove any table using SSMS:
1. At the Object Explorer, right-click the table and select “Delete”.

• To remove table using using TRANSACT-SQL commands
1. If you wish to remove HumanResources.Employee table, enter and execute the
following SQL commands in the SQL Query window:

-- Removes all rows in the table only
DELETE FROM [HumanResources.Employee];

-- Removes the table completely


DROP TABLE [HumanResources.Employee];

3
Lab Exercise 4

Task 1: Create a Foreign Key using SSMS
You are tasked to create an Employee table with employee details and to create a link to the
Department table which contains the department name and its manager. Department table is the
primary table.

1. Create the following tables in LabDatabase using TRANSACT-SQL or SSMS:

USE LabDatabase;

-- Create Employee

CREATE TABLE Employee (


EmployeeID int NOT NULL PRIMARY KEY,
FirstName varchar(50) NULL,
LastName varchar(50) NULL,
Title varchar(20) NULL,
Dept varchar(5) NULL,
EmailAddress varchar(MAX) NULL );

-- Create Department

CREATE TABLE Department (


Dept varchar(5) NOT NULL PRIMARY KEY,
DeptName varchar(50) NULL,
ManagerID int NULL);


2. In Object Explorer, refresh the LabDatabase > Tables folder.

3. Expand the LabDatabase > Tables folder.

4. Right-click Employee and select Design.

1


5. Select Relationships from the Table Designer drop-down menu near the top of the screen as
shown below:



6. Click the Add button.

7. Click the ellipsis (. . .) beside the Table and Specification property dialog box as shown below:

2


8. Select the table that your foreign key refers to in the primary key table (Department) and its
attribute Dept in the drop-down lists as shown below:


9. The Foreign key table should be Employee and its attribute Dept as the foreign key.

10. Click OK to close the dialog box.

11. Click the Close button.

12. Save your newly created constraint by selecting Save All from the File menu.

Task 2: Create a Foreign Key using TRANSACT-SQL
Alternatively, you can create a table with a foreign key constraint using SQL. The following creates
the Customer table with a foreign key that links to the Department table. Department table is the
primary table.

USE LabDatabase;

-- Create Customer

CREATE TABLE Customer (


CustID int NOT NULL PRIMARY KEY,
FirstName varchar(50) NULL,
LastName varchar(50) NULL,
Title varchar(20) NULL,
Dept varchar(5) NULL FOREIGN KEY REFERENCES Department(Dept),
EmailAddress varchar(MAX) NULL );

3



Task 3 : Generate Database Diagram using SSMS

You can use the Database Diagrams function in SSMS to generate a diagram to show how the
tables in your database are related.

1. Close all the tables.

2. In Object Explorer, refresh the LabDatabase folder.

3. Select LabDatabase > Database
Diagram folder. Right-click and select
New Database Diagram.

4. At the Add Table window, click
Refresh.

5. Select Department and click Add.
Select Employee and click Add.
Select Customer and click Add.

6. Click Close. Click outside the box.




7. You should be able to see the following database diagram generated, showing the
relationships between the three tables:



4

Task 4 : Create a Non-Clustered Index using SSMS
Your users informed you that besides the CustID (primary key), they also frequently search for
customer information using the name of the customer. Create a non-clustered index to speed up
retrieval of customer data using their first and last names.

1. In the Object Explorer, expand LabDatabase database and its Tables.

2. Expand the Customer table.

3. Expand Indexes.

4. Note that a Clustered-index on CustID (the primary key) has already been created for the
Customer table by SQL Server. Double click on PK_Customer_xxxx… to see its details.



5. Click Cancel and click the minus (-) icon of Indexes.

6. Right-click Indexes > New Index > Non-Clustered Index…

5

7. Click Add and select FirstName and LastName as the columns to create non-clustered index.



8. Click OK. Confirm by clicking OK again.

9. Note that your Non-clustered Index has been created successfully in the Object Explorer.




10. By creating indexes on CustID (clustered) , FirstName and LastName (non-clustered), it means
that any subsequent data retrieval using the any of the 3 fields will be faster than without any
indexes created.

6

1
2
3
4
5
6

You might also like