Lab Manual Fundamental of DB
Lab Manual Fundamental of DB
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
Syntax:.............................................................................................................................................................14
Reference.........................................................................................................................................................29
Annexes...........................................................................................................................................................30
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)
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.
6. Leave all of the defaults and Click OK when you finished. You should now have a new
database.
2
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:
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
Lab Session 2: CREATING, MODIFYING AND DELETING TABLES
Objective: The main objectives of this laboratory session are:
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
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
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
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
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.
(
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
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:
8
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
“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
9
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
10
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
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
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)
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
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.
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
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
Syntax:
14
SELECT column_name_list FROM table_name ORDER BY column_name ASC|DESC;
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
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
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
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
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
Using WITH TIES Clause
Example:
SELECT TOP 5 WITH TIES fname, lname, gender,salary FROM employee
ORDER BY salary DESC;
19
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
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.
You can reference any of the columns that appear in the select list.
21
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
6.
22
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.
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
This example adds a CHECK constraint to ensure that the birth date conforms an acceptable
range of dates.
24
ALTER TABLE EMPLOYEE ADD CONSTRAINT CK_DoB CHECK (DoB >'01-01-1990')
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.
25
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.
Consider the following guidelines for disabling constraint checking on existing data:
26
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
Lab Session 8: JOINING MULTIPLE TABLES
Objective: At the end of this lesson, students will be able to understand and implement the
following concepts:
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
28
Select FName, DName From Instructor cross join Department
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
Figur
e 8.1. Result of left outer join query
29
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
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
30
Fig 8.3 result of a full outer join query
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.
31
Lab Session 9: UPDATING DELETING AND TRUNCATING DATA
Lesson Objectives: at the end of this lesson students will be able to:
32
on i.dno=d.dno where sex ='F' and dname='IT'
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.
33
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
34
4. Use CTE to remove all records of students taking database courses
5. Truncate the student table
6.
35
Lab Session 10: SUBQUERIES
36
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.
37
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:
select name,fathername from instructor inst1 where salary =
(select min(salary) from instructor inst2 where inst1.sex=inst2.sex)
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
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.
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
Lab Session 11: CREATING VIEWS
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.
40
Select * from Instructor_information
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.
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
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:
42
ALTER VIEW dbo.Instructor_information AS
SELECT instID, Name,fathername, Salary FROM Instructor
SELECT * From Instructor_information
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.
43
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?
44
Laboratory Session 12: Creating Index
Objectives:
The objectives of this session are:
Understanding the different index types
Create index of different types
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
45
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.
Example 1:
The SQL statement below creates an index named "Inst_Index" on the "FatherName" column in the
"Instructor" table:
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:
DROP INDEX <index_name> ON <table_name>
Exercise
Create the following indexes
1. Clustered index on course title column of Course table
2. Non Clustered index on dno column of Instructor table
3. unique index on Course title of course table
4. Non clustered index on salary column of instructor table
5. Unique index on the combination of nomenclature and approvedDate columns
in the Curriculum table
46
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.
47
Annexes
48