Вы находитесь на странице: 1из 49

Prepared by Abinew Ali and Tsegaw Kelela

Bahir Dar Intistute of Technology (BiT)

School of Computing

Laboratory Manual for Fundamentals of Database systems

March, 2015

Prepared by:

Abinew Ali(Msc.)
Tsegaw Kelela(Msc.)

Prepared by Abinew Ali and Tsegaw Kelela


Prepared by Abinew Ali and Tsegaw Kelela

Table of Contents
Lab Session 1: INTRODUCING MICROSOFT SQL SERVER 2012 ENVIRONMENT AND CREATING, MODIFYING
AND DELETING DATABASES .................................................................................................................................1

Lab Session 2: CREATING, MODIFYING AND DELETING TABLES .........................................................................4

Lab Session 3: INSERTING DATA ....................................................................................................................8

Lab Session 4: RETRIEVING AND FILTERING DATA ............................................................................................ 10

Lab Session 5: FORMATTING RESULT SETS ....................................................................................................... 14

Lab Session 6: GROUPING AND SUMMARIZING DATA ..................................................................................... 18

Lab Session 7: IMPLEMENTING DATA INTEGRITY CONSTRAINTS ..................................................... 23

Lab Session 8: JOINING MULTIPLE TABLES.............................................................................................. 29

Lab Session 9: UPDATING DELETING AND TRUNCATING DATA ........................................................................ 33

Lab Session 10: SUBQUERIES ............................................................................................................................ 36

Lab Session 11: CREATING VIEWS .............................................................................................................. 40

Lab Session 12: Creating Index ......................................................................................................................... 44

Reference .......................................................................................................................................................... 46

Annexes ............................................................................................................................................................. 47
Prepared by Abinew Ali and Tsegaw Kelela

Lab Session 1: INTRODUCING MICROSOFT SQL SERVER 2012 ENVIRONMENT


AND CREATING, MODIFYING AND DELETING DATABASES
A. INTRODUCING MICROSOFT SQL SERVER 2012 ENVIRONMENT
 SQL Server Management Studio(SSMS)
You can use SQL server management studio to manage database objects using
graphical user interface, GUI (Without writing SQL codes)

To open SQL SSMS, use the following steps:

1. Start  All Programs  Microsoft SQL server 2012SQL Server Management Studio.
2. Click on Connect to your default instance as shown in the following figure.

Fig 1.1: connecting to SQL server

 SQL Server Configuration Manager (SSCM)


It is used to set or change the values of configuration settings that apply to the
database engine instance, agent service and other SQL server services installed on
the host computer.
To open SQL SSCM, use the following steps:
1. Start  All Programs  Microsoft SQL server 2012Configuration Tools  SQL Server
Configuration Manager.

Fig 1.2: connecting to SQL server

1
Prepared by Abinew Ali and Tsegaw Kelela

2. Right click on the service and click on properties to change the currently configured values
 Query Editor
You can open and use Query editor window to write Transact –SQL codes (T-SQL codes) for the
purpose of creating, maintaining and removal of server and database objects

Fig 1.3: Opening Query editor window


B. CREATING, MODIFYING AND DELETING DATABASES
 CREATING A DATABASE
C. using the graphic interface
1. Start SQL Server Management Studio by selecting Start Programs  Microsoft SQL
server 2012 Management Studio.
2. Click on Connect to your default instance of SQL Server as in Figure 1.1
3. Expand your Databases folder.
4. Right-click either the Databases folder in the console tree or the white space in the right
pane, and choose New Database from the context menu.
5. You should now see the General tab of the Database properties sheet. Enter the
database name, and leave the owner as <default>.

Fig 1.4: connecting to SQL server

6. Leave all of the defaults and Click OK when you finished. You should now have a new
database.

B. Using Transact SQL statements (T-SQL)


We can create a new database and the files used to store the database using T- SQL Code. From the
toolbar, click on New Query
Write the database creation statement on the editor and click on Execute .
Here is the simplest syntax leaving other parameters to take the default values:

2
Prepared by Abinew Ali and Tsegaw Kelela

CREATE DATABASE database_name


database_name Is the name of the new database. Database names must be unique within an instance of
SQL Server

For example, to create a database with name ‘Test’, we write the following statement:

CREATE DATABASE test

 MODIFYING A DATABASE
You can modify the current settings of an existing database through the GUI or T-SQL code
To modify a database using a GUI,
For example, to modify the value of the database auto growth size, follow the next steps:
1. Right click the database
2. Click on Properties
3. Click on the Files Tab
3. Change the existing auto growth settings by modifying values as shown in Fig 1.5 below:

Fig 1.5 modifying a database


Alternatively, you can also use T-SQL code to achieve the same result. For example, we can
modify the file growth of a test database as follows:

USE test
GO
ALTER DATABASE student MODIFY FILE (NAME = N'test', FILEGROWTH = 2048KB )
GO
Dropping a Database

We can drop a database either by right clicking the database and pressing Delete on the context
menu or using the following Drop Syntax

DROP DATABASE <databaseName>


Example: DROP DATABASE test
EXERCISES
1. Create a database with your Name
2. Modify the initial size of the database to be 5 MB
3. Delete the database that you have already created.

3
Prepared by Abinew Ali and Tsegaw Kelela

Lab Session 2: CREATING, MODIFYING AND DELETING TABLES


Objective: The main objectives of this laboratory session are:

 To create a table and data types in SQL server


 Defining the data types for the table
 Deleting records ,dropping, altering tables

Creating Tables
Tables are a two dimensional data structure having rows and columns. They are used to store data in the
database.

Creating a table involves defining the columns with appropriate data types and specifying whether the
values to be stored in each column are allowed to be null or not.

A data type simply specifies what type of data can be placed into the object (column, variable, parameter,
and so on). Database integrity depends heavily on appropriately scoped data types. There are four basic
categories of data types in SQL server. These are Numeric, Date Time, Strings and Others.

Numeric data types


The numeric data type has two subcategories: exact and approximate. Exact data types fit within a
finite range of numbers. Table 2-1 lists and defines each exact numeric data type.
Data Type Range Storage
Bigint –9,223,372,036,854,775,808 to 8 bytes
9,223,372,036,854,775,807
Int –2,147,483,648 to 2,147,483,647 4 bytes
smallint –32,768 to 32,767 2 bytes
Tinyint 0 to 255 1 byte
Money –922,337,203,685,477.5808 to 8 bytes
922,337,203,685,477.5807
smallmoney –214,748.3648 to 214,748.3647 4 bytes
Table 2.1: Exact numeric data type

String data types


The string data type contains three subcategories: character, Unicode, and binary. Each contains
three specific data types. These data types are similar in that each subcategory contains a fixed-
length data type and a variable-length data type.

Char[n], NChar[n], Varchar[n], Nvarchar[n] belongs to the strings data types. NChar and Nvarcahr
are Unicode String data types.

Note: n defines the string length that can be stored. For variable-length data types, max can be
specified for n, which indicates that the maximum storage size is 2 GB.

4
Prepared by Abinew Ali and Tsegaw Kelela

Date and time data types


There are six data types under this category. This include Date, Datetime, smalldatetime, time(n),
datetime2(n),and datetimeOffset.
We can retrieve the list of all data types supported by the current SQL Server using the following T-SQL
Code:
Select name from sys. Types
To create a table using GUI, follow the next steps as indicated in Figure 2.1 below
1. Expand your database  Right Click on Tables and specify columns with their data types

Figure 2.1 Creating a Table

2. When you finish, go to the Tool bar and Click on Save. You will be prompted to fill the table
name. Fill in the table name box and click OK.
3. After refreshing the Tables folder, you should see the newly created table
T- SQL Syntax:
USE database_name
CREATE TABLE table_name
(
Column_Name data type NOT NULL,Column2 data type ,Column3 data type NOT
NULL...... Column N data type)
5
Prepared by Abinew Ali and Tsegaw Kelela

Note:-
 We can define up to 1024 columns per table.
 If you do not specify NULL or NOT NULL, SQL Server provides the NULL.

Example: To create the student table under a database called Registrar,

USE Registrar
CREATE TABLE student
(
stud_ID int not null,
First_Name varchar(30),
Address varchar (30) default ‘Addis Ababa’
)

Modifying a table

You can modify the table by adding a new column and deleting a column from the table.

Adding a Column

The type of information that you specify when you add a column is similar to that which you supply when
you create a table.

Syntax: ALTER TABLE table_name ADD column_name data type

For example, to add the column age in the student table we write :

ALTER TABLE STUDENT ADD age INT

If we need to modify (change) the data type of the already created

Column, we can use the following syntax:

ALTER TABLE table_name ALTER COLUMN column_name new_data_type


For example, to change the data type of stud_ID column in the student table from integer to character data
type, we write:

ALTER TABLE student ALTER COLUMN stud_ID varchar(30)

Deleting a Column
Deleting columns are unrecoverable. Therefore, be certain that you want to remove a column before doing
so.

Syntax: ALTER TABLE table_name DROP COLUMN column_name

This example deletes a column from a table


ALTER TABLE student DROP COLUMN age

6
Prepared by Abinew Ali and Tsegaw Kelela

Generating Column Values using Identity Property

You can use the Identity property to create columns (referred to as identity columns) that contains system
generated sequential values identifying each row Inserted into a table.

Syntax: CREATE TABLE table_name

(
Column_name data type IDENTTY (seed, increment) NOT NULL
)

The following example is used to create auto increment column on the EmpID column of Employee
table with a seed valued of 1(initial value) and incrementing by 1.
Create table Employee
(EmpID int NOT NULL identity(1,1), EmpName varchar (20) )
Consider the following requirements for using the Identity property
Only one identity column is allowed per table

 It must be used with integer (int, bigint, smallint, or tinyint), numric, or decimal data ypes.
 The numeric and decimal data types must be specified with a scale of 0
 It cannot be updated
 It does not allow null values

Deleting a Table
Deleting a table removes that table definition and all data, as well as the permission for that table.
Before you delete a table, you should remove any dependencies between the table and other
objects.

Syntax: DROP TABLE table_name


Example: DROP TABLE student

Exercise
1. Create table whose name is Staff with attributes like name, Id, sex, salary, Nationality and age
(Using GUI and T-SQL code as we have seen in this lesson).

2. Modify the employee table by adding a column named Qualification.

3. Modify the Staff table by modifying the data type of the age column to int.

4. Delete the table Staff

7
Prepared by Abinew Ali and Tsegaw Kelela

Lab Session 3: INSERTING DATA


Inserting Data to a table
You can insert data to a table using the GUI or T-SQL code. For example, to insert data into the course table
found under test database, use the steps shown below:

1. Navigate to Database Test TablesCourse Table

Fig 3.1 Navigating to a specific table of the database

2. Right Click on Course Table Edit Top 200 rows


3. Fill the data on each mandatory cells and press Tab at the end of each row
4. When you finish entering data, click on Execute icon on the tool bar or press F5 to save rows.

Fig 3.2 Inserting data using GUI

Inserting data using T-Code


 Inserting data Using INSERT...VALUES method
Use the INSERT statement with the VALUES clause to add rows to a table.
When you insert rows, consider the following facts and guidelines:
 Must adhere to the same order and data type of the columns in the table. Otherwise, the
insertion will fail.
 Use the column_list to specify columns that will store each incoming value.
 You must enclose the column_list in parentheses and delimit it by commas.
 If you are supplying values for all columns, using the column_list is optional
 Character data and dates must be enclosed in single quotation marks.
8
Prepared by Abinew Ali and Tsegaw Kelela

Syntax
INSERT INTO table_name[ColumnNameList] VALUES (list_of_values)
Example: To insert values in the course table with a value of Cno=3,Ctitle=‘Database‘,CrHr=5 and
Dno=10:
Insert into Course values(3,’Database’,5,10)
Inserting data Using INSERT ...ELECT Method .
o To insert data using this method, the columns derived from the result of the select stamen
must fit to the columns of the table we are going to insert.
Example:
Insert into Employee Select * from Instructor
Note: if ColumnNameList is not specified, the values clause expect the whole list of values to
all columns of the table.
 Inserting data Using INSERT...EXEC UTE method
o This is a method of populating data to a table using the result of rows fetched by a
stored procedure
Example: To insert data to an employee table using rows fetched by A stored procedure
called fetchInstructors, we can use the following code:
Insert into Employee EXECUTE fetchInstructors
 Inserting data using SELECT… INTO method
o Syntax:
Select {Column List|* } from TableName into NewTable [WHERE] [CONDITION]
This method fetch subset of rows from an existing table and insert the rows into a
dynamically created a new table
Example: To insert rows fetched from Instructor table by creating a into a new table table
called Employee we can use the following code:
Select * from instructor into Employee
 Inserting Data by Using Column Defaults.
To insert a default value on the default column of a table, we can either remove that column from
the ColumnList in the INSERT …..VALUES statement or we can use the key word DEFAULT
in place of the value.
Example: To insert the default value BahirDar into a city Column of Employee

Insert into Employee(IdNo,fName,Lname,sex) values(1,’Hailu’,’Kassa’,’M’) OR


Insert into Employee values(1,’Hailu’,’Kassa’,’M’,DEFAULT)

Exercise
o Create an Emplyee table under a database called ‘HR’
Employee
IDNo Fname Lname Sex Date_of_birth Kebele Marital_status
1 Almaz Kassa F 2/3/1977 15 Single
2 Mohamed Kemal M 4/6/1983 20 Married
3 Aynalem Molla F 12/9/1971 9 Married
4 Sisay Tesfaye M 5/10/1988 7 Single
Additional information (Assumption about existing business rules):
 Values for sex attribute are optional while Values for kebele are mandatory(it is not
possible to leave this value blank)
 The values for IDNo field could be generated automatically
9
Prepared by Abinew Ali and Tsegaw Kelela

 “Married” can be used as a default value for Marital_status coulumn


2. Insert the sample data using the insertion methods we have seen in this session

Lab Session 4: RETRIEVING AND FILTERING DATA


4.1 RETRIEVING DATA BY USING THE SELECT STATEMENT
You can use the SELECT statement to specify the columns and rows of data that you want to
retrieve from tables.
Syntax: SELECT [ALL|DISTINCT]<select_list>
FROM {<table_source >}
WHERE <search_condition>
o The SELECT statement lists the items or column names, computed values, the
aggregate functions, etc to be retrieved.
o The FROM clause specifies the table or tables from which columns and rows are
returned.
o The WHERE clause specifies the condition restricting the query. You can restrict the
number of rows by using comparison operators, character strings, and logical
operators as search conditions.
When you specify columns to retrieve, consider the following facts and guidelines:
o The select list retrieves and displays the columns in the specified order
o Separate the column names with commas, except for the last column name
o Avoid or minimize the use of an asterisk(*) in the select list. An asterisk is used to retrieve
all columns from a table.
Example: The next statement retrieves the Fname, Lname and sex columns of
all instructors from the instructor table.
Select Fname, Lname,sex from Instructor

Selecting ALL Columns (SELECT *)


Asterisk * is used to get all the columns of a particular table. For example the SQL select * from
Employee will retrieve the entire records of the employee table.
SELECT * FROM Employee

Eliminating Duplicate Rows using Distinct


To eliminate the duplicates from the result ser we use the key word DISTINCT.
Example: SELECT DISTINCT cno from student_course

Using the WHERE Clause to Specify Rows


Using the WHERE clause, you can retrieve specific rows based on given search conditions. The
search conditions in the WHERE clause can obtain an unlimited list of predicates.
Syntax:
<search_condition> uses expression {=|<>|>|>=|<|<=}expression

10
Prepared by Abinew Ali and Tsegaw Kelela

String expressions [NOT]LIKE string_expression


Expressions [NOT |BETWEEN]expression AND expression
When you specify rows with the WHERE clause, consider the following facts and guidelines:
o Place single quotation marks around all char, nchar,varchar,nvarchar, text, datetime, and
smalldatetime data
o Use a WHERE clause to limit the number of rows that are returned.
The next example retrieves the InstID, name and fatherName from the Instructor table in which their salary is
less than 5000 birr.
Select InstID, name ,fatherName from Instructor where salary<5000

4.2 FILTERING DATA


You can limit the results by specifying search conditions in a WHERE clause to filter data. There is
no limit to the number of search conditions that you can include in a SELECT statement. The
following table describes the type of filter and the corresponding search condition that you can use to
filter data.
Type of filter Search Condition
Type of Filter Search Condition
Comparison Operators =, <, >, >=, <=, and <>
String comparisons LIKE , NOT LIKE
Logical Operators: combination of conditions AND, OR
Logical Operators: negations NOT
Range of values BETWEEN , NOT BETWEEN
List of values IN , NOT IN
Unknown values IS NULL, IS NOT NULL

Using String Comparison


You can use the LIKE search condition in combinations with wildcard characters to select rows by comparing
character strings. When you use the LIKE search condition, consider the following facts:
o All characters in the pattern string are significant, including leading and trailing blank spaces
o Like can be use only with data of the char, nchar, varchar, nvarchar,binary,
varbinary,smalldatetime or datetime data types, and under certain conditions, with text, ntext, and
image data types

Wildcard Description
% Any string of zeros or more characters
underscore ( _) Any single character
[] Any Single character within the specified ranges or set
[^] Any single character not within the specified range or set

Examples
Expression Returns
LIKE ‗Br%‘ Every name beginning with the letters BR
LIKE ‗%een‘ Every name containg the letters en
LIKE ‗_en‘ Every three letter name ending in the letters en
LIKE ‗[CK]%‘ Every name beginning with the letter C or K
LIKE ‗[S-V] ing‘ Every four letter name ending with ing and beginning with single letter from S to V
LIKE ‗M[^c]%‘ Every name beginning with the letter M that does not have
11
Prepared by Abinew Ali and Tsegaw Kelela

Logical and grouping operators (Parenthesis)


Use the logical operators AND, OR, and NOT to combine a series of expressions and to refine query
processing. The results of a query may vary depending on the grouping of expressions and the order
of the search conditions.
When you use logical operators:
 Use the AND operator to retrieve rows that meet all of the search criteria
 Use the OR operator to retrieve rows that meet any of the search criteria
 Use the NOT operator to negate the expressions that follows the operator.

Microsoft SQL Server evaluates the NOT operator first, followed by the AND operator and then
the OR operator. The Precedence order is from left to right if all operators in an expression are of
the same level.

EXAMPLE1
SELECT name, fatherName FROM Student
WHERE
sex <>’ F’ AND AcademicStatus <> 'Good'
OR
sex <>’ F’ AND dno <> 10

EXAMPLE 2
SELECT name, fatherName FROM Student
WHERE
(sex <>’ F’ AND AcademicStatus <> 'Good')
OR
(sex <>’ F’ AND dno <> 10)
EXAMPLE 3
SELECT name, fatherName FROM Student
WHERE
(sex <>’ F’ AND AcademicStatus <> 'Good')
AND
(sex <>’ F’ AND dno <> 10)

Using List of Values as Search Criteria


Use the IN search condition in the where clause to retrieve rows that match a specified list of values.

When you use the IN search condition, use either the IN search condition or a series of comparison
expressions that are connected with an OR operator.
Example:
List the name of Instructors in department 5 or department 10
USE Registrar
SELECT name, fatherName FROM Instructor Dno IN (5, 10)

12
Prepared by Abinew Ali and Tsegaw Kelela

Retrieving Unknown Values


A column has a null value if no value is entered during data entry and no default values are defined
for that column. A null value is not the same as entries with a zero (a numerical value) or a blank (a
character value)

Use the IS NULL search condition to retrieve rows in which information is missing from a specified
column.

Use the IS NOT NULL search condition to retrieve rows that have known values in the specified
columns.

Example: List all curricula that are not yet approved.


USE Registrar
SELECT * from Curriculum where appovedDate IS NULL

Exercises
1. List the name of female students
2. List all students in department 20
3. List the name of female students in department 20
4. List name and department of female students whose academic status is Passs
5. List name, id and department of male students except Asmare and Sisay
6. List name, sex and age of all students whose fname starts with ‗A‘ and ends with ‗ew‘
7. Show the name of instructors whose salary lies within the range of 10 and 15 thousands
8. Show all students whose academic status is not yet determined

13
Prepared by Abinew Ali and Tsegaw Kelela

Lab Session 5: FORMATTING RESULT SETS


 Sorting Data
 Changing Columns Names (Aliases)
Objective:
The main objectives of this laboratory session are:
 Sorting rows in the result set in ascending (ASC) or descending (DESC) order
 Changing Columns Names (Aliases)
 Eliminating Duplicate Rows
 Sorting Data

The SELECT DISTINCT Statement


In a table, a column may contain many duplicate values; and sometimes you only want to
list the different (distinct) values. The DISTINCT keyword can be used to return only
distinct (different) values.
Syntax: SELECT DISTINCT column_name_list FROM table_name;

Example: Select Distinct adress From Employee

The ORDER BY clause


Use the ORDER BY clause to sort rows in the result set in ascending (ASC) or descending (DESC) order. When
you use the ORDER BY clause, consider the following facts and guidelines:

 Sort is in ascending order by default


 You can sort by column names, computed values, or expressions
 Columns that are included in the ORDER BY clause do not have to appear in the select list.
 You can not use text, ntext, or image columns in the ORDER BY clause
 If the ORDER BY clause is used with a UNION statement, then the columns on which you
sort must be the column names or aliases specified in the first SELECT statement.

14
Prepared by Abinew Ali and Tsegaw Kelela

Syntax:

SELECT column_name_list FROM table_name ORDER BY column_name ASC|DESC;

Example1: Select * From Employee Order By lname Desc

The UNION Operator


The UNION operator is used to combine the result-set of two or more SELECT statements.
Notice that each SELECT statement within the UNION must have the same number of columns. The
columns must also have similar data types. Also, the columns in each SELECT statement must be in
the same order.
Syntax: Select * From Table1 UNION Select * From Table2

Example2: Select * From Student Union Select * From Employee

You can also select some of the attributes that have same data types from the two tables:
Example: Select fname,salary,adress from employee Union select lname,age,adress from student

Example3:
SELECT EmployeeNumber, FirstName, LastName from Employee UNION SELECT cust_id,
fname, servedbyemp from customer ORDER BY FirstName;
15
Prepared by Abinew Ali and Tsegaw Kelela

SQL Aliases
SQL aliases are used to give a database table or a column in a table, a temporary
name. Basically aliases are created to make column names more readable.
Aliases can be useful when:
 There are more than one table involved in a query
 Functions are used in the query
 Column names are big or not very readable
 Two or more columns are combined together

SQL Alias Syntax for Columns


SELECT column_name AS alias_name FROM table_name;

SQL Alias Syntax for Tables


SELECT column_name(s) FROM table_name AS alias_name;

Examples:
//SQL Alias for Columns:

SELECT emp_id AS id FROM employee;

//SQL Alias for Tables: SELECT emp_id, adress FROM employee AS Emp;

The following example merges/Combines 4 colums of the employee table into one column
alias (adress column):
Example:

SELECT State+','+city+', '+woreda+','+kebele AS Adress FROM Employee;

16
Prepared by Abinew Ali and Tsegaw Kelela

Exercises

1. Write SQL statement to show the list of all database courses. The result should be ordered in
alphabetical order of their titles.
2. Write SQL statement to show the list of all female instructors. Abbreviated column names
should be shown with their expanded form in the result.
3. Write SQL statement to show the list of unique set of credit hour values in the course table.
4. Write SQL statement to show the combined list of the university community (i.e, name of
instructor and student community in one result set)

17
Prepared by Abinew Ali and Tsegaw Kelela

Lab Session 6: GROUPING AND SUMMARIZING DATA


 LISTING THE TOP N VALUES
 USING AGGREGATE FUNCTIONS
 Using Aggregate Functions with NULL Values
GROUP BY Fundamentals
 Using the GROUP BY Clause
 Using the GROUP BY Clause with the HAVING Clause
 Using the GROUPING Function

The SELECT TOP Clause

The SELECT TOP clause is used to specify the number of records to return/returns the top
n values. The SELECT TOP clause can be very useful on large tables with thousands of
records. Returning a large number of records can impact on performance.

Note: Not all database systems support the SELECT TOP clause.

Syntax: SELECT TOP number|percent column_name(s) FROM table_name;

Example: Select Top 5 Salary From Employee Order By salary Desc

Example2: The query to retrieve the top 25% of all employees in descending order of their salary.

Select Top 25 percent Salary From employee order by salary desc;

18
Prepared by Abinew Ali and Tsegaw Kelela

Using WITH TIES Clause


Example:
SELECT TOP 5 WITH TIES fname, lname, gender,salary FROM employee
ORDER BY salary DESC;

USING AGGREGATE FUNCTIONS


Functions that calculate averages and sums are called aggregate functions. When an aggregate
function is executed, SQL Server summarizes values for an entire table or for groups of columns
within the table, producing a single value for each set of rows for the specified columns.
 You can use aggregate functions with the SELECT statement or in combination with the
GROUP BY clause
 With the exception of the COUNT(*) function, all aggregate functions return a NULL if no
rows satisfy the WHERE clause. The COUNT(*) function returns a value of zero if no rows
satisfy the WHERE clause.
Syntax:
SELECT ALL| DISTINCT
TOP n [PERCENT] [WITH TIES]<select _list>
INTO new table
FROM <table_source >
WHERE <search_conditions>
GROUP BY ALL<group by expressions>
HAVING <search conditions>
ORDER BY <column name >[ASC|DESC]
The following example calculates the average salary of all employees in the employee table.
Select AVG (salary) from employee
The following example adds all rows in the salary column in the employee table and returns the sum
of all row values of the salary column.
Select sum(salary) From Employee

19
Prepared by Abinew Ali and Tsegaw Kelela

Using Aggregate Functions with NULL Values

Null values can cause aggregate functions to produce unexpected results. For example, if you
execute a SELECT statement that includes a COUNT function on a column that contains 18 rows,
two of which contain null values, your result set returns a total of 16 rows. SQL Server ignores the
two rows that contain null values. Therefore, use caution when using aggregate functions on
columns that contain null values, because the result set may not be representative of your data.
However, if you decide to use aggregate functions with null values, consider the following facts and
guidelines:
 SQL Server aggregate functions, with the exception of the COUNT(*) function, ignore null
values in columns.
 The COUNT(*) function count all rows, even if every column contains a null value.
For example, if you execute a SELECT statement that includes the COUNT(*) function on a column
containing a total of 18 rows, 2 of which contain null values, your result set returns a total of 18 rows.
The following example lists the number of employees in the employees table

Select count (*) From employee

GROUP BY Fundamentals
The GROUP BY clause groups rows on the basis of similarities between them. For example, to
group all the rows in the Customer table on the basis of the city, the result set of which would be the
creation of one group of Customer per town showing the number of customers found in each city.
Example: SELECT city, count(*) FROM customer Group by city

20
Prepared by Abinew Ali and Tsegaw Kelela

If you want to generate summary values for a column, use aggregate functions with GROUP BY
clause. Use the HAVING clause with GROUP BY clause to restrict the groups of rows that is
returned in the result set.

Note: Using GROUP BY clause does not guarantee a sort order. If you want the results to be sorted,
include the ORDER BY clause.
When you use the GROUP BY clause, consider the following facts and guidelines:
 SQL Server produces a column of values for each defined group
 SQL Server returns only single rows for each group that you specify; it does not return detail
information.
 All columns that are specified in the GROUP BY clause must be included in the select list.
 If you include a WHERE clause, SQL Server groups only the rows that satisfy the WHERE
clause conditions
 Do not use the GROUP BY clause on columns that contain multiple null values because the
null values are processed as a group.
 Use the ALL keyword with the GROUP BY clause to display all rows with null values in the
aggregate columns, regardless of whether the rows satisfy the WHERE clause.

Using the GROUP BY Clause with the HAVING Clause

Use the HAVING clause on columns or expressions to set conditions on the groups included in a
result set. The HAVING clause sets conditions on the GROUP BY clause in much the same way that
the WHERE clauses interacts with the SELECT statement.
When you use the HAVING clause, consider the following facts and guidelines:
 Use the HAVING clause only with the GROUP BY clause to restrict the grouping.
 Using the HAVING clause without the GROUP BY clause is not meaningful.
21
Prepared by Abinew Ali and Tsegaw Kelela

 You can reference any of the columns that appear in the select list.
 Do not use the ALL keyword with the HAVING clause because the HAVING clause
overrides the ALL keyword and returns groups that satisfy only the HAVING clause.
The following example lists the number of each city where we have more than one customer.
SELECT city, count(*) FROM customer Group by city
SELECT city, count(*) From Customer group by city Having count(*) >1

EXERCISES:
Create the student_course table as shown in the logical model indicated at the appendix of this
manual to solve the following problems:

1. Show the total number of credit hours taken by the first semester of 2007.
2. For each course, show the number of students registered for the course
3. For each student who has registered for at least one course, show the student Id, year and
the number of courses.
4. For each course that are taken in the first semester of 2007, give the course code, the total
credit hours and number of students registered for that course.
5. For each students who are registered in 2007, show the numbers of courses in which he/she
scored B or better grades

22
Prepared by Abinew Ali and Tsegaw Kelela

Lab Session 7: IMPLEMENTING DATA INTEGRITY CONSTRAINTS

Objective: After the end of this session, students will be able to:
 Describe the types of data integrity
 Describe the methods to enforce data integrity
 Determine which constraint to use, and create constraints.
 Define and use Primary key, foreign key, Check, Unique, and Default constraints.
 Disable constraints

Introduction
An important step in database planning is deciding the best way to enforce the integrity of the
data. Data integrity refers to the consistency and accuracy of data that is stored in a database.
The different types of data integrity are: Domain Integrity, Entity Integrity, and Referential
Integrity
Constraints are the preferred method of enforcing data integrity. Each type of data integrity,
domain, Entity, and referential – is enforced with separate types of constraints. Constraints
ensure that valid data values are entered in columns and that relationship are maintained
between tables.

Creating Constraints
You create constraints by using the CREATE TABLE OR ALTER TABLE statement. You can add
constraints to a table with existing data, and you can place constraints on single or multiple
columns:
 If the constraint applies to a single column, it is called a column-level constraint
 If a constraint references multiple columns, it is called a table-level constraint, even if it
does not reference all columns in the table.

CREATE TABLE table-name


Column_definition
<table_constraint >
<column_definition>= column_name data type
Default constant_expression
< column_constraint>
CONSTRAINT constraint_name
[Primary key| Unique ]
[clustered | Nonclustered]
Foreign key References ref_table [ref_column]
ON DELETE {CASCADE| NO ACTION}
ON UPDATE {CASCADE| NO ACTION}
CHECK (logical_expression)
Example1. This example creates a constraint in student table.

23
Prepared by Abinew Ali and Tsegaw Kelela

Create table student


(StudentID int IDENTITY (1,1) NOT NULL,
StudentName varchar(30) constraint DF_NAME DEFAULT 'Unknown',
Age int constraint CK_age CHECK (age >=18),
Sex char,
DNO int,
CONSTRAINT PK_STUDENT PRIMARY KEY(StudentID),
CONSTRAINT FK_STUDENT FOREIGN KEY (Dno) references Department(Dno)
ON UPDATE CASCADE ON DELETE CASCADE
)
Consider the following facts when you implement or modify constraints:

 You can create, change & drop constraints without having to drop & recreate a table.
 You must build error-checking logic into your applications and transactions to test
whether a constraint has been violated.
 SQL Server verifies existing data when you add a constraint to a table.
 You must specify names for constraints when you create them, because SQL Server
provides complicated, system-generated names. Names must be unique to the database
object owner and follow the rules of SQL Server identifiers.

Types of Constraints
1. DEFAULT Constraints
A default constraint enters a value in a column when one is not specified in an INSERT
statement. Default constraint enforce domain integrity

Syntax: CONSTRAINT [constraint name] DEFAULT [constraint expression]


Example:
ALTER TABLE student ADD CONSTRAINT DF_studentname DEFAULT 'UNKNOWN' FOR fName
Consider the following facts when you apply a DEFAULT constraint:
 It verifies existing data in the table.
 It applies only to INSERT statements
 Only one DEFAULT constraint can be defined per column
 It cannot be placed on columns with the Identity property or on columns with the row
version data type.
2. CHECK Constraints
A check constraint restricts the data that users can enter into a particular column to specific
values. CHECK constraints are similar to WHERE clauses in that you can specify the conditions
under which data will be accepted.

Syntax: CONSTRAINT [constraint name] CHECK (logical expression)

24
Prepared by Abinew Ali and Tsegaw Kelela

This example adds a CHECK constraint to ensure that the birth date conforms an acceptable
range of dates.

ALTER TABLE EMPLOYEE ADD CONSTRAINT CK_DoB CHECK (DoB >'01-01-1990')

Consider the following facts when you apply a CHECK constraint


 It verifies data every time when you execute an INSERT or UPDATE statement
 It can reference other columns in the same table
 It cannot contain subqueries
 If any data violates the CHECK constraint, you can execute the DBCC
CHECKCONSTRAINTS statement to return the violating rows.
3. PRIMARY KEY Constraints
A PRIMARY KEY constraint defines a primary key on a table that uniquely identifies a row. It
enforces entity integrity.
Syntax: CONSTRIANT (constraint name)
Example: This example adds a constraint that specifies that the primary key value of the
Student table is the student identification and indicates that a nonclustered index will be
created to enforce the constraint.

ALTER TABLE Student ADD CONSTRAINT PK_Student PRIMARY KEY (StudentID)

Consider the following facts when you apply a PRIMARY KEY constraint:
 The values entered must be unique
 Null values are not allowed
 It creates a unique index on the specified columns. You can specify a clustered or
nonclustered index. Clustered is the default.
The index created for a PRIMARY KEY constraint cannot be dropped directly. It is dropped
when you drop the constraint. If you want to assign more than one column as a Primary key
constraint, you can define the primary keys when you create the table. The following example
creates two primary keys (composite keys) for the CourseRegistration table:
Create table CourseRegistration (StudentID int not null, CourseCode int not null,
Primary Key (StudentID, CourseCode))
4. UNIQUE Constraints
A unique constraint specifies that two rows in a column cannot have the same value. This
constraint enforces entity integrity with a unique index. A unique constraint is helpful when
you already have a primary key, such as an employeenumber, but you want to guarantee that
other identifiers, such as an employee’s driverlicensenumber, are also unique.

Syntax: CONSTRINT [constraint name] UNIQUE [CLUSTERED|NONCLUSTERED] (column)

This example crates a UNIQUE constraint on the Employee F_name in the Employee table.

ALTER TABLE Employee ADD CONSTRAINT U_fname UNIQUE NONCLUSTERED(fname)


25
Prepared by Abinew Ali and Tsegaw Kelela

5. FOREIGN KEY Constraints


A FOREIGN KEY constraint enforces referential integrity. The FOREGIN KEY constraint defines
a reference to a column with a PRIMARY KEY or UNIQUE constraint in the same, or another
table.

Syntax:
CONSTRAINT [constraint name]FOREIGN KEY [column] REFERENCES ref_table (ref_column)
This example uses a FOREIGN KEY constraint to ensure that department identification in the
student table is associated with a valid identification in the department table.
ALTER TABLE Student ADD CONSTRAINT FK_Student FOREIGN KEY(Dno)
REFERENCES Department(Dnumber)
Consider the following facts and guidelines when you apply a Foreign key constraint:
 It provides single or multicolumn integrity. The number of columns and data types that
are specified in the FOREIGN KEY statement must match the number of columns and
data types in the REFERENCES clause.
 To modify data, users must have SELECT or REFERENCES permissions on other tables
that are referenced with a FOREIGN KEY constraint.
 You can use the REFERENCES clause without the FOREIGN KEY clause whenyou
reference a column in the same table.
6. Cascading Referential Integrity
The FOREIGN KEY constraint includes a CASCADE option that allows any changes to a column
value that defines a UNIQUE or PRIMARY KEY constraint to automatically propagate the
changes to the foreign key value.
Syntax: CONSTRAINT constraint_name REFERENCES ref_table (ref_column)
ON DELETE CASCADE| NO ACTION
ON UPDATE CASCADE | NO ACTION
Example: Create table department
(Dnumber int Primary Key not null, dname varchar(12), dlocation varchar(12))
Create table student
(studId Int primary key, fname varchar(20), sex char(6), age int, DepNo int foreign key
references Department(DNumber) on delete cascade on update cascade)
NO ACTION specifies that any attempt to delete or update key references by foreign key in
other tables raises an error and the change is rolled back. NO action is the default.
If CASCADE is defined and a row is changed in the parent table, the corresponding row is then
changed in the referencing table. For example if we update the Department table primary key
(i.e. Dnumber & if we specifies CASCADE the modification will be propagated in the Student
table for the row Dno).

7. Disabling Constraints
When you define a constraint on a table that already contains data, SQL Server check the data
automatically to verify that it meets the constraint requirements. However, you can disable
constraint checking on existing data when you add a constraint to the table.
26
Prepared by Abinew Ali and Tsegaw Kelela

Consider the following guidelines for disabling constraint checking on existing data:
 You can disable only CHECK and FOREIGN KEY constraints. Other constraints must be
dropped and then added again.
 To disable constraint checking when you add a CHECK or FOREIGN KEY constraint to a
table with existing data, include the WITH NOCHECK option in the ALTER TABEL
statement.
 Use the WITH NOCHECK option if existing data will not change. Data must conform to
CHECK constraints if the data is updated.
 Be certain that it is appropriate to disable constraint checking. You can execute a query
to change existing data before you decide to add constraint.
You can disable constraint checking on existing CHECK and FOREIGN KEY constraints so that
any data that you modify or add to the table is not checked against the constraint.

To avoid the costs of constraint checking, you might want to disable constraints when:
 You already have ensured that the data conform the constraints.
 You want to load data that does not conform to the constraints. Later, you can execute
queries to change the data and then re-enable the constraints.
Disabling constraints on one table does not affect constraints on other tales that reference the
original table. Updates to a table still can generate constraint violation errors. Enabling a
constraint that has been disabled requires existing another ALTER TABLE statement that
contains either a CHECK or CHECK ALL clause

To Add a constraint that can check and prohibit age entries <30 use:
Alter Table student with nocheck add constraint ck_age check (age>31)
To disable the constraint, use:
Alter Table student nocheck constraint ck_age
To Re-enable the constraint, use:
Alter Table student check constraint ck_age
EXERCISES:

1. Create all the possible constraints (primary key, foreign key, default, check/nocheck,
unique key …..) for the logical database schema given on the Anex.
2. Add a constraint that can restrict sex entries only in ‘M’ or ‘F’ of the student table.
3. Disable the constraint that restricts sex entries on the student table.
4. Re-enable the constraint that restricts sex entries on the student table.
5. List the name of students whose GPA is greater than 3.
6. List the title of the course taken by the student whose name is Elias.

27
Prepared by Abinew Ali and Tsegaw Kelela

28
Prepared by Abinew Ali and Tsegaw Kelela

Lab Session 8: JOINING MULTIPLE TABLES


Objective: At the end of this lesson, students will be able to understand and implement the
following concepts:

 Joining tables to produce a single result set


 Using Inner Joins to join records from different tables
 Using Outer Join to join records from different tables
 Using CROSS Join to join records from different tables

Types of Joins
 Cross Join
 Inner Join
 Outer Join
 Left Outer Join
 Right Outer Join
 Full Outer Join

We use joins to combine rows of two or more tables and produce a single result set that incorporates
rows and columns from these tables.
Syntax:
Select columnNameList From tableName {INER JOIN | LEFT JOIN | RIGHT JOIN | FULL OUTER
Join| CROSS JOIN } On Joining condition

When you implement joins, consider the following facts and guidelines:
 Whenever possible, specify the join condition based on the primary and foreign keys;
however, you may use any other columns if required.
 It is advisable to use entire key in the ON clause when you join tables
 Use shared (common) columns to join tables. The columns used in the joining condition
should have the same or compatible data types
 Try to limit the number of tables in a join, since SQL takes too much time to process the
query
CROSS Join
 Cross joins display every combination of all rows in the joined table. A shared column is not
required to use cross joins.
 Cross join are rarely used on a normalized database, most often used to generate testing data
from a few rows when you need a large number of records.

Example:
List all possible combinations of the values in the Instructor name and the department name
Select FName, DName From Instructor cross join Department

29
Prepared by Abinew Ali and Tsegaw Kelela

INNER JOIN
Inner Joins combine tables by computing values in columns that are common to both tables. SQL
Server returns only rows that match the join condition.
Inner Joins are the SQL Server default. So you can use JOIN instead of INNER JOIN
Do not use a null value as a join condition because null values do not evaluate equally with one
another.
Syntax: SELECT column_name(s) FROM table1. INNER JOIN table2. ON
table1.column_name=table2.column_name ………………………….
Example 1: Retrieve the name of each instructor with the name of the department for which she/he
is working.
Select, name, fatherName,salary, Dname From Instructor INNER JOIN Department
ON instructor.Dno = Department.DNO
Example 2: List all departments with the name of the person who is leading the department.
Select, dname, name,fatherName From Department d INNER JOIN Instructor i
ON d.dept_Head_Id = i. instId
Using Outer Join
Left or Right outer joins combine rows from two tables that match the join condition, plus many
unmatched rows of either the left or right table is specified in the JOIN clause.
 Rows that do not match the join condition display NULL in the result set.
 You can use full outer joins to display all rows in the joined tables, regardless of whether
the tables have any matching values.
LEFT OUTER JOIN
This join returns all the rows from the left table in conjunction with the matching rows from the right
table. If there are no columns matching in the right table, it returns NULL values.
Example: Retrieve the name of each instructor with the name of the department managed by
him/her. Note that those instructors who are not department heads will be shown in the result.
Select name,fatherName,dname From Instructor i Left JOIN departement d
ON i. instId = d.headId

Figure 8.1. Result of left outer join query

30
Prepared by Abinew Ali and Tsegaw Kelela

RIGHT OUTER JOIN


This join returns all the rows from the right table in conjunction with the matching rows from the left
table. If there are no columns matching in the left table, it returns NULL values.

Example:
List all departments with the name of the person who is managing it.
Select dname,name,fatherName From Instructor i Right JOIN departement d
ON i. instId = d.headId

Figure 8.2. Result of right outer join query

Note: You can omit the word OUT in Right or Left outer join query statements. You can also omit
the word INNER in INNER JOIN
That means, the following query blocks are same:
RIGHT OUTER JOIN  has the same effect with writing RIGHT JOIN
LEFT OUTER JOIN  has the same effect with writing LEFT JOIN
INNER JOIN has the same effect with writing JOIN.
FULL OUTER JOIN
This join combines left outer join and right outer join. It returns row from either table when the
conditions are met and returns null value when there is no match.
Example:
List all departments with the name of the person who is managing it. The following result is
displayed when the query is executed against an Instructor table with 3 records and department table
having two records.
Only CS department has a head assigned to it.
Ali is the only person assigned as a department head
31
Prepared by Abinew Ali and Tsegaw Kelela

Fig 8.3 result of a full outer join query

Joining More Than Two Tables


It is possible to join any number of tables. Any table that is referenced in a join operation can be
joined to another table by a shared column.
Use multiple joins to obtain related information from multiple tables. When you join more than two
tables, consider the following facts and guidelines:
 You should have one or more tables with foreign key relationships to each of the tables that
you want to join
 The ON clause should reference each column that is part of a composite key
 Include WHERE clause to limit the number of rows that are returned.
 Although not recommended in today‘s coding, you can also use the old pre - 1992 standard
SQL inner join syntax in which the WHERE clause specifies the join style and columns.

Example: List the name of all students and the title of courses they have taken with the type of grade
scored on each courses.
Select fname,ctitle,lettergrade from student s inner join student_course
sc on s.studid=sc.studid inner join course c on sc.cno=c.cno
Using the old pre - 1992 standard SQL join syntax, this query can be re-written as follows
Select fname,ctitle,lettergrade from student s, student_course sc, course
c where s.studid=sc.studid and sc.cno=c.cno

EXERCISES
1. Retrieve the name and academic status of all students who are in IT department.
2. For each student, retrieve name and the department to which he/she belongs. The result is expected
show all students regardless of whether they are assigned to a department or not.
3. List the name of all departments with the name of instructors assigned to it. The result is expected to
show each department regardless of whether there are instructors assigned to it or not.
4. Retrieve the name of all female instructors together with the title of the course they are teaching. The
result should be filtered to only those who are teaching in the second semester of 2007 academic year.
5. Retrieve the title of all courses taken by more than 50 students. The result should show course title
and total number of students registered for that course.

32
Prepared by Abinew Ali and Tsegaw Kelela

Lab Session 9: UPDATING DELETING AND TRUNCATING DATA

Lesson Objectives: at the end of this lesson students will be able to:
 Modify data using update statement
 Remove records using delete and truncate statements
 Use transactions to modify data.
Updating Data
The UPDATE statement enables you to update existing rows in a table. The standard UPDATE
statement has the following form:-
UPDATE <target table>
SET <col 1> = <expression 1>,
<col 2> = <expression 2>,
...,
<col n> = <expression n>
[WHERE <predicate>]

You specify the target table name in the UPDATE clause. If you want to filter a subset of rows, you
indicate a WHERE clause with a predicate. Only rows for which the predicate evaluates to true are
updated. Rows for which the predicate evaluates to false or unknown are not affected. An UPDATE
statement without a WHERE clause affects all rows. You assign values to target columns in the SET

clause.
Example 1: the following Update statement can be used to increase the salary of all instructors by 25 %
Update instructor set salary =salary +salary*.25

Example 2: the following Update statement can be used to increase the salary of female instructors by 50 %
Update instructor set salary =salary +salary*.25 where sex ='F'

When you update rows, consider the following facts and guidelines:
 Specify the rows to update with the WHERE clause
 Specify the new values with the SET clause
 Verify that the input values have compatible data types with the data types that are
defined for the columns
 SQL Server does not update rows that violate any integrity constraints.

Specifying Rows to Update Using Joins


When you use joins to update rows, use the FROM clause to specify joins in the UPDATE
Statement.
The follwing example uses a join to update the Instructor table by adding 30 % to the
salary of female instructors who are working in IT department:

Update i set salary =salary +salary*.25


from instructor i inner join department d
on i.dno=d.dno where sex ='F' and dname='IT'
33
Prepared by Abinew Ali and Tsegaw Kelela

UPDATE using Common Table Expression (CTE)


This capability can be useful when you want to be able to see which rows are going to be modified
before you actually apply the update.
Example: we can use CTE to update the Instructor table by adding 40 % to the salary of female
instructors who are working in IT department.
With I as
(
select fname,lName,sex,salary from instructor i inner join department d
on i.dno=d.dno
)
Update I set salary=salary*1.40

Deleting Data
 DELETE Statement
We can use the DELETE statement to delete rows from a table. We can optionally specify a
predicate to restrict the rows to be deleted. The general form of a DELETE statement looks like the
following:
DELETE FROM <table Name>
WHERE <predicate>

If you don‘t specify a predicate, all rows from the target table are deleted. As with unqualified
updates, you need to be especially careful about accidentally deleting all rows by highlighting only
the DELETE part of the statement, missing the WHERE part.
Example: remove all courses with less than two credit hours
Delete from course where crHr <2

DELETE Based on a Join


Enable us to delete rows from one table based on information evaluated in related rows in other
tables.
Example: Remove records of all male Instructors who are working in IT department
delete from i
from instructor i inner join department d
on i.dno=d.dno
Where sex ='M' and dname='IT'

DELETE Using Common Table Expressions


Like with updates, T-SQL supports deleting rows by using table expressions. The idea is to use
CTE or a derived table to define the rows that you want to delete, and then issue a DELETE
statement against the table expression.

34
Prepared by Abinew Ali and Tsegaw Kelela

Example: to remove records of all male Instructors who are working in IT department, we can use
the following CTE:

With maleInstructors as
(
select fname,lName,sex,salary from instructor i inner join department d
on i.dno=d.dno Where sex ='M' and dname='IT'
)
DELETE from maleInstructors

TRUNCATE Statement
The TRUNCATE statement deletes all rows from the target table. Unlike the DELETE statement, it
doesn‘t have an optional filter, so it‘s all or nothing.
As an example, the following statement truncates the course table.
TRUNCATE TABLE Course
After executing the statement, the target table is empty.
The DELETE and TRUNCATE statements have a number of important differences between them:
 The DELETE statement writes significantly more to the transaction log compared to the
TRUNCATE statement. For DELETE, SQL Server records in the log the actual data that was
deleted. For TRUNCATE, SQL Server records information only about which pages were de
allocated. As a result, the TRUNCATE statement tends to be substantially faster.
 The DELETE statement doesn‘t attempt to reset an identity property if one is associated with a
column in the target table. The TRUNCATE statement does.
 The DELETE statement is supported if there‘s a foreign key pointing to the table in question as
long as there are no related rows in the referencing table. TRUNCATE is not allowed if a foreign
key is pointing to the table—even if there are no related rows in the referencing table, and even if
the foreign key is disabled.
 The DELETE statement requires DELETE permissions on the target table. The TRUNCATE
statement requires ALTER permissions on the target table.

When you need to delete all rows from a table, it is usually preferred to use TRUNCATE because it
is significantly faster than DELETE. However, it does require stronger permissions, and is more
restricted.

EXERCISES
Write T-SQL statements to provide solutions to the next questions

1. Modify the academic status of all students to PASS


2. Increase the salary of female Instructors by 10% for those who are earning less than the
average salary of all instructors
3. Delete all Instructors supervised by Kebede Sisay
4. Use CTE to remove all records of students taking database courses
5. Truncate the student table

35
Prepared by Abinew Ali and Tsegaw Kelela

Lab Session 10: SUBQUERIES

Objectives: At the end of this lesson students will be able to:


 Describe when and how to use a sub query
 Use sub queries to break down and perform complex queries
 Discuss how correlated queries are processed.
A sub query is a SELECT statement nested inside a select, insert, update or Delete
statement or inside another sub query. Often, you can rewrite sub queries as joins and use
Sub queries in place of an expression.
An expression is a combination of identifiers, values, and operations that SQL server
evaluates to obtain a result.
You use sub queries to break down a complex query into a series of logical steps to solve a
problem with single statements. Sub queries are useful when your query relies on the
results of another query.
How to use Sub queries
When you decide to use sub queries, consider the following facts and guidelines:
 You must enclose sub queries in parentheses
 You can use a sub query in place of an expression as long as a single value or list of
values is returned. You can use a sub query that returns a multicolumn record set in
place of a table or to perform the same function as a join
 You cannot use sub queries that retrieve columns that contain text and image data
types
 You can have sub queries within sub queries, nesting up to 32 levels.
Using a Sub query as a Derived Table
You create a derived table by using a sub query in place of a table in FROM clause. A
derived table is a special use of a sub query in a FROM clause to which an alias or user
specified name refers. The result set of the sub query in the FROM clause forms a table
that the outer SELECT statement uses
This example uses a sub query to create a derived table in the inner part of the query that
the outer part queries. The derived table itself is functionally equivalent to the whole query,
but it is separated for illustrative purposes
select i.instId , i.fname from (select * from instructor) as i

36
Prepared by Abinew Ali and Tsegaw Kelela

Using a Sub query as an Expression


In Transact-SQL, you can substitute a sub query wherever you use an expression. The sub query
must evaluate to a scalar value, or to a single column list of values. Sub queries that return a list of
values replace an expression in Where CLAUSE THAT CONATINS the IN keyword.

When used as an expression, consider that a sub query:


 Is evaluate and treated as an expression. The query optimizer often evaluates an expression
as equivalent to a join connecting to a table that has one row
 Is executed once for the entire statement
The following example returns the salary of an instructor, average salary of all instructors and the
difference between the salaries of each instructors and average salary of instructors.
select instId , name, fatherName,salary,
(Select avg(salary)from instructor)as'avg',
Salary - (select avg(salary)From instructor)as 'Diffrence' from
instructor

Sub queries can be self-contained—namely, independent of the outer query; or they can be
Correlated; namely, having a reference to a column from the table in the outer query. In terms of
the result of the sub query, it can be scalar, multi-valued, or table-valued.
Self-contained sub queries are sub queries that have no dependency on the outer query.
If you want, you can highlight the inner query and run it independently. This makes the
troubleshooting of problems with self-contained sub queries easier compared to correlated sub
queries.
Example of self contained subquery:
 List the name of instructors who are earning the minimum salary
select name,fathername from instructor where salary =(select min(salary) from instructor)

Correlated sub queries are sub queries where the inner query has a reference to a column from the
table in the outer query.
Correlated sub query break down complex queries into two or more simple, related queries.
When you create a correlated sub query, the inner sub queries are evaluated repeatedly, once for
each row of the outer query:
 SQL server executes the inner query for each row that the outer query selects.
 SQL server compares the results of the sub query to the results outside the sub
query
You can‘t just highlight the inner portion and run it independently. As an example, suppose that
you need to return list of instructors with the minimum salary per each gender category.
You can use a correlated sub query to return the minimum salary out of instructors sex is equal to
the one in the outer row (the correlation), as follows:
37
Prepared by Abinew Ali and Tsegaw Kelela

select name,fathername from instructor inst1 where salary =


(select min(salary) from instructor inst2 where inst1.sex=inst2.sex)

The IN, ALL, and ANY operators in sub query


A row from a table satisfies a condition with the IN operator if the value of a particular
column occurs in a set of expressions. The expressions in such a set entered one by one
by a user. The IN operator can also take another form in which it is unnecessary to list the
set of expressions. The set is determined by SQL at the point when the statement is
processed.

 The comparison operator is any one of the following =,<>, <, >, <=, >=.
SOME is a different word for ANY (or in other words, SOME and ANY perform the same
function).
 an ALL condition evaluates to TRUE if and only if the corresponding comparison
condition without the ALL evaluates to TRUE for all rows in the table represented in
the table expression.
Similarly, an ANY condition evaluates TRUE if and only if the corresponding comparison
condition without the ANY evaluates to TRUE for any of the rows in the table represented in
the table expression.
If the table is empty, then the ALL condition returns TRUE while the ANY condition returns
FALSE.
Example 1: Get the names of all Instructors whose salary is greater than the maximum of
departmental averages. For this query, first you have to find average salary of the
instructors in each of the departments; then, find the name whose salary is greater than the
maximum of those departmental averages.
Select fatherName,salary From instructor
Where salary > ALL (Select avg (salary) From instructor Group by dno)
Example 2: List the name of students who registered for all courses offered in 2007t
select *from student where studid IN (select studId from student_Course sc
where year=2007)

Using the Exists and NOT EXISTS Clauses


You can use the EXISTS and NON EXISTS operators to determine whether data exists in a
list of values.
Use the EXISTS and NOT EXISTS operators with correlated sub queries to restrict the
result set of an outer query to rows that satisfy the sub query. The EXISTS and NOT
EXISTS operators return TRUE or FALSE, based on whether rows are returned for sub
queries
When a sub query is introduced with the EXISTS operator, SQL Server tests whether data
that matches the sub query exists. No rows are actually retrieved.
When SQL Server processes sub queries that use the EXISTS OR NOT EXISTS operator:
 The outer query tests for the existence of rows that the sub query returns.

38
Prepared by Abinew Ali and Tsegaw Kelela

 The sub query returns either a TRUE or FALSE VALUE based on the given
condition in the query.
 The sub query does not produce any data.
Example 1: List the name of students who registered for all courses offered in 2007

select fname from student s where EXISTS (select * from student_Course sc


where s.studId=sc.studId and year=2007)
Exercises
Use sub queries to write SQL codes for the following queries

1. List the name of all departments offering database courses


2. List the name of all instructors who are working in a department with high salary payment
3. Find the name departments with no female instructor assigned to it
4. Find the name departments with at least one female instructor assigned to it
5. Find all courses in IT curriculum

39
Prepared by Abinew Ali and Tsegaw Kelela

Lab Session 11: CREATING VIEWS

Objectives: At the end of this lesson students will be able to:


 Create views on tables
 Update or alter different types of views
 Delete/Remove the Views that you have created

 A view is a virtual table that consists of columns from one or more tables
 Implements a security mechanism
View provides the ability to store a predefined query as an object in the database for later use.
The tables queried in a view are called base tables. With a few exceptions, you can name and
store any SELECT statement as a view. Common examples of views are:
 A subset of rows or columns of a base table
 A union of two or more base tables
 A join of two or more base tables
 A statistical summary of a base table
 A subset of another view, or some combinations of views and base tables

Advantages of Views
Views offer several advantages, including focusing data for users, simplifying permission
management, and organizing data for export to other applications.

Creating Views
You can create views by using the Create View Wizard, SQL Server Enterprise Manager, or
Transact-SQL. You can create views only in the current database.
When you create a view, MSSQL Server verifies the existence of objects that are referenced in
the view definition. Your view name must follow the rules for identifiers. Specifying a view
owner name is optional. You should develop a consistent naming convention to distinguish views
from tables.

Syntax: CREATE VIEW owner. view_name (column) WITH ENCRYPTION AS


Select_statement [WITH CHECK OPTION]
Example 1: This example creates a view that contains Instructor ID, Gender and Salary information.
Create View Instructor_information AS
SELECT InstID, sex, salary from Instructor
This statement queries the view to see the results.
Select * from Instructor_information

40
Prepared by Abinew Ali and Tsegaw Kelela

To execute the CREATE VIEW statement, you must be a member of the system administrators‘
role, database owner (dbo_owner) role, or the data definition language administrator
(dbo_ddladmin) role, or you must have been granted the CREATE VIEW permission. You must
have also a SELECT permission on all tables or views that are referenced within the view.

To avoid situations in which the owner of a view and the owner of the underlying tables differ, it
is recommended that the db user own all objects in a database. Always specify the dbo user as
the owner name when you create the object; otherwise, the object will be created with your user
name as the object owner.

You specify the contents of a view by using a SELECT statement. With a few limitations, views
can be as complex as you like. You must specify column names if:
 Any of the column of the view are derived from an arithmetical expression, built in
function, or constraint
 Any columns in tables that will be joined share the same name

When you create views, it is important to test the SELECT statement that defines the view to
ensure that SQL Server returns the expected result set.

Restrictions on View Definitions:


When you create views, consider the following restrictions:
 The CREATE VIEW statement cannot include the INTO keyword.
 The CREATE VIEW statement can include the ORDER BY clause, only if the TOP keyword is
used.
 Views cannot references temporary tables
 Views cannot references more than 1024 columns.
 The CREATE VIEW statement cannot be combined with other Transact-SQL statements
in a single batch.
Altering and Dropping Views
In this example, Instructors_HomeBase joins the Instructor and Department tables.
Altering View
Example 1: Create a View that to retrieve the name of each instructor with the name of the
department for which she/he is working.

Create View Instructors_HomeBase AS


Select I.name, I.fatherName, I.salary, d.Dname From Instructor I INNER JOIN
Department d ON i.Dno = d.DNO
Select * from Instructors_HomeBase

41
Prepared by Abinew Ali and Tsegaw Kelela

Example 2: Create a View to list all departments with the name of the person who is leading the
department.

Create View DepartmentInformation AS Select dname, name,fatherName


From Department d INNER JOIN Instructor i
ON d.depart_HeadId = i.instId

Select * from DepartmentInformation

Example 3: Create a View to Selects every Instructor in the "Instructor" table with a Salary higher
than the average Salary.
CREATE VIEW [Instructor Salary Above Average] AS

SELECT Name,fathername, Salary FROM Instructor

WHERE Salary> (SELECT AVG(salary) FROM Instructor)

Select * from [Instructor Salary Above Average]

The ALTER VIEW statement changes the definition of a view, including indexed views, without
affecting dependent stored procedures or triggers. This allows you to retain permissions of the view.

Note: if you use the WITH CHECK OPTION, WITH ENCRYPTION, WITH
SCHEMA_BINDING, WITH VIEW_METADATA option when you create the view, you must
include it in the ALTER VIEW statement if you want to retain the functionality that the option
provides.
The following example ALTER Instructor_information View to add the name column:
ALTER VIEW dbo.Instructor_information AS
SELECT instID, Name,fathername, Salary FROM Instructor
SELECT * From Instructor_information

42
Prepared by Abinew Ali and Tsegaw Kelela

Options when creating views


 SCHEMABINDING: Binds views to underlying tables. The view may have to be modified or
dropped to remove dependency on table

 CHECK OPTION: Forces all data modification statements executed against the view to
follow the criteria set within select statement. When a row is modified through a view, the
WITH CHECK OPTION makes sure the data remains visible through the view after the
modification is committed.
 ENCRYPTION: Encrypts the entries in sys.syscomments that contain the text of the CREATE
VIEW statement. Using WITH ENCRYPTION prevents the view from being published as part
of SQL Server replication.
Example of creating views with schemabinding option
Create view instructorsViews
with schemabinding
as select fname from dbo.instructor
Example of creating views with check option
Create view instructorsViews
with schemabinding
as select fname from dbo.instructor
with check option
Example of creating views with encryption option
Create view instructorsViews
with encryption
as
select fname from dbo.instructor
Dropping View
If you no longer need a view, you can remove its definition from the database by executing the
DROP VIEW statement. Dropping a view removes its definition and all permissions assigned to it.
Syntax: DROP VIEW view_name
The following example deletes the Instructor_information view from the database.
DROP VIEW Instructor_information
EXERCISES
 Create a view called NUMBER_Departemnt that contains all Departments and the total
number of Instructors who belong to that Department.
 Create a view called StudenInformation the contains the ID Number and name of each
Student who, for at least score Grade of C in each Course.
 Create a view called TOTALS that displays the total amount of Salaries for each
Instructor who earns salary greater than 5000.
 Remove the view called NUMBER_Departemnt that you have created above.
 Perform the following modfication operations (update, insert, and delete operations) for
the Instructor table?

43
Prepared by Abinew Ali and Tsegaw Kelela

Lab Session 12: Creating Index


Objectives:
 The objectives of this session are:
o Understanding the different index types
o Create index of different types
o Drop the already created indexes

Indexes:

An index is a database structure which is stored as an object to allow the database application to find
data fast without reading the whole table.
Index can be created in a table to find data more quickly and efficiently. The users cannot see the
indexes; indexes are just used to speed up searches/queries.
Note: Updating a table with indexes takes more time than updating a table without (because the
indexes also need an update). So you should only create indexes on columns (and tables) that will be
frequently searched against.
Types of indexes
The following are the index types available in SQL Server 2012:
 Clustered: determines the physical order of the table
 Non-clustered: Contains only keys and no actual data.
 Covering: INCLUDE columns for columns in the SELECT list that are not already part of the key columns
 Primary and secondary XML: designed for indexing this complex data type
 Spatial: important for good performance when querying spatial data.
 Full-text: token-based functional indexes that store information about significant words, where they exist
within text within a column or table in the database
 Columnstore: Organize data by columns rather than by rows

In this lesson, we will focus only on the most commonly used indexes which are Clustered and
non Non-clustered indexes.
Important points
 By default, SQL server creates a clustered index when primary key is defined on a
table
 If we don’t specify the index type, attempting to create an index on a non key column
will default to Non-clustered INDEX
 You can create only one clustered index per table
To Create Index, we use the following syntax:]

CREATE [UNIQUE|CLUSTERED |NONCLUSTERED]


INDEX index_name ON table_name (column_name1, column_name2..)

Note that:

 index_name is the name of the INDEX.


 table_name is the name of the table to which the indexed column belongs.
 column_name1, column_name2.. is the list of columns which make up the INDEX.

44
Prepared by Abinew Ali and Tsegaw Kelela

Example1:
The SQL statement below creates an index named "Inst_Index" on the "FatherName" column
in the "Instructor" table:
CREATE nonclustered index Inst_Index ON Instructor(FatherName)
If you want to create an index on a combination of columns, you can list the column names within
the parentheses, separated by commas:

Syntax:
CREATE INDEX indexType index_name ON table_name (column_name1,
column_name2);
Example 2: The SQL statement below creates an index named "Instructor_Index" on the ―Name‖
and "FatherName" column in the "Instructor" table:

CREATE UNIQUE INDEX Instructor_Index ON Instructor(Name,FatherName)

To Drop Index:

DROP INDEX <index_name> ON <table_name>

Exercise
Create the following indexes

A. Clustered index on course title column of Course table


B. Non Clustered index on dno column of Instructor table
C. unique index on Course title of course table
D. Non clustered index on salary column of instructor table
E. Unique index on the combination of nomenclature and approvedDate columns
in the Curriculum table

45
Prepared by Abinew Ali and Tsegaw Kelela

Reference
1) Microsoft SQL Server 2012 step by step. O’Reilly Media, Inc. 1005 Gravenstein Highway North
Sebastopol, California 95472
2) Microsoft SQL Server 2008, All –in –one Desk Reference for Dummies. 2008. Robert D.Schneider.
Wiley publishing inc.
3) Microsoft SQL Server 2008 a beginner’s guide. 2008. DusanPetkovic. McGraw Hill.

46
Prepared by Abinew Ali and Tsegaw Kelela

Annexes

Annex1: Logical data model of XYZ Registrar database

47

Вам также может понравиться