Fundamental of DB Lab Manual
Fundamental of DB Lab Manual
Fundamental of DB Lab Manual
School of Computing
March, 2015
Prepared by:
Abinew Ali(Msc.)
Tsegaw Kelela(Msc.)
Table of Contents
Lab Session 1: INTRODUCING MICROSOFT SQL SERVER 2012 ENVIRONMENT AND CREATING, MODIFYING
AND DELETING DATABASES .................................................................................................................................1
Reference .......................................................................................................................................................... 46
Annexes ............................................................................................................................................................. 47
Prepared by Abinew Ali and Tsegaw Kelela
1. Start All Programs Microsoft SQL server 2012SQL Server Management Studio.
2. Click on Connect to your default instance as shown in the following figure.
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
6. Leave all of the defaults and Click OK when you finished. You should now have a new
database.
2
Prepared by Abinew Ali and Tsegaw Kelela
For example, to create a database with name ‘Test’, we write the following statement:
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:
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
3
Prepared by Abinew Ali and Tsegaw Kelela
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.
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
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.
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.
For example, to add the column age in the student table we write :
Deleting a Column
Deleting columns are unrecoverable. Therefore, be certain that you want to remove a column before doing
so.
6
Prepared by Abinew Ali and Tsegaw Kelela
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.
(
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.
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).
3. Modify the Staff table by modifying the data type of the age column to int.
7
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
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
10
Prepared by Abinew Ali and Tsegaw Kelela
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
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)
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
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.
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
14
Prepared by Abinew Ali and Tsegaw Kelela
Syntax:
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
Examples:
//SQL Alias for Columns:
//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:
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
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.
Example2: The query to retrieve the top 25% of all employees in descending order of their salary.
18
Prepared by Abinew Ali and Tsegaw Kelela
19
Prepared by Abinew Ali and Tsegaw Kelela
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
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.
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
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.
23
Prepared by Abinew Ali and Tsegaw Kelela
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
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.
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.
This example crates a UNIQUE constraint on the Employee F_name in the Employee 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
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
30
Prepared by Abinew Ali and Tsegaw Kelela
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
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
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
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.
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
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
35
Prepared by Abinew Ali and Tsegaw Kelela
36
Prepared by Abinew Ali and Tsegaw Kelela
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
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)
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
39
Prepared by Abinew Ali and Tsegaw Kelela
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.
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.
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.
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
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
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
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:]
Note that:
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:
To Drop Index:
Exercise
Create the following indexes
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
47