You are on page 1of 74

Database Management

Systems
Laboratory Manual

September,
2008

1
Table of Contents
BACKGROUND.................................................................................................................................................5
LABORATORY SESSION 1: INTRODUCING MICROSOFT SQL SERVER 2000 ENVIRONMENT 6
WHAT ARE QUERY ANALYZER AND ENTERPRISE MANAGER? .....................................................................................7
HOW TO USE QUERY ANALYZER:..........................................................................................................................7
HOW TO USE ENTERPRISE MANAGER:....................................................................................................................8
LABORATORY SESSION 2: CREATING, MODIFYING AND DELETING DATABASES...............10
I.CREATING A DATABASE....................................................................................................................................10
II.M ODIFYING A DATABASE.................................................................................................................................11
III.DELETING A DATABASE..................................................................................................................................11
EXERCISES:.......................................................................................................................................................12
LABORATORY SESSION 3: CREATING TABLES AND DATA TYPES..............................................13
CREATING TABLES.............................................................................................................................................13
DELETING A TABLE............................................................................................................................................14
MODIFYING A TABLE..........................................................................................................................................14
Adding a Column .....................................................................................................................................14
Deleting a Column...................................................................................................................................14
Generating Column Values......................................................................................................................14
LABORATORY SESSION 4: RETRIEVING DATA..................................................................................16
RETRIEVING DATA BY USING THE SELECT STATEMENT AND FILTERING DATA........................................................16
Using the SELECT Statement...................................................................................................................16
Specifying columns............................................................................................................................................16
Selecting ALL Columns (SELECT *)...........................................................................................................17
Eliminating Duplicates using DISTINCT......................................................................................................17
LABORATORY SESSION 5: FILTERING DATA.....................................................................................18
Logical and Grouping Operators (Parentheses).....................................................................................20
LABORATORY SESSION 6: FORMATTING RESULT SETS................................................................22
Sorting Data.............................................................................................................................................22
Eliminating Duplicate Rows.....................................................................................................................22
Changing Columns Names (Aliases)........................................................................................................22
Exercise:...................................................................................................................................................23
LABORATORY SESSION 7: GROUPING AND SUMMARIZING DATA.............................................25
LISTING THE TOP N VALUES..............................................................................................................................25
USING AGGREGATE FUNCTIONS...........................................................................................................................25
Using Aggregate Functions with NULL Values.......................................................................................26
GROUP BY Fundamentals.......................................................................................................................27
Using the GROUP BY Clause............................................................................................................................27
Using the GROUP BY Clause with the HAVING Clause...................................................................................27
Using the GROUPING Function........................................................................................................................29
LABORATORY SESSION 8: IMPLEMENTING DATA INTEGRITY/SPECIFYING
CONSTRAINTS\..............................................................................................................................................31
CREATING CONSTRAINTS.....................................................................................................................................31
TYPES OF CONSTRAINTS.....................................................................................................................................32
1.DEFAULT Constraints..........................................................................................................................32
2. CHECK Constraints ............................................................................................................................33
3.PRIMARY KEY Constraints..................................................................................................................33
4.UNIQUE Constraints............................................................................................................................34
FOREIGN KEY Constraints.....................................................................................................................34
Cascading Referential Integrity...........................................................................................................................35
DISABLING CONSTRAINTS....................................................................................................................................35
Disabling Constraint Checking When Loading New Data......................................................................36
LABORATORY SESSION 9: JOINING MULTIPLE TABLES................................................................39

2
USING INNER JOINS ............................................................................................................................................39
EXERCISES........................................................................................................................................................40
LABORATORY SESSION 10: SUBQUEIRES............................................................................................41
How to use Subqueries.............................................................................................................................41
Using a Subquery as a Derived Table......................................................................................................41
Using a Subquery as an Expression.........................................................................................................41
Using a subquery to correlated Data.......................................................................................................42
Subqueries in the SELECT Clause...........................................................................................................43
The IN, ALL, and ANY operators in subquery.........................................................................................43
Using the Exists and NOT EXISTS Clauses.............................................................................................44
Exercises...................................................................................................................................................45
LABORATORY SESSION 11: MODIFYING DATA.................................................................................46
Using Transactions..................................................................................................................................46
Inserting Data..........................................................................................................................................47
Inserting a Row of Data by Values.....................................................................................................................47
Using the INSERT…SELECT Statement...........................................................................................................47
Creating a Table Using the SELECT INTO Statement.......................................................................................48
Inserting Partial Data..........................................................................................................................................48
Inserting Data by Using Column Defaults..........................................................................................................49
Deleting Data...........................................................................................................................................49
Using the Delete Statement.................................................................................................................................49
Using the Truncate Table Statement ..................................................................................................................49
Deleting Rows Based on Other Tables................................................................................................................50
Specifying Conditions in the WHERE Clause....................................................................................................50
Updating Data..........................................................................................................................................50
Updating Rows Based on Data in the Table........................................................................................................51
Updating Rows Based on Other Tables...............................................................................................................51
LABORATORY SESSION 12: VIRTUAL TABLE (VIEWS)....................................................................53
Creating Views.........................................................................................................................................53
Restrictions on View Definitions:.......................................................................................................................53
Example: View of Joined Tables...................................................................................................................54
Altering and Dropping Views...................................................................................................................54
Altering View....................................................................................................................................................54
Syntax: CREATE VIEW owner view_name [column]...............................................................................55
Dropping View...................................................................................................................................................55
Locating View Definition Information................................................................................................................55
LABORATORY SESSION 13: USER DEFINED FUNCTION..................................................................57
WHAT IS A USER DEFINED FUNCTION?.................................................................................................................57
SETTING PERMISSIONS FOR USER-DEFINED FUNCTIONS............................................................................................58
ALTERING AND DROPPING USER-DEFINED FUNCTIONS.............................................................................................58
Altering Functions....................................................................................................................................58
Dropping Functions.................................................................................................................................58
USING A SCALAR USER-DEFINED FUNCTION...........................................................................................................59
USING A MULTI-STATEMENT TABLE-VALUED FUNCTION.........................................................................................59
LABORATORY SESSION 14: STORED PROCEDURES.........................................................................61
CREATING A STORED PROCEDURE.........................................................................................................................61
Viewing Information About Stored Procedures.......................................................................................62
EXECUTING STORED PROCEDURES........................................................................................................................62
Executing a Stored Procedure by Itself....................................................................................................62
ALTERING AND DROPPING STORED PROCEDURES....................................................................................................63
Altering Stored Procedures......................................................................................................................63
Dropping Stored Procedures...................................................................................................................64
USING PARAMETERS IN STORED PROCEDURES........................................................................................................64
Using Input Parameters...........................................................................................................................64
LABORATORY SESSION 15: TRIGGERS.................................................................................................66
CONSIDERATION OF USING TRIGGERS....................................................................................................................66
CREATING TRIGGERS..........................................................................................................................................66
3
Disabling and Enabling a Trigger ..........................................................................................................68
DROPPING A TRIGGER .........................................................................................................................................68
HOW AN INSERT TRIGGER WORKS...................................................................................................................69
HOW A DELETE TRIGGER WORKS........................................................................................................................69
HOW AN UPDATE TRIGGER WORKS.................................................................................................................70
HOW AN INSTEAD OF TRIGGER WORKS..........................................................................................................70
1.CREATE A TRIGGER THAT GUARANTEES THAT THE SUM OF ALL PENALTIES FOR ONE PLAYER IS NOT MORE THAN 250 BIRR
.......................................................................................................................................................................72
APPENDIX.......................................................................................................................................................73
A. FOOT BALL LEAGUE DATABASE......................................................................................................................73
B. CREDIT DATABASE........................................................................................................................................74

4
Background
The relational database management systems and services is on of the main branches of the
IT industry where technological developments are taking place at a very rapid pace. We see
hundreds of new database and related products being released every month. Major
Software vendors churning out database products with more and more features, with each
release of their database offerings. The competition in the database market segment is so
intense that survival itself is extremely difficult. Other than the database vendors there are
thousands of companies who developed applications, for example, ERP, e-commerce,
banking, etc., which are implemented in one of the relational database management
systems. Database is becoming prominent by the day. Today, almost all applications – from
spreadsheets and word processing to statistical analysis tools – have the capability to
seamlessly integrate with the databases, get the required data from the databases, and use it
for performing tasks from statistical analysis to mail-merging.

The name SQL is derived from Structured Query Language. Originally, SQL was called
SEQUEL (for Structured English Query Language) and was designed and implemented at
IBM Research as the interface for an experimental relational database system called
SYSTEM R. SQL is now the standard language for commercial relational DBMSs. A joint
effort by ANSI (the American National Standards Institute) and ISO (the International
Standards Organization) has led to a standard version of SQL (ANSI 1986) called SQL-86
or SQL1. A revised and much expanded standard called SQL2 (also referred to as SQL-92)
has subsequently been developed. Plans are already well underway for SQL3, which will
further extend SQL with object-oriented and other recent database concepts.

SQL is a comprehensive database language; it has statements for data definition, query, and
update. Hence, it is both a DDL and a DML. In addition, it has facilities for defining views
on the database, for specifying security and authorization, for defining integrity constraints,
and for specifying transaction controls. It also has rules for embedding SQL statements into
a general-purpose programming language such as C++ or Java and etc.
This manual has 15 laboratory sessions (lessons). Each laboratory session has objectives,
description of the lab lessons, and exercises. Students are expected to read the lab manual
thoroughly and do the exercises.
Laboratory Session 1: Introducing Microsoft SQL Server
2000 Environment
Objectives: At the end of this laboratory session students will be able to:
 Describe how SQL Server can be installed
 Use SQL Server database environment effectively and efficiently
 Describe the basic type of Transact-SQL.
 Use Query Analyzer and Enterprise manager easily

Installing SQL Server

To install Microsoft SQL Server 2000 Enterprise Edition, follow these steps on the
database server and the history server:

1. If Microsoft SQL Server 2000 Enterprise Edition is already installed, uninstall it,
and install it using these instructions to set the correct installation parameters for
Tivoli Business Systems Manager.
2. Insert the Microsoft SQL Server 2000 Enterprise Edition CD and click SQL Server
2000 Components.
3. Click Install Database Server.
a. The Microsoft SQL Server 2000 Enterprise Edition setup begins. Click
Next.
4. From the Welcome window, click Next.
5. From the Computer Name window, click Local Computer and Next.
6. From the Installation Selection window, click Create a new instance of SQL
Server or Install Client Tools. Click Next.
7. From the User Information window, type your name and company. Click Next.
8. From the Software License Agreement window, read the agreement, and click Yes
if you agree with the terms.
9. From the Installation Definition window, click Server and Client Tools. Click
Next.
10. From the Instance Name window, make sure the Default check box is selected and
click Next.
11. From the Setup Type window, click Custom, click both Browse buttons and use
D:\ as the destination directory for the program files and data files. This causes your
SQL Server 2000 program files and data files to be placed in the D:\MSSQL
directory.
12. Click Next.
13. From the Select Components window, accept all the default components and
subcomponents. Click Next.
14. From the Services Accounts window, keep the default value Use the same account
for each service.
a. For Service Settings, click Use a Domain User account. Type the
username, password and domain information for a user that has
administrative rights across all Tivoli Business Systems Manager servers.
b. Click Next.
15. From the Authentication Mode window, click Mixed Mode (Windows
Authentication and SQL Authentication) and type the SQL sa password.
16. From the Collation Settings window, click Collation designator and click
Latin1_General. Select Binary as the Sort Order.
17. From the Network Libraries window, accept the default values for Named Pipes and
Named Pipe name and TCP/IP Sockets. Select both Multi-Protocol and Enable
Multi-Protocol encryption. Click Next.
18. When the Start Copying Files window opens, click Next to continue with the
installation. If you want to change any parameters, click Back.
a. When you click Back, selections reset back to their default values. If you
click Back at any time during the installation, make sure you reselect the
values you wanted before clicking Next.
19. From the Choose Licensing Mode window, click Processor License for. Type the
number of processors you need for your machine. Click Continue.
20. From the Setup Complete window, click Finish.

What are Query Analyzer and Enterprise Manager?

Query Analyzer and Enterprise Manager are the two frequently used tools for most SQL
Server 2000 client users.

1. Query Analyzer:

The SQL Server Query Analyzer is your primary interface for running SQL queries or
stored procedures. You will be using this utility throughout your database courses.

2. Enterprise Manager:

SQL Server 2000 Enterprise Manager is the primary graphical administrative and
development interface for SQL Server. There is very little SQL Server Enterprise Manager
can do that you can't accomplish from a SQL command. However, using the Enterprise
Manager is sometimes more convenient (especially when you are new to SQL Server
2000). You can use Enterprise Manger to create your own database, cope / delete tables,
query / update tables without writing SQL commands.

How to use Query Analyzer:

• login Query Analyzer: click Start / Programs / Microsoft SQL Server / Query
Analyzer:

• Select your target SQL Server: click the browser button (right to SQL Server input)
and select ORADEV (Note, if you have a SQL Server database running on your
local pc, the default SQL Server is your local SQL Server database).

• Under Connect using, select SQL Server Authentication mode and type in your
user id and password ( you may obtain your userid/password from your instructor),
click OK.
• Congratulations!....you are in Query Analyzer now:
The right pane is Query Analyzer where you write your SQL command, the left pane is
Object Browser window (if you don't see this, just click Tools / Object Browser /
Show/hide to display the window).

• Please note: Northwind and pubs are the two default sample databases for learning
purposes. You can practice your SQL command by using these two sample
databases. However, it is strongly recommended that you create your own database
for all your purposes, to know how, please see the next section How to use
Enterprise Manager. Most importantly, don't try to query, update, delete or modify
master, msdb, tempdb databases, these databases are system databases and not
supposed to be used by client users.

• Write your first SQL query command: in Query Analyzer, with Northwind database
selected from dropdown list above the window, and type in: select * from
Customers, and click Query -> Execute from the toolbar:

How to use Enterprise Manager:

• Registering a Server: In order to use Enterprise Manger, you must register a server.
to do so, click Start / Programs / Microsoft SQL Server / Enterprise Manager:

• click Plus sign of Microsoft SQL Servers, select and right-click SQL Server Group
-> New SQL Server Registration, you will see Register SQL Server Wizard:

• click Next and select ORADEV and click Add:

• At next screen, select The SQL Server login information that was assigned to me by
system administrator (SQL Server Authentication).

• Next screen, select Prompt for the SQL Serve account information when
connecting:

• Next screen, select Add the SQL Server(s) to an existing SQL Server Group:

• click finish............., you are done.

• To use Enterprise Manager, under SQL Server Group click ORADEV (Windows
NT), and type in your user id/password:
• After connecting the SQL Server, you will see the following screen, and you can do
most activities graphically that you do with in Query Analyzer with SQL
Command.

• To create your own database: right click Databases, click New databases:

Just type in your new database name you choose, then you are done!

Exercise:
1. Using Enterprise manager try to create SQL Server Group called
‘SQL2001’ and try to register your database
2. Under the SQL2001 Server group, create a database called ‘MyDB’
3. Open Microsoft Access and create some tables using Design View and
populate the tables with a data using the Worksheet View
Laboratory Session 2: Creating, Modifying and Deleting
Databases
Objective: The objective of this laboratory session is to create, modify and delete a
database in SQL server 2000.

I. Creating a Database
You can create a database by using
1. Create a database by using the create database wizard in SQL Server
Enterprise Manager
 Start SQL Server Enterpriser Manager
 Click your database server
 On the Tools menu click Wizard
 In the Select Wizard dialog box, expand Database, and then double
Click Create Database Wizard
 Complete the wizard by using the information in the following table.
Use defaults provided by the wizard for any options that the table does
not specify
Database Name: Library

2. Create a database by using SQL Server Enterprise Manager

 In the SQL server Manager Console tree, right click Database and then
click New Database
 Use the information in the following table to create a new database. Use
the defaults for any options that the table does not specify.
Database Name: Library1
3. Create a database by using Transact- SQL statements in SQL Query
Analyzer

CREATE DATABASE library


ON PRIMARY
(
NAME= library_Data,
FILENAME='C:\Program Files\Microsoft SQL
Server\MSSQL\Data\library_Data.mdf',
SIZE=7MB,
FILEGROWTH=3MB)
LOG ON
(
NAME= library_Log,
FILENAME='C:\Program Files\Microsoft SQL
Server\MSSQL\Data\library_Log.ldf',
SIZE=3MB,
MAXSIZE=10MB,
FILEGROWTH=1MB
)
Specifying Options during database Creation
Primary File: The primary file consists of the initial data file in the primary file
group. A file group is a named collection of data files. The primary file group
contains all system tables. It also contains all objects and data not assigned to user-
defined filegroups. The recommended file name extension for primary data files is
.mdf
Secondary File: Database may have secondary data files. Some databases may be
large enough to need multiple secondary data files, or they use secondary files on
separate disk drives to spread the data across multiple disc. The recommended file
name extension for secondary data files is .ndf
Transaction Log: Every database must have transaction log. Unless specified
otherwise, a transaction log file is automatically created with a system generated
name. The recommended file name extension for transaction log file is .ldf
Size: you can specify sizes of each data and log file. The minimum size is 512KB
for both data and log file.
File Growth: You can specify whether a file will grow in size if necessary. This
option is referred to as autogrow.
Maximum Size: you can specify the maximum size to which a file can grow in
megabytes or as a percentage. The default growth value is 10 percent. If you do not
specify , by default the file will grow until the disk is full.
4. Create a database with the default value in SQL Query Analyzer

 Open Query Analyzer and type the following:

 Syntax: Create Database (Name of the Database)

Note: When you create a database you need to use the Master database.

II. Modifying a database


You can also manually increase the size of any data or transaction log file by using
either SQL Server Enterpriser Manager or the ALTER DATABASE statement in
Transact SQL .
ALTER DATABASE database Name //the name of the database to be modified.
MODIFY FILE
(NAME = ‘File Name’ //the name of the file to be changed.
MAXSIZE=20MB)// the size in megabites.
Go

III. Deleting a database


You can delete database by using SQL Enterprise Manager or by executing the DROP
DATABASE statement.
The following restrictions apply to deleting database. You cannot delete:
 A database that is in the process of being restored
 A database that is open for reading or writing by any user
 A database that is publishing any of its tables as part of SQL Server replication
 A system database.
To delete the database in Transact-SQL:

DROP DATABASE database name


Viewing database Information and changing database options
Viewing database using:
i. SQL Server Enterprise Manager
 In the SQL Server Enterprise Manager console tree, expand Databases, and then
click the name of the Database
 On the View menu, click Task pad
 In the details pane, review the displayed information
ii. Query Analyzer
 Switch to SQL Query Analyzer and, on the tool bar , click Clear Window.
 In the Query window type and execute the following command;
Exec sp_helpdb// this displays information about all databases
EXEC sp_helpdb library// displays information about the Library database
Use Library
EXEC sp_spaceused// displays information about the amount of space used
in the Library database
Change the database to read only mode
i. SQL Server Enterprise Manager
 Expand Database s, right click Library and then click properties
 Click Options tab, and review the available database options
 Select the Read-only check box to change the Library database to read only
mode, and then click OK
ii. SQL Query Analyzer
 In the query window, type and then execute :
EXEC sp_dboption // to view a list of settable database options
EXEC sp_dboption Library // to view a list of database options that are
enabled for the Library database
EXEC sp_dboption Library, ‘read only’, ‘true’// to change the Library
database to read only mode
Type and execute this stored procedure EXEC sp_dboption Library to
verify that the Library database is now in read-only mode

Exercises:
1. Create a database called library in options given below.
2. Modify the database file: increase the size of the data file and decrease the size of
the log file.
3. Delete the database that you have already created.
Laboratory Session 3: Creating Tables and data types
Objective: The main objectives of this laboratory session are:
 to create a table and data types in SQL Server 2000
 defining the data types for the table
 specify the type of information (characters, numbers, or dates) that a column can
hold as well as how the data is stored.
 Deleting records ,dropping, altering tables

Creating Tables
Consider the following facts when you create tables in SQL Server. You can have up to:
 Two billion tables per database
 1,024 columns per table
 8060 bytes per row(this approximate maximum length does not apply to image,
text and ntext data types).

Column Collation
SQL Server supports storing objects with different collations in the same database.
Separate SQL Server collations can be specified at the column-level, so that each column in
a table can be assigned a different collation.
Specifying NULL or NOT NULL
You can specify in the table definition whether to allow null values in each column. If you
do not specify NULL or NOT NULL, SQL Server provides the NULL.
The following example creates the table called Product, specifying the columns of the
table, a data type for each column, and whether that column allows NULL values.

Syntax: CREATE TABLE table_name


(
Column_Name data type NOT NULL,
Column2 data type ,
Column3 data type NOT NULL

)
Example: Create the following tables
CREATE TABLE Employee
(
Emp_no int not null,
Emp_Name varchar(30),
Address varchar (30)
)
Create table Product
(
Product id int not null ,
Product_name varchar (20),
Quantity int ,
Manu_date datetime,
Price money
)
Deleting a Table
Deleting a table removes that table definition and all data, as well as the permission
specification for that table.
Before you delete a table, you should remove any dependencies between the table and other
objects.

Syntax: DROP TABLE table_name

DROP TABLE Product;

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

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

Syntax: ALTER TABLE table_name ADD column_name data type

This example add a new column manufacturing_date in the PRODUCT table .

ALTER TABLE PRODUCT ADD manufacturing_date datetime

In addition to this, if we need to modify (change ) the data type of the already created
column we can use the following syntax.

ALTER TABLE table_name ALTER COLUMN column_name data type // new data type
For example if we want to change the manufacturing_date from a date data type in to
charcter data type we use the following SQL statements

ALTER TABLE product ALTER COLUMN manufacturing_date varchar(20)

Deleting a Column
Deleting columns are unrecoverable. Therefore, be certain that you want to remove a
column before doing so.
Syntax: ALTER TABLE table_name DROP COLUMN column_name
This example deletes a column from a table
ALTER TABLE product DROP COLUMN manufacturing_date

Generating Column Values


i. Identity Property
You can use the Identity property to create columns (referred to as identity
columns)that contains system generated sequential values identifying each row
inserted into a table.
Syntax: CREATE TABLE table
(
Column_name data type IDENTTY (seed, increment) NOT NULL
)
The following example will make the student_id an auto increment column in the
student table.
Create table student
(
Student_id int identity (1,1) NOT NULL,
Student_name char (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 types. The numeric and decimal data types must be specified with a scale of 0.
 It can not be updated
 It does not allow null values
ii. Using the NEWID function and the uniqueidentifier Data Type

Exercise
1. Create table whose name is employee with attributes like name, Id, sex, salary,
Nationality and age.(Using different methods that we have seen).
2. Modify the employee table by adding a column named Qualification.
3. Modify the employee table by modifying a column named age.
4. Delete the table Employee.
Laboratory Session 4: Retrieving Data
Objectives: The main objectives of this laboratory session are:
 Retrieving all the information of the table.
 Specifying the row by using the where clause.
 Specifying the column by selecting individual columns.
 Being familiar with different data filtering mechanisms.

Retrieving Data by Using the SELECT Statement and Filtering


Data
Before you can work with data, you must select the data that you want to retrieve
from your tables. You can use the SELECT statement to specify the columns and
rows of data that you want to retrieve from tables.

Using the SELECT Statement


Use the select statement to retrieve data.
Syntax: SELECT [ALL|DISTINCT]<select_list>
FROM {<table_source >}
WHERE <search_condition>
Use the SELECT statement to specify the columns and rows that you want to be
returned from a table.
 The SELECT statement lists the items –column names, computed
values, the aggregate functions, etc to be retrieved.
 The FROM clause specifies the table or tables from which columns
and rows are returned.
 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.

Specifying columns
You can retrieve particular columns form a table by listing them in the select list.
The select list contains the columns, expressions, or keywords to select or the local
variable to assign. The options that can be used in the select list include:

SELECT |ALL|DISTINCT FROM <table name>


WHERE <condition>
When you specify columns to retrieve, consider the following facts and guidelines:
 The select list retrieves and displays the columns in the specified order
 Separate the column names with commas, except for the last column name
 Avoid or minimize the use of an asterisk(*) in the select list. An asterisk is used to
retrieve all columns from a table.
Example: This example retrieves the ProductID, ProductName and quantity columns of
all products from the product table.
Selecting ALL Columns (SELECT *)
Asterisk * is used to get all the columns of a particular table. For example the SQL select *
from Employee will retrieve the entire copy of the employee table.
SELECT *
FROM Employee

Eliminating Duplicates using DISTINCT


When you give a select statement th DBMS does not eliminate the duplicates from the
result.
For example the following SQL SELECT statement does not eliminate the duplicates

SELECT Publisher
FROM BOOk

To eliminate the duplicates from the result ser we use the key word DISTINCT.

SELECT DISTINCT
Publisher

Using the WHERE Clause to Specify Rows

Using the WHERE clause, you can retrieve specific rows based on given
search conditions. The search conditions in the WHERE clause can obtain an
unlimited list of predicates.
Syntax
<search_condition> uses expression {=|<>|>|>=|<|<=}expression
String expressions [NOT]LIKE string_expression
Expressions [NOT |BETWEEN]expression AND expression
When you specify rows with the WHERE clause, consider the following facts
and guidelines:
 Place single quotation marks around all char, nchar,varchar,
nvarchar, text, datetime, and smalldatetime data
 Use a WHERE clause to limit the number of rows that are returned
when you use the SELECT statement.
This example retrieves the productID and ProductName from the product
table in which its price is more than 1000 birr
SELECT ProductID, ProductName
FROM Product
WHERE price >1000.00—search conditions
Laboratory Session 5: Filtering Data
Objective: The main objectives of this laboratory session are:
 Being familiar with different types of filtering
 Using comparison operators
 Using Logical Operators
You sometimes want to limit the results that a query returns. You can limit the results
by specifying search conditions in a WHERE clause to filter data. There is no limit to
the number of search conditions that you can include in a SELECT statement. The
following table describes the type of filter and the corresponding search condition that
you can use to filter data.
Type of filter Search Condition
Comparison Operators =, <, >, >=, <=, and <>
String comparisons LIKE and NOT LIKE
Logical Operators: combination of conditions AND, OR
Logical Operators: negations NOT
Range of values BETWEEN and NOT BETWEEN
List of values IN and NOT IN
Unknown values IS NULL and IS NOT NULL

Using comparison operators


Use comparison operators to compare the values in a table to a specified value or
expression. You can use comparison operators to check for a condition. Comparison
operators compare columns or variables of compatible data type.

Note: Avoid the use of NOT in search conditions. They may slow data retrieval
because all rows in a table are evaluated.

Using String Comparison


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

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

Example
Expression Returns
LIKE ‘BR%’ Every name beginning with the letters BR
LIKE ‘Br%’ Every name beginning with the letter Br
LIKE ‘%een’ Every name ending with the letter een
LIKE ‘%en%’ 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 in the letters ing and
beginning with single letter from S to V
LIKE ‘M[^c]%’ Every name beginning with the letter M that does not have
letter c as the second letter
Using Logical Operators
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 2000 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

Retrieving Range of Values


Use the BETWEEN search condition in the WHERE clause to retrieve rows that
are within a specified range of values. When you use BETWEEN consider the
following:
 SQL server includes the end values in the result set
 Use BETWEEN …… AND rather than >= X and <=Y. If you want to
exclude the end values in the range use (> x and <y).
 Use NOT BETWEEN search condition to retrieve rows outside of the
specified range
Logical and Grouping Operators (Parentheses)

EXAMPLE 1

SELECT au_lname, au_fname, city, state FROM authors


WHERE
city <> 'OAKLAND' AND state <> 'CA'
OR
city <> 'Salt Lake City' AND state <> 'UT'

EXAMPLE 2

SELECT au_lname, au_fname, city, state FROM authors


WHERE
(city <> 'OAKLAND' AND state <> 'CA')
OR
(city <> 'Salt Lake City' AND state <> 'UT')

EXAMPLE 3

SELECT au_lname, au_fname, city, state FROM authors


WHERE
(city <> 'OAKLAND' AND state <> 'CA')
AND
(city <> 'Salt Lake City' AND state <> 'UT')

EXAMPLE 4

SELECT au_lname, au_fname, city, state FROM authors


WHERE
NOT
(
(city='OAKLAND' AND state='CA')
OR
(city='Salt Lake City' AND state='UT')
)
Using List of Values as Search Criteria
Use the IN search condition in the where clause to retrieve rows that match a specified list
of values. When you use the IN search condition, consider the following:
 Use either the IN search condition or a series of comparison expressions that are
connected with an OR operator.
 Use the NOT IN to retrieve rows that are not in your specified list of values. Be
aware that using NOT conditions may slow data retrievals.
Example:
List the name of companies located in Japan or Italy
USE Northwind
SELECT companyname, country
FROM Suppliers
WHERE country IN (‘Japan’, ‘Italy’)
Retrieving Unknown Values
A column has a null value if no value is entered during data entry and no default values are
defined for that column. A null value is not the same as entries with a zero (a numerical
value) or a blank (a character value)
Use the IS NULL search condition to retrieve rows in which information is missing from a
specified column.
Use the IS NOT NULL search condition to retrieve rows that have known values in the
specified columns.
Example; List the name of companies that does not have fax

USE Northwind
SELECT companyname, fax
FROM Suppliers
WHERE fax IS NULL
Laboratory Session 6: Formatting Result Sets
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
Use the ORDER BY clause to sort rows in the result set in ascending (ASC) or descending
(DESC) order. When you use the ORDER BY clause, consider the following facts and
guidelines:
 Execute the sp_helpsort system stored procedure to determine the sort
order that was defined for the database during installation
 Sort is in ascending order by default
 You can sort by column names, computed values, or expressions
 Columns that are included in the ORDER BY clause do not have to appear
in the select list.
 You can not use text, ntext, or image columns in the ORDER BY clause
 If the ORDER BY clause is used with a UNION statement, then the
columns on which you sort must be the column names or aliases specified
in the first SELECT statement.

Example: Create t1 (col1 int, col2 int);

Create t2 (col3 int, col4 int);

SELECT * from t1 UNION SELECT * from t2 ORDER BYcol1;

This statement succeeds because col1 belongs to the first table (t1)

SELECT * from t1 UNION SELECT * from t2 ORDER BYcol3;

This statement fails because col3 does not belong to the first table (t1)

Eliminating Duplicate Rows


If you require a list of unique values, use the DISTINCT clause to eliminate duplicate rows
in the result set.
 The combination of values in the select list determines distinctiveness
 The DISTINCT clause sorts the result set in random order unless you have included
an ORDER BY clause
 If you specify a DISTINCT clause, the ORDER BY columns must appear in the
SELECT list

Changing Columns Names (Aliases)


Create a more readable column names by using AS keyword to replace default column
names with aliases in the select list.
Syntax: SELECT column_name | expressions AS column_heading
FROM table_name
You can include up to 128 characters in a column alias.

Using Literals
Literals are letters, numbers, or symbols that are used as specific values in a result set. You
can include literals in the select list to make result sets more readable.
Syntax: SELECT column_name | ‘string literal’[, column_name|’string_literal’…] FROM
table_name
USE northwind
SELECT firstname, lastname,’Identification number:’, employeeid
FROM employees

Firstname lastname employeeid


Nancy Davolio Identification number: 1
Andrew Fuller Identification number 2
… … … …

Exercise:
Create the following tables:
Customer (customer_ID, Customer_name, Customer_address, city, state,
postal_code)
Product (product_ID, product_description, product_finsih, standardprice,
product_line_id)
Order_line (oreder_ID, product_ID, ordered_quatity)

Order (order_id, order_date, customer_ID)

Q1. Which products have a standard price of less than $275?

Q2. What is the address of the customer named Home Furnishings? Use an alias
NAME for customer name.
Q3. Which orders have been placed since 10/24/2000?
Q4. List product name, finish, and unit price for all desk and all tables that cost more than
$300 in the product
Q5. Which products have a standard price between $ 200 and $300
Q6. Retrieve the unique order numbers in the Order_line table
Q7. List all customers who live in warmer states
Q8. List all customers city whose address is Florida, California, Texas, or Hawaii. List the
customers alphabetically by state, and alphabetically by customer within each state.
Q9. List the name of customers that begins in AB
Q10. List the name of products that does not contain c as the second letter.
Laboratory Session 7: Grouping and summarizing Data
This lab session provides students with the skill to group and summarize data by using
aggregate functions.
Objectives: at the end of this lesson the students will be able to:
 Use the TOP n keyword to retrieve a list of the specified top values in a table.
 Generate a single summary value by sing aggregate functions .
 Organize summary data for a column by using aggregate functions with the
GROUP BY clauses and the ROLLUP or CUBE operator.
 Generate control break reports by using COMPUTE and COMPUTE BY clauses.

Listing the TOP n Values


Use the TOP n keyword to list only the first n rows or n percent of a result set. Although
the TOP n keyword is not ANSI_standard , it is useful, for example, to list a company’s top
selling products.
When you use the TOP n or TOP n PERCENT keyword, consider the following facts and
guidelines:
 Specify the range of values in the ORDER BY clause. If you do not use an ORDER
BY clause, MS SQL Server returns rows that satisfy the WHERE caluse in no
particular order
 Use an unassigned d integer following the TOP keyword.
 If the TOP n PERCENT keyword yields a fractional row, SQL server round to the
next integer value.
 Use the WITH TIES clause to include ties in your result set. Ties result when two or
more values are the same as the last row that is returned in the ORDER BY clause.
Your result set may therefore include any number of rows.
Note: You can use the WITH TIES clause only when an ORDER BY clause exists.
Use Noerthwind
This example uses the TOP n keyword to find the five products with the highest
quantities that are ordered in a single order.
USE Northwind
SELECT TOP 5 ordrid, productid, quantity
FROM order details
ORDER BY quantity DESC
go
This example use the TOP n keyword and WITH TIES clause to find the five products
with the highest quantities that are ordered in a single order. The result set lists a total of
10 products, because additional rows with the same values as the last row also are included.

USE Northwind
SELECT TOP 5 WITH TIES orderid, productid, quantity
FROM order_details
ORDER BY quantity DESC
Go

Using Aggregate Functions


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

ORDER BY <column name >[ASC|DESC]

This example calculates the average age of all players in the player table
USE FOOBALL_LEAGUE
Select AVG(age)
From player
GO
This example adds all rows in the won column in the Match table.
USE FOOBALL_LEAGUE
Select sum(won)
From Match
GO

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 or which contain null values, your result set returns a total of 16
rows. SQL Server ignores the tow 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 fount 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 that contains a total of 18 rows, two of which contain null
values, your result set returns a total of 18 rows.
This example lists the number of employees in the employees table
USW Northwind
Select count (*)
From employees
GO
GROUP BY Fundamentals
The GROUP BY clause groups rows on the basis of similarities between them. We could,
for example, group all the rows in the PLAYERS table on the basis of the place of
residence, the result set of which would be the creation of one group of players per town.
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 tat 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.

Using the GROUP BY Clause


Use the GROUP BY clause on columns or expression to organize rows into groups and to
summarize those groups. For example, use the GROUP BY clause to determine the town in
which the players resident.
Select town
From players
GROUP BY town
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
 The number of columns items is limited by the GROUP BY column sizes, the
aggregated columns, and the aggregate values involved in the query. This originates
form the limit of 8,060 bytes on the intermediate work table that is needed to hold
the intermediate query results.
 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 woth null
values in the aggregate columns, regardless of whether the rows satisfy the WHERE
clause.
Examples:
1. This example shows the number of players found in each town.
SELECT town, count(*)
FROM Players
Group by town
2. The example retrieves the number of penalties paid in each year.
Select Year (Payment_Date), count(*)
From penalty
Group By Year (Payment_Date)

Using the GROUP BY Clause with the HAVING Clause


Use the HAVING clause on columns or expressions to set conditions on the groups
included in a result set. The HAVING clause sets conditions on the GROUP BY clause in
much the same way that the WHERE clauses interacts with the SELECT statement.
 When you use the HAVING clause, consider the following facts and guidelines:
Use the HAVING clause only with the GROUP BY clause to restrict the grouping .
Using the HAVING clause without the GROUP BY clause is not meaningful.
 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.
This example lists the number of each player who has penalized more than one penalty.
SELECT PlayerNo
FROM Penalty
GROUP BY PlayerNo
HAVING COUNT(*) > 1
Examples:
1. For each player who has incurred more than 2000 Birr worth of penalties in total, find
the player number and the total amount of penalties.
SELECT PlayerNo, sum(amount)
FROM penalty
GROUP BY PlayerNo
HAVING sum(amount) > 2000
2. For each player who is a captain and who has incurred more than 180 Birr worth of
penalties in total, find the player number and the total amount of penalties
SELECT PlayerNo, sum(amount)
FROM penalty
WHERE PlayerNo IN (
SELECT playerNo
FROM Teams
)
GROUP BY playerNo
HAVING sum (amount) > 180
Using GROUP BY Clauses with the ROLLUP and CUBE Operator
Use the GROUP BY clause with the ROULLUP and CUBE Operators to generate
aggregate values within result sets. The ROLLUP and CUBE operators can be useful for
cross-referencing information within a table without having to write additional scripts.
Use the GROUP BY clause with the ROLLUP operator to summarize group values. The
GROUP BY clause with the ROLLUP operator provides data in a standard relational
format.
When you use the GROUP BY clause with the ROLLUP operator, consider the following
facts and guidelines:
 SQL Server processes data from right to left, along the list of columns that are
specified into the GROUP BY clause. SQL Server then applies the aggregate
functions toe each group.
 SQL Server adds a row to the result set that displays cumulative aggregates, such as
a running sum or a running average. These cumulate aggregates are indicated with a
NULL in the result set.
 You cannot use the ALL keyword with the ROLLUP operator.
This example lists all rows from the orderhist table and summary quantity values for each
products

USE Northwind
Select Productid, orderid, sum(quantity) as [total quantity]
From orderhist
Group by productid, orderid
WITH ROLLUP
ORDER BY productid, orderid
GO
When you use the GROUP BY clause with CUBE operator, consider the following
facts and guidelines:
 If you have n columns or expressions in the GROUP BY clause, SQL Server returns
2n possible combinations in the result set.
 The NULLs in the result set indicate that those particular rows are created a result
of the CUBE operator.
 You can use the ALL keyword with the CUBE operator.
Example This example returns a result that provides the quantity for each product for
each order, total quantity for all products for each order , total quantity for
each product for all orders , and a grand total quantity for all products for all
orders.
USE Northwind
Select Productid, orderid, sum(quantity) as [total quantity]
From [order details]
Where orderid< 10250
Group by productid, orderid
WITH CUBE
ORDER BY productid, orderid
GO

Using the GROUPING Function


Use the GROUPING function with either the ROLLUP or CUBE operator to distinguish
between the detail and summary values in your result set. Using the GROUPING function
helps to determine whether the NULLs that appear in your result set are actual null values
in the vase tables or whether the ROLLUP or CUBE operator generated the row.
When you use the GROUPING function, consider the following facts and guidelines:
 SQL Server produces new columns in the result set fro each column that is
specified in the GROUPING functions
 SQL Server returns a value of 1 to represent ROLLUP or CUBE summary values
in the result set.
 SQL Server returns a value of 0 to represent detail values in the result set.
 You can specify the GROUPING function only on columns that exist in the
GROUP BY clause
 Use the GROUPING function to assist in referencing your result sets
programmatically.
Example This example returns a result that provides the quantity for each product for
each order, total quantity for all products for each order , total quantity for
each product for all orders , and a grand total quantity for all products for all
orders.
The GROUPING function distinguishes the rows in the result set that the CUBE
operator generates.

USE Northwind
SELECT productid, GROUPING(productid), orderid,
GROUPING (orderid), SUM (quantity) as [total quantity]
FROM orderhist
GROUP BY productid, orderid
WITH CUBE
ORDER BY productid, orderid
GO
Exercises:
1. Show the different years in which players joined the club, use the PLAYRS table.
2. For each year, show the number of players that joined the club
3. For each player who has incurred at least one penalty, give the player number, the
average penalty amount and the number of penalties.
4. For each team that has played in the first division, give the team number, the
number of marches and the total number of sets won.
5. Fro each player who lives in Addis Ababa, list the name, initials, and the number
of penalties incurred by him or her
6. For each team, show the team number, the division and the total number of sets
won.
Laboratory Session 8: Implementing data
integrity/Specifying 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.
Constraints are an ANSI- standard method of enforcing data integrity. Each type of data
integrity – domain, Entity, and referential – is enforced with separate types of constraints.
Constraints ensure that valid data values are entered in columns and that relationship are
maintained between tables.

Creating Constraints
You create constraints by using the CREATE TABLE OR ALTER TABLE statement. You
can add constraints to a table with existing data, and you can place constraints on single or
multiple columns:
 If the constraint applies to a single column, it is called a column-level constraint
 If a constraint references multiple columns, it is called a table-level constraint, even
if it does not reference all columns in the table.
CREATE TABLE table-name
Column_definition
<table_constraint >
<column_definition>= column_name data type
Default constant_expression
< column_constraint>
CONSTRAINT constraint_name
[Primary key| Unique ]
[clustered | Nonclustered]
Foreign key References ref_table [ref_column]
ON DELETE {CASCADE| NO ACTION}
ON UPDATE {CASCADE| NO ACTION}
CHECK (logical_expression)
Example1. This example creates a constraint in student table.
Create table student
(
StudentID int IDENTITY (1,1) NOT NULL,
StudentName varchar(30) constraint DF_NAME DEFAULT ‘Unknown’
Age int constraint CK_age CHECK (age >=18)
Sex char,
DNO int ,
CONSTRAINT PK_STUDENT PRIMARY KEY(StudentID)
CONSTRAINT FK_STUDENT FOREIGN KEY (Dno) references Department
(Dnumber) ON UPDATE CASCADE ON DELETE CASCADE

)
GO
Consider the following facts when you implement or modify constraints:
 You can create, change and drop constraints without having to drop and
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.
For help with constraints, execute the :
sp_helpconstraint or sp_help system stored procedure
The following system tables store constraint definitions: syscomments,
sysreferences, andsysconstraints

Types of Constraints
1. DEFAULT Constraints
A default constraint enters a value in a column when one is not specified in an INSERT
statement. Default constraint enforce domain integrity
Syntax: CONSTRAINT [constraint name] DEFAULT [constraint expression]
This example adds a DEFAULT constraint that inserts the UNKOWN value in the student
table if a student name is not provided.

ALTER TABLE student


ADD
CONSTRAINT DF_studentname DEFAULT ‘UNKNOWN’ FOR StudentName
Consider the following facts when you apply a DEFAULT constraint:
 It verfies existing data in the table.
 It applies only to INSERT statements
 Only one DEFAULT constraint can be defined per column
 It cannot be placed on columns with the Identity property or on columns
with the rowversion data type.
2. CHECK Constraints
A check constraint restricts the data that users can enter into a particular column to specific
values. CHECK constraints are similar to WHERE clauses in that you can specify the
conditions under which data will be accepted.
Syntax: CONSTRAINT [constraint name]
CHECK (logical expression)
This example adds a CHECK constraint to ensure that the birth date conforms an
acceptable range of dates.

USE Northwind
ALTER TABLE Employees
ADD
CONSTRAINT CK_birthdate > ’01-01-1990’ and birthdate < getdate())

Consider the following facts when you apply a CHECK constraint


 It verifies data every time when you execute an INSERT or UPDATE statement
 It can reference other columns in the same table
 It cannot contain subqueries
 It cannot be place on columns with the rowversion data types.
 If any data violates the CHECK constraint, you can execute the DBCC
CHECKCONSTRAINTS statement to return the violating rows.

3. PRIMARY KEY Constraints


A PRIMARY KEY constraint defines a primary key on a table that uniquely identifies a
row. It enforces entity integrity.

Syntax: CONSTRIANT (constraint name)


PRIMARY KEY [CLUSTERED|NONCLUSTERED ]
{column..}
Example: This example adds a constraint that specifies that the primary key value of the
Student table is the student identification and indicates that a nonclustered index will be
creates to enforce the constraint.

ALTER TABLE Student


ADD
CONSTRAINT PK_Student PRIMARY KEY NONCLUSTERED (StudentID)

Consider the following facts when you apply a PRIMARY KEY constraint:
 The values entered must be unique
 Null values are not allowed
 It creates a unique index on the specified columns. You can specify a clustered or
nonclustered index. Clustered is the default.
The index created for a PRIMARY KEY constraint cannot be dropped directly. It is
dropped when you drop the constraint.
If you want to assign more than one column as a Primary key constraint , you can define
the primary keys when you create the table.
This example creates two primary keys(composite keys) for the CourseRegestraion 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 employee
number, but you want to guarantee that other identifiers, such as an employee’s driver
license number , are also unique.

Syntax: CONSTRINT [constraint name]


UNIQUE [CLUSTERED|NONCLUSTERED]
(column)
This example crates a UNIQUE constraint on the company name in the Suppliers table
Use Northwind
ALTER TABLE Suppliers
ADD
CONSTRAINT U_CompanyName
UNIQUE NONCLUSTERED (CompanyName)

FOREIGN KEY Constraints


A FOREIGN KEY constraint enforces referential integrity. The FOREGIN KEY constraint
defines a reference to a column with a PRIMARY KEY or UNIQUE constraint in th 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
CONSTRAITNT 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.
 Unlike PRIMARY KEY or UNIQUE constraints, Foreign key constraints do not
create indexes automatically. However, if you will be using many joins in your
database, you should create an index for the FOREIGN KEY to improve join
performance.
 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 when
you reference a column in the same table.
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. This action is referes to as cascading
referential integrity. The Reference clauses of the CREATE TABLE and ALTER TABLE
statements support ON DELETE and ON UPDATE clauses. These clauses allow you to
specify the CASCADE or NO ACTION option.
Syntax: CONSTRAINT constraint_name REFERENCES ref_table (ref_column)
ON DELETE CASCADE| NO ACTION
ON UPDATE CASCADE | NO ACTION
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 tow is
then changed in the referencing table..
For example if we update the Department table primary key i.e. Dnumber and if we
specifies CASCADE the modification will be propagated in the Student table for the row
Dno.

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, u 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:
 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.
Syntax: ALTER TABLE table
[WITH CHECK| WITH NOCHECK]
ADD CONSTRAINT constraint_name
[FROEIGN KEY ] (column)
REFERENCES ref_table (rer_column)
[CHECK (logical condition)]
In this example, you add a FROEIGN KEY constraint that verifies that all employees are
associated with a valid manager. The constraint is not enforced on existing data at the time
that the constraint is added.

Use Northwind
ALTER TABLE Employees
WITH NOCHEK
ADD CONSTRIANT FK_Employees
FOREIGN KEY (ReportsTo)
REFERENCES Employees(EmployeeID)
Disabling Constraint Checking When Loading New Data
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 conforms t 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
Syntax: ALTER TABLE table
[CHECK | NOCHECK] CONSTRIANT
ALL| constraint
This example disables the FK_Employees constraint. It can be reenabled by executing
another ALTER TABLE statement with the CHECK clause.

USE Northwind
ALTER TABLE Employees
NOCHECK
CONSTRAINT FK_Employees

To determine whether a constraint is enabled or disabled on a table, execute the sp_help


system stored procedure, or use the CnstDisabled property in the OBJECTPROPERTY
function.
Consider the following tables and do the exercises below.
Course

Grade
Department
Student

Exercises

1. Create the tables shown below(course, grade, department, Student )


2. Create all the possible constraints
3. Make sure that if the student grade is not given make the value no grade ‘NG’
4. List the name of students whose gpa is greater than 3.
5. List the title of the course taken by the student whose name is Elias.
6. Which student has stood first in the first semester?
7. Which student has stood first in the second semester?
8. Which student is best at the moment depending on gpa?
9. List the title of the courses that are taken by Ahmed in the second semester.
10. Display a grade report for student whose name is Sophia in first semester.
11. If a student is going to leave a campus he needs to have a student copy how do
prepare what the student need?
12. List the name of the department in which coms1 is given.
13. 10. Calculate GPA for Ahmed includes his name and id in the displayed result.
Laboratory Session 9: JOINING Multiple Tables
Objective: The main objectives of this laboratory session are:
 Joining tables to produce a single result set.
 You will be familiar with different kinds of joining.
 Using Inner Joins to join records from different tables.
 Using Outer Join to join records from different tables.
 Using CROSS Join to join records from different tables.

You join tables to produce a single result set that incorporates rows and columns from two
or more tables.
Syntax: Select columnName
From table name INER, LEFT, RIGHT, FULL, OUTER, CROSS JOIN
On table name
A join allows you to select columns from multiple tables by expanding FROM clause of the
SELECT statement. Two additional keywords are included in the FROM clause: - JOIN
and ON
 The JOIN keyword specifies which tables are to be joined and how to join them
 The ON keyword specifies which columns the tables have in common
Queries Two or More Tables to Produce a Result Set

A join allows you to query two or more tables to produce a single result set. 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 columns common to the specified tables to join the tables. These columns should
have the same or compatible data types
 Try to limit the number of tables in a join, since SQL takes to much time to process
the query
 You can join one or more tables in a single SELECT statement

Using Inner Joins


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 Join 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.

Example : Retrieve the employees name, salary and the employees department
Select, eName, salary, dName
From EMPLOYEE INNER JOIN DEPARTMENT ON
EMPLOYEE.Dnum =Department.DNO
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 the do not match the join condition deplays 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.
Retrieve the name of project and its location and the name of the controlling department
Select ProiectName, location, DName
FROM Department LEFT OUTER JOIN Project
ON Department.Dno S

Using CROSS Join


Cross joins display every combination of all rows in the joined table. A common column is
not required to use cross joins.
Cross join are rarely used on a normalized database, you can use them for checklists of
business templates.

List all possible combinations of the values in the employee name and the department name

Select EName, DName


From Employee cross join Department
Joining More Than Two Tables
It is possible to join any number of tables. Any table that is referenced in a join operation
can be joined to another table by a common column.
Use multiple joins to obtain related information from multiple tables. When you join more
than two tables, consider the following facts and guidelines:
 You should have one or more tables with foreign key relationships to each of the
tables that you want to join
 The ON clause should reference each column that is part of a composite key
 Include WHERE clause to limit the number of rows that are returned.

Exercises
1. Retrieve the name and address of all employees who work for the
‘Research’ department.
2. For each employee, retrieve the employee’s first and last name and the first
and last name of his or her immediate supervisor
3. For every project located in ‘Stafford’ list the project number, the
controlling department number, and the department manager’s last name,
address, and birthdates.
Laboratory Session 10: Subqueires
Objectives: At the end of this lesson students will be able to:
 Describe when and how to use a subquery
 Use subqueries to break down and perform complex queries
 Discuss how correlated queries are processed.
A subquery is a SELECT statement nested inside a select , insert , update or Delete
statement or inside another subquery. Often you can rewrite subqueries as joins and use
subqueries in place of an expression.
An expression is a combination of identifiers, values, and operations that SQL server
evaluates to obtain a result.
You use subqueries to break down a complex query into a series of logical steps and, as a
result, to solve a problem with single statements. Subqueries are useful when your query
relies on the results of another query.

How to use Subqueries


When you decide to use subqueries, consider the following facts and guidelines;
 You must enclose subqueries in parentheses
 You can use a subquery in the place of an expression as long as a single value or list
of values is returned. You can use a subquery that returns a multicolumn record set
in place of a table or to perform the same function as a join
 You cannot use subqueries that retrieve columns that contain text and image data
types
 You can have subqueries within subqueries, nesting up to 32 levels. The limit varies
based on available memory and the complexity of other expressions in the query.

Using a Subquery as a Derived Table


You create a derived table by using a subquery in place of a table in FROM clause. A
derived table is a special use of a subquery in a FROM clause to which an alias or user-
specified name refers. The result set of the subquery in the FROM clause forms a table that
the outer SELECT statement uses

This example uses a subquery to create a derived table in the inner part of the query that the
outer part queries. The derived table itself is functionally equivalent to the whole query, but
it is separated for illustrative purposes

Use northwind
Select T. ordered, T. CusomerID
From (Seelct Orderid, customerid)
From Orders) as T
When used as a derived table, consider that a subquery;
 Is a record set within a query that functions as a table
 Takes the place of a table in the FROM clause
 Is Optimized with the rest of the query

Using a Subquery as an Expression

In Transact-SQL you can substitute a subquery wherever you use an expression. The
subquery mist evaluate to a scalar value, or to a single column list of values. Subqueries
that retune a list of values replace an expression in Where CLAUSE THAT CONATINS
the IN keyword.
When used as an expression, consider that a subquery:
 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
This example returns the price of a popular computer book, the average price of all books
and the difference between the price of the book and the average price of all books.

Use pubs
Select title, price
(Select avg(price) from titles) as average
Price-(select avg(price From titles as difference )
From titles
Where type= ‘popular_comp’
Go

Using a subquery to correlated Data

You can use a correlated subquery as a dynamic expression that changes for each row of an
outer query
The query processor performs the subqurey for each row in the outer query, one row at a
time, which is in turn evaluate as an expression for that row and passed to the outer query.
The correlated subquery is effectively a JOIN between the dynamically executed subquery
and the row from the outer query.
You can typically rewrite a query in a number of ways and still obtain the same results.
Correlated subqueries break down complex queries into tow or more simple, related
queries.

When you create a correlated subquery, the inner subqueries 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 subquery to the results outside the subquery
This example returns a list of customers who ordered more than 20 pieces of product
number 23.

Use Northwind
Select ordered, customerid
From orders as or1
Where 20< (select quantity
From [ofder_detaisl ] as od
Where or1.orderid = od. Ordered
AND od. Productid= 23)
Correlated subquery return a single value or a list of values for each row specified by the
FROM clause of the outer query. The following steps describe how te correlated subquery
is evaluated in the above example.
1. The outer query passes a column value to the inner query
The column value that the outer query passes to the inner query is the orderid. The
outer query passes the first orderid in the orders table to the inner query.
2. The Inner query uses the values that the outer query passes
Each ordered in the orders table sis evaluated to determine whether an identical
orderid in the order_detail table and that ordered purchased product number 23,
and then the inner query returns that orderid to the outer query.
3. The inner query returns a value back to the outer query.
The WHERE clause of the outer query further evaluates the orderid that purchased
product number 23 to determine whether the quantity ordered exceeds 20.
4. The Process is repeated for the next row of the outer query.
The outer query passes the second orderid in the orders table to the inner query,
and SQL Server repeats the evaluation process for that row.

Example 2: This example returns a list of products and the largest order ever placed
for each product in the order_details table. Notce that this correlated subquery
references the same table as the outer query; the optimizer will generally treat this
as a self- join.

USE NORTHWIND
SELECT DISINCT productid, quantity
FROM order_detail as od1
WHERE quantity = ( SELECT max(quantity)
FROM order_details as od2
WHERE od1.productid = ord2.productid)
GO

Look at the appendices and do the following questions


Give the player number and name of each player who has incurred at least one penality

SELECT PlayerNo, Name


FROM PLAYER
WHERE EXISTS
SELECT *
FROM PENALITY
WHERE Player.PlayerNo= Penality.PlayerNo

Subqueries in the SELECT Clause


Subqueries can also be used in the SELECT clause;

The IN, ALL, and ANY operators in subquery


A row from a table satisfies a condition with the IN operator if the value of a particular
column occurs in a set of expressions. The expressions in such a set entered one by one by
a user. The IN operator can also take another form in which it is unnecessary to list the set
of expressions. The set is determined by SQL at the point when the statement is processed.
The general form of this operator is
Row constructor
Comparison operator ALL | SOME | ANY
Table expression
Where 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).
In general , 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.
Consider the following query: Get the names of all the books whose price is greater than
the maximum of the category averages. For the above query, first you will have to find the
average price of the book in each of the categories, then the maximum fo those category
averages and then find the titles whose price is greater than the maximum category. Here is
how it is implemented.

Select title
From catalog
Where price > ALL (Select avg (price)
From catalog
Group by Category)
The format of ALL and ANY are, as we have seen , ‘ x comparison operator ALL.(table-
expression)’ and ‘ X comparison operator ANY(table expression)’

Using the Exists and NOT EXISTS Clauses


You can use the EXISTS and NON EXISTS operators to determine whether data exists in a
list of values.
Use the EXISTS and NOT EXISTS operators with correlated subqueries to restrict the
result ser of an outer query to rows that satisfy the subquery. The EXISTS and NOT
EXISTS operators return TRUE or FALSE, based on whether rows are returned for
subqueries

When a subquery is introduced with the EXISTS operator, SQL Server tests whether data
that matches the subquery exists. No rows are actually retrieved.
When SQL Server processes subqueries that use the EXISTS OR NOT EXISTS operator:
 The outer query tests for the existence of rows that the subquery returns.
 The subquery returns either a TRUE or FALSE VALUE based on the given
condition in the query.
 The subquery does not produce any data.

Example 1: This example depicts that the player number 10 played team number and the
division the team is located.

SELECT TEAMNO, DIVISION


FROM TEAMS
WHERE EXISTS
(SELECT *
FROM MATCHES
WHERE PLAYERNO =10
AND TEAMNO= TEAMS.TEAMNO

Example 2: Find each player for whom no team exists in which the player concerned has
never played.

SELECT PLAYERNO
FROM PLAYER AS P
WHERE NOT EXISTS
(SELECT *
FROM TEAMS AS T
WHERE NOT EXISTS
(SELECT *
FROM MATCHES AS M
WHERE T.TEAMNO=M.TEANO
AND P.PLAYERNO=M.PLAYRno
)

Exercises
1. Give the name of each player who has played for a first division team, who has
won at least one match and who has not incurred a single penalty.
2. Give the number and name of each player who has played for both first and
second team
3. Find the team number and division of each team in which player 44 has played.
4. Retrieve the number and the name of each player who has not played matches
for team 1.
5. Give the team number of each team in which player 10 has not played.
6. Find the player number and name of each player who has won at least two
matches.
7. Give the name of each player who incurred no penalties between 1 January
2002 and 31 December 2002.
Laboratory Session 11: Modifying Data
Objectives: at the end of this lesson students will be able to:
 Describe how students can use transactions to modify data.
 Explain that rows can be inserted by using the DEFAULT values keywords to save
time during data entry
 Describe modifying data by using the INSERT…SELECT statement, as well as
deleting and updating rows that are based on other tables by using subqueries
 Discuss the use of the DELETE and TRUNCATE TABLE statement to remove
rows.
 Use INSERT, UPDATE, and DELETE statement to modify the rows of data.

Using Transactions
A transaction is a sequence of operations performed as a single logical unit of work. SQL
programmers are responsible fro starting and ending transactions at points that enforce the
logical consistency of the data.
Starting Transactions
You can start transactions in MSSQL Server in one of three modes:
 Explicit transactions start by issuing a BEGIN TRANSACTION statement
 Autocommit transactions are the default for SQL Server. Each individual Transact-
SOL statement is committed when it completes. You do not have to specify any
statements to control transactions.
 Implicit transactions mode is set by an application programming interface (API)
function or the Transact-SQL SET IMPLICIT_TRANSACTIONS ON statement.
Using this model, the next statement automatically starts a new transaction. When
that transaction completes, the next Transact_SQL statement starts a new
transaction.
Ending Transactions
You can end transactions by using a COMMIT or ROLLBACK statement.
The COMMIT statement indicates that if a transaction is successful, SQL Server
should commit it. A COMMIT statement guarantees that all of the transaction\s
modifications are permanently part of the database. A COMMIT statement also
frees resources, such as locks, that the transaction uses.

The ROLLBACK statement cancels a transaction. It backs out all modifications


made in the transaction by returning the data to the state in which it was at the start
of the transaction. A ROLLBACK statement also frees resources held by the
transaction.
BEGIN TRANSACTION

UPDATE Penalty
SET AMOUNT = AMOUNT *2
WHERE PlayerNo= 4

IF @@error <> 0
BEGIN
RAISERROR (‘Error, transaction not completed!’,16, -1)
ROLLBACK TRANSACTION
END

Inserting Data
You can insert data through a transaction by specifying a set of values or inserting the
results of a SELECT statement. You can create a table and insert a data simultaneously.
You do not have to insert values into all data fields within a row.

Inserting a Row of Data by Values


The INSERT statement adds rows to a table.

INSERT INTO (table-name/view_name) VALUES (DEFAULT/NULL/ expression)/


DEFAULT VALUES

Use the INSERT statement with the VALUES clause to add rows to a table. When you
insert rows, consider the following facts and guidelines:
 Must adhere to destination constraints or the INSERT transaction fails
 Use the column_list to specify columns that will store each incoming value. You
must enclose the column_list in parentheses and delimit it by commas. If you are
supplying values for all columns, using the column_list is optional.
 Specify the data that you want to insert by using the VALUES clause. The
VALUES clause is required for each column in the table or column_list.
The column order and data type of new data must correspond to the table column order
and data type. Many data types have an associated entry format. For example,
character data and dates must be enclosed in single quotation marks.

The following example adds DreamTeam as a new Team

Insert into Team (TeamNo, PlayerNo, Division) Values (2, 9, ‘DreamTeam’)

Using the INSERT…SELECT Statement


The INSERT…SELECT statement adds rows to a table by inserting the result ser of a
select statement
Use the INSERT…SELECT statement to add rows to an existing table from other sources.
Using the INSERT…SELECT statement is more efficient than writing multiple , single
row INSERT statements. When you use the INSERT…SELECT statement, consider the
following facts and guidelines:
 All rows that satisfy the SELECT statement are inserted into the outermost table of
the query
 You must verify that the table that receives the new rows exists in the database
 You must ensure that the columns of the table that receives the new values have
data types compatible with the columns of the table source
 You must determine whether a default value exists or whether a null clause is
allowed for any columns that are omitted . If null values are not allowed, you must
provide values for these columns.

Syntax INSERT table_name


SELECT column_list
FROM table_list
WHERE search_conditions
This example adds new player to the player table.
Insert players
Select

Creating a Table Using the SELECT INTO Statement


You can place the result ser of any query into a new table by using the SELECT INTO
statement
Use the SELECT INTO statement to populate new tables in a database with imported data.
You also can use the SELECT INTO statement to break down complex problems that
require a data ser fro various sources.
When you use the SELECT INTO statement, consider the following facts and guidelines:
 You can use the SELECT INTO statement to create a table and to insert rows into
the table in a single operation
Ensure that the table name that is specified in the SELECT INTO statement is
unique. If a table exists with the same name, the SELECT INTO statement fails.
 You can create a local or global temporary table.
Create a local temporary table by preceding the table name with a number sign (#),
r create a global temporary table by preceding the table name with a double number
sign(##).
A local temporary table is visible in the current session only. A global temporary
table is visible to all sessions:
• Space for a local temporary table is reclaimed when the user ends the
session
• Space for a global temporary table is reclaimed when the session that
created the table ends, and the last Transact-SQL statement that referenced
the table at that time completes.
 You must create column aliases or specify the column names of the new table in
the select list.
Syntax: SELECT <select_list>
INTO new table
FROM <table_sources>
WHERE <search_condition>
This example creates a local temporary table based on the query made on the Player
table. You can use string and mathematical functions to manipulate the result set.

Select name, birth_date, town, house_no


Into playerInfo
From player

Inserting Partial Data


When you insert partial data, consider the following fats and guidelines:
 List only the column names for the data that you are supplying in the INSERT
statement
 Do not specify columns in the column_list that have an IDENTITY property or that
allow default or null values.
 Enter a null value explicitly by typing null without single quotation marks.

Syntax: INSERT INTO table_name (column_list) VALUES (values)


Inserting Data by Using Column Defaults
When a table has default value constraints, or when a column has a default value, use the
DEFAULT keyword in the INSERT statement to have SQL Server supply the default value
for you.
If you use the DEFAULT keyword, and the columns do not have default values or allow
null values, the INSERT statement fails.

Example: This example inserts a default value in the Division column


Insert into Team (TeamNo ,PlayerNo ) values (3, 5)

Deleting Data
The Delete statement removes one or more rows from a table or view by using a
transaction. You can specify which rows SQL Server deletes by filtering on the targeted
table, or by using a JOIN clause or a subquery. The TRUNCATE TABLE statement is used
to remove all rows from a table.

Using the Delete Statement


The delete statement removes rows form tables. Use the DELETE statement to remove one
or more rows from a table.
Syntax:
Delete FROM table_name/view_name
WHERE search_conditions
Example: This example removes tuples that are equal to the penalty date before the New
Year.

Delete From Penalty


Where Penalty_Date < ‘1/01/2009’
When using the DELETE statement, consider the following facts:
 The DELETE statement removes one or more rows in a table, according to the
WHERE clause condition, if specified otherwise, DELETE removes all rows.
 Each Deleted row is logged in the transaction log.

Using the Truncate Table Statement


The Truncate table removes all data from a table. Use the TRUNCATE TABLE statement
to perform a nonaligned deletion of all rows.
Syntax: TRUNCATE TABLE table_name
This example removes all data from the Player table
USE FOOTBALL_LEAGUE
TRUNCATE TABLE Player
GO
This example is an illustration and will produce an error, due to the existence of a foreign
key constraint between PLAYER and TEAM.
When you use the TRUNCATE TABLE statement, consider the following facts:
 SQL Server deletes all rows but retains the table structure and its associated objects
 The TRUNCATE TABLE statement executes more quickly than the DELETE
statement because SQL Server logs only the deal location of data pages
 If a table has an IDENTITY column, the TRUNCATE TABLE statement resets the
seed value.
Deleting Rows Based on Other Tables
Use the DELETE statement with joins or subqueries to remove rows from a table based on
data stored in other tables. This is more efficient than writing multiple, single-row
DELETE statement.

Using an additional FROM Clause


In a DELETE statement, the WHERE clause references values in the table itself and
is used to decide which rows to delete. If you use an additional FROM clause, you
can reference other tables to make this decision. When you use the DELETE
statement with an additional FROM clause, consider the following facts:
 The first FROM clause indicates the table from which rows are deleted.
 The second FROM clause may introduce a join an acts as the restricting
criteria for the DELETE statement.
Syntax:
DELETE FROM <table_name/ view_name>
FROM <table_ source>
WHERE <search_condition>

This example uses a join operation with the DELETE statement to remove rows
from the Penalty table for the players’ birth date on 4/14/1984.

USE FOOTBALL_LEAGUE
GO
DELETE FROM PENALTY
FROM player as PL
Inner join penalty as P
ON PL. PlayerNo = P.PlayerNo
WHERE birth_date = ‘4/14/1998’

Specifying Conditions in the WHERE Clause


You also can use a subquery to determine which rows to delete from a table based on rows
of another table. You can specify the conditions in the WHERE clause rather than using an
additional FROM clause. Use a nested or correlated subquery in the WHERE CLAUSE to
determine which rows to delete.
This example removes the same rows in the Penalty table as the above example and shows
that you convert a join operation to a nested subquery.

USE FOOTBALL_LEAGUE
DELETE FROM [penalty]
WHERE PlayerNo IN (
SELECT PlayerNo
FROM Player
WHERE birthDate =’4/14/1984’)

Updating Data
The UPDATE statement can change data values in single rows, groups of rows , or all rows
in a table or view. You can update a table based on data in the table or on data in other
tables.
Updating Rows Based on Data in the Table
The UPDATE statement modifies existing data.

UPDATE {table_name| view_name}


SET {column_name= {expression|default | null}}|
@variable = expression
WHERE {search condition}
Use the UPDATE statement to change single rows, groups of rows, or all of the rows in a
table. 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. The changes
do not occur, and the statement is rolled back.
 You can change the data in only one table at a time
 You can set one or more columns or variables to an expression. For example, an
expression can be a calculation (the amount * 2) or the addition of two columns.
The following example adds 10 percent to the current penalty amount of the players
Use FOOTBALL_LEAGUE
GO
UPDATE PENALTY
SET Penalty_amount = (penalty_amount*1.1)
GO

Updating Rows Based on Other Tables


Use the UPDATE statement with a FROM clause to modify a table based on values from
other tables.
Using the UPDATE Statement
When you use joins and subqueries with the update statement, consider the following facts
and guidelines
 SQL Server never updates the same row twice in a single UPDATE statement. This
is a built-in restriction that minimizes the amount of logging that occurs during
updates.
 Use the SET keyword to introduce the list of columns or variable names to be
updated. Columns referenced by the SET keyword must be unambiguous. For
example, you can use a table prefix to eliminate ambiguity.

Syntax: UPDATE {table_name|view_name}


SET
{column_name={expression|DEFAULT |NULL}}
[FROM <table_source>]
[WHERE search_conditions]
Specifying Rows to Update Using Joins
When you use joins to update rows, use the FROM clause to specify joins in the UPDATE
Statement
This example use a join to update the products table by adding $2.00 to the unitprice
column for all products supplied y suppliers in the United States (USA)
UPDATE products
SET unitprice= unitpirce +2
FROM products
INNER JOIN suppliers
ON products.supplierid= suppliers.supplierid
WHERE suppliers. Country= ‘USA’
GO
Specifying rows to update using sub queries
When you use sub queries to update rows, consider the following facts and guidelines:
 If the sub query does not return a single value, you must introduce the sub query
with the IN, EXISTS, ANY, OR ALL keyword.
 Consider using aggregate functions with correlated sub queries , because SQL
Server never updates the same row twice in a single UPDATE statement
This example uses a subquery to update the products table by adding $ 2.00 to the unitprice
column for all products supplied by suppliers intheinUnited States(USA). Notice that each
product has only one supplier.
UPDATE products
SET unitprice= unitprice +2
WHERE supplierid IN (
SELECT supplierid
FROM suppliers
WHERE country= ‘USA’
)
GO

Exercises:
1. Create a table the same as TEAM table but with out the division column.
2. Populate the table that you created with the appropriate data
3. Using INSERT INTO command insert the values to the new table from the TEAM
table.
4. increase all penalties by 15%
5. Delete all penalties incurred by player 8 in 2002
6. Delete players who live in the same town as player 8, but keep the data about player 8
7. Change the value F in sex column of the players table to W (woman)
8. Increase by 20 percent all penalties higher than the average penalty
Laboratory Session 12: Virtual Table (Views)
Objectives: At the end of this lesson students will be able to:
A view provides the ability t 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, making data complexity,
simplifying permission management, and organizing data for export to other applications.

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

Syntax CREATE VIEW owner. view_name (column)


WITH ENCRYPTION
AS
Select_statement
[WITH CHECK OPTION]
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
N.B When you create views, it is important to test the SELECT statement that defines the
view to ensure that SQL Server returns the expected result set.

Restrictions on View Definitions:


When you create views, consider the following restrictions:
 The CREATE VIEW statement cannot include the COMPUTE, OR COMPUTE
BY clauses. The CREATE VIEW statement cannot include the INTO keyword.
 The CREATE VIEW statement can include the ORDER BY clause, only if the TOP
keyword is used.
 Views cannot references temporary tables
 Views cannot references more than 1024 columns.
 The CREATE VIEW statement cannot be combined with other Transact-SQL
statements in a single batch.
Example 1
This example creates a view that contains player number and player birth date.

CREATE VIEW Player_Information


AS
SELECT playerNo,
Birth_date

This statement queries the view to see the results.

SELECT * FROM Player_Information

Example: View of Joined Tables


You often create views to provide a convenient way of looking at information from two or
more joined tables in one central location.

Altering and Dropping Views


In this example, PenaltyStatusView joins the Player and Penalty tables.

Altering View

USE Football_league
GO

CREATE VIEW PenaltyStatusView


AS
SELECT P.playerNo, P. Name, Payment_date, amount
FROM player as P inner join penalty as N ON P.PlayerNo = N.PlayerNo

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. This statement is subject to the same restrictions as the CREATE
VIEW statement. If you create a view and recreate it you must reassign permissions to it.
Syntax: CREATE VIEW owner view_name [column]
WITH ENCRYPTION
AS
Select_statement
[WITH CHECK OPTION]

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 alters Player_information view to add the name column

USE FOOTBALL_LEAGUE
GO

ALTER VIEW dbo. Player_Information


AS
SELECT PlayerNo, Name, Birth_Date
FROM Player

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


This example deletes the Player_Infromation view

USE FOOTBALL_LEAGUE
GO
DROP VIEW Player_InformatGFion

Locating View Definition Information


You may want to see the definition of a view in order to alter the view definition or to
understand how its data is derived form the base tables.
You can locate view definition information with SQL Server Enterprise Manager or by
querying the following views and system tables.

Information schema view or system tables Display information on

INFORMATION_SCHEMA.TABLES or systobject view names.


INFORMATION_SCHEMA.VIEW_TABLE_USAGE or
Sysdepends base object names
INFORMATION_SCHEMA.VIEW or syscomments View definition
INFORMATION_SCHEMA.VIEW_COLUMN
_USAGE or Syscolumns Columns that are defined
in a
view
Modifying Data Trough Views
Views do not maintain a separate copy of data. Instead, they show the resutlset of a query
on one or more base tables. Therefore, whenever you modify data in a view, you are
actually modifying the base table.
With some restrictions you can insert, update or delete table data freely through a view. In
general, the view must be defined on a single table and must not include aggregate
functions or GROUP BY clauses in the SELECT statement.
Specifically, modifications that are made by using views:
 Cannot affect more than one underlying table
 The select clause may not contain set functions
 The select clause may not contain DISTINCT .
 The FROM clause may not contain more than one table
 The WHERE clause may not contain a correlated subquery
 The SELECT statement may not contain a GROUP BY clause( and therefore also
no HAVING clause).
 The SELECT statement may not contain on ORDER BY clause.
 The SELECT statement may not contain set operations.
 A virtual column may not be updated.

The BEGIN_AGE column in the following view may not be updated (though the PlayerNo
column maybe updated):

CREATE VIEW AGE (PLAYERNO, BEGIN_AGE) AS


SELECT PLAYERNO, JOINED - YEAR (BIRTH_DATE)
FROM PLAYERS

Exercises:
1 Create a view called NUMBERPLS that contains all the team numbers and the
total number of players who have played for that team.
2 Create a view called WINNER tht contains the number and name of each
player who, for at least one team, has won one match.
3 Create a view called TOTALS that records the total amount of penalties for
each player who has incurred at least one penalty.
4 Remove the view called TOWN that you have created last time.
5 Does the following update operations (update, insert, and delete operations)
peroformed for the PenaltyStatusView?
Laboratory session 13: User Defined Function
Objectives: At the end of this lesson (lab session), students will be able to:
 Create and alter used defined functions
 Describe different types of functions
 Use the functions in their daily life

What is a User Defined Function?


In SQL Server, you can design your own functions to supplement and extend the system
supplied (built-in) functions.
A user-defined function takes zero, or more, input parameters and returns either a scalar
value or a table. Input parameters can be ay data type except timestamp,cursor, or table.
User defined functions do not support output parameters.
Creating User Defined Functions
You create a user defined function in nearly the same way that you create a view or stored
procedure.

Creating a Function
You create user-defined functions by using the CREATE FUNCTION statement. Each
fully qualified user defined function name (database_name.owner_name. function_name)
must be unique. The statement specifies the input parameters with their data types, the
processing instructions, and the value returned with each data type.
CREATE FUNCTION function_name
@parameter_name scalar_parametr_ data_type
RETURNS scalar_return_data_type
WITH <function_option>
AS
BEGIN
Function Body
RETURN sacalar_expression
END

This example creates a user defined function to replace a null value with the words Not
Applicable
USE Northwind
GO
CREATE FUNCTION fn_NewRegion
(@myinput varchar (30))
RETURNS varchar(30)
BEGIN
If @myinput is null
SET @myinput =’Not Applicable’
RETURN @myinput
END
When referencing a scalar user defined function, specify the function owner and the
function name in two-part syntax
SELECT LastName, City, dbo.fn_NewRegion(Region) AS Region, Country
FROM Employees
Restrictions of Functions
Nondeterministic functions are functions, such as GETDATE(), that could return different
results values each time that they are called with the same set of input values. Built-in
nondeterministic functions are not allowed in the body of user-defined functions. The
following built-in functions are nondeterministic.
@@ERROR FORMATMESSAGE USER_NAME
@@IDENTITY GETANSINULL NEWID
@@ROWCOUNT GETDATE PERMISSIONS
@@TRANCOUNT etc

Setting Permissions for User-defined Functions


The permission requirements for user-defined functions are similar to that of other database
objects:
 You must have CREATE FUNCTION permission to create, alter, and drop user-
defined functions
 Users other than the owner must be granted EXECUTE permission on a function
before they can use it in a Transact-SQL statement
 If the function is being schema-bound, you must have REERENCE permission on
tables, views, and functions referenced by the function. REFERENCE permissions
can be granted through the GRANT statement to views and user defined functions
as well as tables
 If a CREATE TABLE or ALTER TABLE S statement references a user-defined
function in a CHECK constraint, DEFAULT clause, or computed column, the table
owner must also own the function.

Altering and Dropping User-defined Functions


You can alter and drop user-defined functions by using the ALTER FUNCTION statement.
The benefit of altering a function instead of dropping and recreating it is the same as it is
for views and procedures. The permissions on the function remain and immediately apply
to the revised function.

Altering Functions
You modify a user-defined function by using the ALTER FUNCTION statement
Syntax : ALTER FUNCTION function_name
<New Function Content>

This example shows how to alter a function.


ALTER FUNCTION dbo. fn_NewRegion
<New Function Content>

Dropping Functions
You can drop a user-defined function by using DROP FUNCTION statement.

Syntax: DROP FUNCTION function_name

This example shows how to drop a function


DROP FUNCTION dbo.fn_NewRegion
Using a Scalar User-defined Function
A scalar function returns a single data value of the type defined in a RETURNS clause. The
body of the function, defined in a BEGIN…END block, contains the series of Transact-
SQL statements that return the value. The return type can be any data type except text,
ntext, image, cursor, or timestamp.
A scalar user-defined function is similar to a built-in function. After you create it, you can
reuse it.
This example creates a user defined function that receives date and column separators as
variables and reformats the date as a character string.
USE Northwind
GO
CREATE FUNCTION fn_DateFormat
(@indate datetime, @separator char (1))
RETURNS varchar (20)
AS
BEGIN
RETURN
CONVERT (varchar (20), datepart(mm, @indate))
+ @separator
+ CONVERT (varchar(20), datepart(dd, @indate))
+@separatro
+CONVERT (varcahr(20),datepart(yy, @indate))

END
You can call a scalar user-defined function in the same way that you do a built-in function.

SELECT dbo. fn_DateFormat (GETDATE(), ‘:’)

Using a Multi-Statement Table-valued Function


A multi-statement table-valued function is a combination of a view and a stored procedure.
You can use user-defined functions that return a table to replace stored procedures or views
A table-valued function (like a stored procedure) can use complex logic and multiple
Transact-SQL statements to build a table. In the same way that you use a view, you can use
a table-valued function in the FROM clause of a Transact-SQL statement.
When using a multi-statement table-valued function, consider the following facts:
The BEGIN and END delimit the body of the function
The RETURNS clause specifies table as the data type returned.
The RETUENS clause defines a name for the table and defines the format of the table. The
scope of the return variable name is local to the function.

You can create function by using many statements that perform complex operations.
This example creates a multi-statement table-valued function that returns thee last name or
both the first and last names of employees, depending on the parameter provided.

USE Northwind
GO
CREATE FUNCTION fn_Employees
(@length varchar(9))
RETURNS @fn_Employee TABLE
(EmployeeID int Primary Key Not Null,
[Employee Name] varchar (16) Not Null)
AS
BEGIN
IF @length =’ShortName’
INSERT @fn_Employees SELECT EmployeeID, LastName
FROM Employees
ELSE IF @length =’LongName’
INSERT @ fn_Employees SELECT EmployeeID,
(FirstName + ‘ ‘ + LastName) FROM Employees
RETURN
END
You can call the function instead of a table or view.

SELECT * FROM dbo.fn_Employees (LongName)


or

SELECT * FROM dbo.fn_Employees (ShortName)

Exercises
11Create a function which gives GPA of a student when you give his/her Id no.
11Create a function that gives its factorial when you give the number..
11Create a function which gives you the maximum of the sequence of numbers.
11Create a function which displays the information of a student
Laboratory session 14: Stored Procedures
Objective: At the end of this lesson (lab session) students will be able to:
 Describe how a stored procedure is processed
 Create, execute, modify, and drop a stored procedure
 Create stored procedures that accept parameters
 Execute extended stored procedures
 Create custom error messages.
 Appreciate the performance of the stored procedures
A stored procedure is a certain piece of code (the procedure), consisting of declarative and
procedural SQL statements stored in the catalog of a database that can be activated by
calling it from a program, a trigger or another stored procedure.
Each stored procedure consists of at least three parts: a list of parameters, a body and a
name.
The procedure above has only one parameter called PNO_VAR (the player number). The
word IN indicates that this parameter is an input parameter. After the execution of the
procedure the value of PNO_VAR will be unchanged.
Between the keyword BEGIN and END the so-called procedure body of the procedure is
specified.
The names of the stored procedure within the database have to be unique, just like the name
of users.
Stored procedures are a method of encapsulating repetitive tasks. Stored procedures
support user declared variables, conditional execution, and other powerful programming
features.
SQL Server supports five types of stored procedures;
 System stored procedure
 Local stored procedure
 Temporary stored procedure
 Remote stored procedure
 Extended stored procedure
Stored procedure in SQL Server is similar to procedures in other programming languages,
in that they can:
 Contain statements that perform operations in the database, including the ability to
call other stored procedures
 Accept input parameters
 Return a status value to a calling stored procedure or batch to indicate success or
failure ( and the reason for failure)
 Return multiple values to the calling stored procedure or batch in the form of output
parameters.

Creating a Stored Procedure


You can create a stored procedure in the current database only except for temporary stored
procedures, which are always created in the temdb database.
You can create stored procedure by using the CREATE PROCEDURE statement .
Consider the following facts and guidelines when you create a stored procedure:
 Stored procedures can reference tables, views, user defined functions , and other
stored procedures, as well as temporary tables.
 If a stored procedure creates a local temporary table, the temporary table only exists
for the purpose of the stored procedure and disappears when stored procedure
execution completes.
 A CREATE PROCEDURE statement cannot be combined with other Transact-SQL
statements in a single batch.
 Design a stored procedure to accomplish a single task.

Syntax: CREATE PROCEDURE procedure_name [number]


[parameter list]
[declaration section]
[procedure body]
<variable> IN| OUT| INOUT data_type
AS Sql_statement
Example 1. The following statements create a stored procedure that lists all overdue
orders in the Northwind database.

USE Northwind
GO
CREATE PROC OverDueOrders
AS
SELECT *
FROM orders
WHERE RequiredDate < GETDATE() AND ShippDate IS NULL

Example 2: This stored procedure removes all matches played by a specified player.
CREATE PROCEDURE DELETE_MATCHES
(PNO_VAR IN INT ) AS
BEGIN
DELETE
FROM MATFHES
WHERE PLAYERNO = PNO_VAR
END

Viewing Information About Stored Procedures


To print a list of stored procedures and owner names in the database, use the
sp_stored_procedures system stored procedure. You can also query the sysobjects,
syscomments, and sysdepends system tables to obtain information.

Executing Stored Procedures


You can execute a stored procedure by itself or as part of an INSERT statement. You must
have been granted EXECUTE permission on the stored procedure.

Executing a Stored Procedure by Itself


You can execute a stored procedure by issuing the EXECUTE statement along with the
name of the stored procedure and any parameters.
Syntax: EXECUTE
@ return_status
Procedure_name / number / @procedure_var
@parameter = {value /@variable [OUTPUT]/[DEFAULT]}

WITH RECOMPILE
The following statement execute a stored procedure that lists all overdue orders in the
Northwind database.

EXEC OverdueOrders

Executing a Stored Procedure Within an INSERT Statement


The INSERT statement can populate a local table with a result set that is returned from a
local or remote stored procedure. SQL Server loads the table with data that is retuned from
SELECT statements in the stored procedure. The table must already exist, and data types
must match.
Example: The following statement creates the EmployeeCustomer stored procedure, which
inserts employees into the Customers table of the Northwind database.

USE Northwind
GO
Create proc EmploeeCustomer
As
Select
UPPER (SUBSTRING (LastName, 1,4) + SUBSTRING (FirstName, 1,1)
‘Northwind Traders’, RTRIM (FirstName) +’ “ + LastName, ‘Employee’, address,
City, Region, PostalCode, Country, (‘(206) 555-1234’ + x ‘+ Extension), null
FROM Employees
WHERE HireDate < GETDATE()
GO
The following statement execute the EmployeeCustomer stored procedure

INSERT INTO Customers


EXEC EmployeeCustomer

Altering and Dropping Stored Procedures


Stored procedures are often modified in response to requests from users or to changes in
the underlying table definitions.

Altering Stored Procedures


To modify an existing stored procedure and retain permission assignments, use the ALTER
PROCEDURE statement. SQL Server replaces the previous definition of the stored
procedure when it is altered with ALTWER PROCEDURE.
Consider the following facts and guidelines when you use the ALTER PROCEDURE
statement:
If you want to modify a stored procedure which is created with any options, WITH
ENCRYPTION OPTION, you must include the option in ALTER PROCEDURE statement
to retain the functionality that the option provides
ALTER PROCEDURE alters only a single procedure.

Syntax: ALTER PROCEDURE procedure_name


@parameter data_ type
VARYING [=default ] [OUTPUT]
With RECOMPILE/ ENCRYPTION

AS
Sql_statement
Example: The following example modifies the OverdueOrders stored procedure to select
only specific column names rather than all columns from the Orders table, as well as to sort
the result set.

USE Northwind
GO
ALTER PROC OverdueOrders
AS
Select CONVERT (char (8), RequiredDate, 1) RequriedDate,
CONVERT (char (8), OrderDate, 1) OrderDate
OrderID, CustomeID, EmployeeID
FROM Orders
WHERE RequiredDate < GETDATE() AND ShipDate IS NULL
ORDER BY RequiredDate
GO

Dropping Stored Procedures


Use the DROP PROCEDURE statement to remove user defined stored procedures from the
current database.
Before you drop the stored procedure, execute the sp_depends stored procedure to
determine whether objects depend on the stored procedure.

Syntax: DROP PROCEDURE procedure_name


Example: This example dropt the OverdueOrders stored procedure
USE Northwind
GO
DROP PROC OverdueOrders
GO

Using Parameters in Stored Procedures


You can extend the functionality of stored procedures. You can pass information into and
out of stored procedures by using parameters. They enable you to use the same stored
procedure to search in the database many times.
SQL Server supports two parameters: input and output.

Using Input Parameters


Input parameters allow information to be passed into a stored procedure. To define a stored
procedure that accepts input parameters, you declare one or more variables as parameters in
the CREATE PROCDURE statement

@parameter data_type [=default]

Consider the following facts:


 All incoming parameter values should be checked at the beginning of a stored
procedure to trap missing and invalid values early.
 You should provide appropriate default values for a parameter
 The maximum number of local variables in a stored procedure is limited only to
available memory
 Parameters are local to a stored procedure. The same parameter names can be used
in other stored procedure.
Example: The following example crates a year to year sales stored procedure, which
returns all sales between specific dates

CREATE PROCEDURE [year to year sales]


@BeginningDate datetime, @EndingDate datetime
AS
IF @BeginningDate IS NULL or @EndingDate IS NULL
BEGIN
RAISERROR (‘Null values are not allowed’, 14,1)
RETURN
END
SELECT O.ShippedDate, O.OrderID, OS. Subtotal, DATENAME(YY, ShipDate)
AS year
FROM ORDERS AS O INNER JOIN [ORDER SUBTOTALS ] OS
ON O.OrderID = OS.OrderID
WHERE O.shippedDate BETWEEN @BeginningDate AND @EndingDate
GO

Exercises:
1. Create a stored procedure to calculate, for a player, the number of teams and the
number of actual positions on the committee. These two numbers must form the
output parameters of the stored procedure
2. Create a stored procedure that creates the TEAMS table of the user SQLDBA if
does not exist already.
3. Create a stored procedure that can show FiveMostExpensiveProducts in the
products table from the Northwind database.
4. Display the information of the FiveMsotExpensiveProducts
Laboratory session 15: Triggers
Objectives: At the end of this lesson students will be able to:
 Create, alter and delete a trigger
 Recognizes the use of a trigger in the database systems
 Describe the use of triggers
 Discuss some of the facts and guidelines that implementers must consider when
determining whether to use triggers instead of other tools.
Introduction
A Trigger is a special kind of stored procedure that executes whenever an attempt is made
to modify data in a table that the trigger protects. Triggers are defined to specific tables. It
is referred to as the trigger table.

When an attempt is made to insert, update, or delete data in a table, and a trigger for that
particular action has been defined on the table, the trigger executes automatically. It cannot
be circumvented.

Unlike standard stored procedures, triggers cannot be called directly and do not pass or
accept parameters.

Consideration of Using Triggers

 Most triggers are reactive; constraints and the INSTEAD OF trigger are proactive.
Triggers are executed after an INSERT , UPDATE , or DELETE statement is
executed on the table in which the trigger is defined. For example, an UPDATE
statement updates a row in at able, and then the trigger on that table executes
automatically. Constraints are checked before an INSERT, UPDATE, or
DELETE statement executes.
 Constraints are checked first.
If constraints exist on the trigger table, they are checked prior to the trigger
execution. If constraints are violated, the trigger does not execute.
 Tables can have multiple triggers for any action
 Triggers can handle multi-row actions.
o An INSERT , UPDATE , or DELETE action that invokes a trigger can
affect multiple rows. You can choose to :
 Process all of the rows together, in which case all affected rows must
meet the trigger criteria for any action to occur
 Allow conditional actions

Creating Triggers
Create triggers by using the CREATE TRIGGER statement. The statement specifies the
table on which a trigger is defined, the events for which the trigger executes, and the
particular instructions for the trigger.

CREATE TRIGGER trigger_name


On table_name
{FOR |AFTER| INSTEAD OF| INSERT| UPDATE| DELETE
AS
[IF(UPDATE(column_name)….]
[(AND|OR) UPDATE (column_name)…]
Sql statements}

The following example creates a trigger on the Employees table that prevents users from
deleting more than one employee at a time. The triggers fires every time a record or group
of records are deleted from the table. The triggers checks the number of records being
deleted by querying the Deleted table. If more than one record is being deleted, the trigger
returns a custom error message and rolls back the transaction.

Use Northwind
GO
Create TRIGGER Emp_Delete ON NewEmployees
FOR DELETE
AS
IF(SELECT COUNT(*) FROM Deleted) >1
Begin
RAISERROR (
‘You cannot delete more than one employee at a time.’,
16. 1)
ROLLBACK TRANSACTION
END

Altering and Dropping Triggers

Altering a Trigger
If you want to change the definition of the existing trigger, you can alter it without having
to drop it.
The altering definition replaces the definition of the existing trigger with the new
definition. Trigger action also can be altered. For example, if you create a trigger for
INSERT and then change the action to UPDATE, the altered trigger executes whenever the
table is updated.

ALTER TRIGGER trigger_name


ON table
[WITH ENCRYPTION]
{{FRO{[,] [DELETE] [,][UPDATE] [,] [INSERT]}
AS

Sql_statement […n]}
FOR [INSERT],[UPDATE]
AS
IF UPDATE(column)
[{AND|OR} UPDATE(column)[,..n]]
Sql_statement […n]}
{FOR{[,] [INSERT] [,] [UPDATE]}
[NOT FOR REPLICATION]
AS
IF UPDATE(column)
[{AND|OR} UPDATE (column) [,…n]]
Sql_statement […n]}
}
This example alters the delete trigger created in the previous example. New trigger content
is provided, which changes the delete limit from one record to six records.

Use Northwind
Go
Create trigger empl_Delete ON Employees
FOR DELETE
AS
IF (Select count (*) From Deleted) > 6
Begin
Raiserror(
‘You cannot delete more than six employees at a time.’,
16,1)
Rollback Transaction
END

Disabling and Enabling a Trigger


You can enable or disable a specific trigger, or all triggers on a table. When a trigger is
disabled, it is still defined for the table, however, when an INSERT , UPDATE, or
DELETE statements is executed against the table, the actions in the trigger are not
performed until the trigger is re-enabled.

SYNTAX: ALTER TABLE TABLE_NAME


{ENABLE|DISABLE} TRIGGER
{ALL|TRIGGER_NAME}

Dropping a Trigger
You can remove a trigger by dropping it. Triggers are dropped automatically whenever
their associated tables are dropped.

Syntax: DROP TRIGGER trigger_name

How an INSERT Trigger Works

You can define a trigger to execute whenever an INSERT statement inserts data into a
table.
When an INSERT trigger is fired, new rows are added to both the trigger table and the
inserted table. The Inserted table is a logical table that holds a copy of the rows that have
been inserted. The inserted table allows you t reference logged data from the initiating
INSERT statement. The trigger can examine the inserted table to determine whether , or
how, the trigger actions should be carried out. The rows in the inserted table are always
duplicates of one or more rows in the trigger table.

The trigger in this example was created to update a column (UnitsInStock) in the products
table whenever a product is ordered (whenever a record is inserted into the ORDER
DETAILS table). The new value is set to the previous value minus the ordered amount.

Use Northwind
Create trigger orderDet_Insert
ON [Order Detail]
FOR INSERT
AS
UPDATE P SET
unitsInstock= (P.UnitsInStock – I. Quantity)
FROM Products AS P INNER JOIN Inserted AS I
ON P.ProductID = I.ProductID

How an INSERT Trigger Works


You can define a trigger to execute whenever an INSERT statement inserts data into a
table.
When an insert trigger is fired, new rows are added to both the trigger table and the inserted
table. The inserted table is a logical table that holds a copy of the rows that have been
inserted. The inserted table contains the logged insert activity from the INSERT statement.
The inserted table allows you to reference logged data from the initiation INSERT
statement. The trigger can examine inserted table to determine whether, or how, the trigger
actions should be carried out. The rows in the inserted table are always duplicates of one or
more rows in the trigger.
All data modifications activity (INSERT, UPDATE, and DELETE statements) is logged ,
but the information in the transaction log is unreadable. However, the inserted table allows
you to reference the logged changes that the INSERT statement caused. Then you can
compare the changes to the inserted data in order to verify them or take further action.

Example: This trigger in this example was created to update a column (UnitsInStock) in
the Products table whenever a product is ordered (whenever a record is inserted into the
Order Details table). The new value is set to the previous value minus the ordered amount.

USE Northwind
CREATE TRIGGER OrdeDet_Insert
ON [Order Details ]
FOR INSERT
AS
UPDATE P SET
UnitsInStock = (P.UnitInStock – I. Quantity)
FROM Products as P INNER JOIN Inserted as I
ON P. ProductID= I.ProductID

How a Delete Trigger Works


When a DELETE trigger is fired, deleted rows form the affected table are placed in a
special deleted table. The deleted table is a logical table that holds a copy of the rows that
have been deleted. The deleted table allows you to reference logged data from the initiating
DELETE statement.

 When a row is appeared to the deleted table, it no longer exist in the database table,
therefore the deleted table and the database tables have no rows in common
 Space is allocated from memory to create the deleted table. The deleted table is
always in the cache.
 A trigger that is defined for a DELETE action does not execute for the
TRUNCATE TABLE STATEMENT because TRUNCATE TABLE is not logged.
The trigger in this example was created to update the Discontinued column in the
Products table whenever a category is deleted ( whenever a record is deleted from the
Categories table). All affected products are marked as 1, including they are discontinued.

USE Northwind
CREATE TRIGGER category_Delete
ON Categories
FOR DELETE
AS
UPDATE P SET Discontinued =1
FROM Products AS P inner join deleted as d
On p. categoriyID = d. categoryID

How an UPDATE Trigger Works


An UPDATE statement can be thought of as two steps: the DELETE step that captures the
before image of the data, and the INSERT step that captures the after image of the data.
When an UPDATE statement is executed on a table that has a trigger defined on it, the
original rows ( before image) are moved into the deleted table, and the updated rows (after
image) are inserted into the inserted table.
The trigger can examine the deleted and inserted tables, as well as the updated table, to
determine whether multiple rows have been updated and how the trigger actions should be
carried out.
You can define a trigger to monitor data updates on a specific column by using the IF
UPDATE statement.

Syntax: IF UPDATE (<column_name>)

This example prevents a user form modifying the EmployeeIds column in the Employees
table

USE Northwind
GO
CREATE TRIGGER Employee_Update
ON Employees
FOR UPDATE
AS
IF UPDATE (EmployeeID)
BEGIN TRANSACTION
RAISERROR (‘Transaction cannot be processed.\
***** Employee ID number cannot be modified.’)
ROLLBACK TRANSACTION
END

How an INSTEAD OF Trigger Works


You can specify an INSTEAD OF trigger on both tables and views. This trigger executes
instead of the original triggering action. INSTEAD OF triggers increase the variety of
tuples of updates that you can perform against a view. Each table or view is limited to one
INSTEAD OF trigger for each triggering action (INSERT, UPDATE, or DELETE).
You cannot create an INSTEAD OF trigger on views that have the WITH CHECK
OPTION defined.
Example:
This example creates a table with customers in Germany and a table with customers in
Mexico. An INSTEAD OF trigger placed on the view redirects updates to the appropriate
underlying table. The insert to the Customers table occurs instead of the insert to the view.

**Create two tables with customer data in the Northwind database

SELECT * INTO CustomersGer FROM customers


WHERE Customers.Country =’Germany’
SELECT * INTO CustomesMex FROM Customers
WHERE Customers.Country= ‘Mexico’
Go

**Create a view on the data

CREATE VIEW CustomersView AS


SELECT * FROM CustomersGer
UNION
SELECT * FROM CustomersMex
GO
** Create an INSTEAD OF trigger on the view
CREATE TRIGGER Customers_Update2
ON CustomersView
INSTEAD OF UPDATE AS
Declare @Country varchar (15)
SET @Country = ( select country from Inserted)
IF @Country = ‘Germany’
BEGIN
UPDATE CustomersGer
SET CustomersGER.Phone = Inserted.Phone
FROM CustomersGer JOIN Inserted
ON CustomersGer. CustomerID = Inserted.CustomerID
END
ELSE
IF @Country = ‘Mexico’
BEGIN
UPDATE CustomersMex
SET CustomersMex.Phone = Inserted.Phone
FROM CustomersMex JOIN Inserted
ON CustomersMex. CustomerID = Inserted.CustomerID
END

**** Test the trigger by updating the view


UPDATE CustomersView SET Phone =’030-0078769’
WHERE CustomerID = ‘ALFKI’

SELECT CustomerID, Phone FROM CustomersView


WHERE CustomerID =’ALFKI’

SELECT CustomerID, Phone FROM CustomerGer


WHERE CustomerID =’ALFKI’
Exercises
1. Create a trigger that notifies when we insert and update a data.
2. Create a trigger that transfers data from one table to another table.
3. Create trigger that shows the difference when we update the price of some thing in a
table.

1. Create a trigger that guarantees that the sum of all penalties for one player is not
more than 250 Birr
4. Create a trigger called BIRTHJOINED that the year of birth of a player is at least
lower than the year he or she joined the club
5. Remove the BIRTHJOINED trigger.
Appendix
A. Foot ball League Database

Create table Player


Create table Team (
( PlayerNo int not null,
TemaNo int not null, Name char(15),
PlayerNo int not null, BirthDate Datetime,
Division varchar(10), Sex char(1),
Primary Key (TeamNo) Joined int not unll
) Street char(15),
HouseNo varcahr (6),
PostCode varchar(6),
Town varchar (10),
Create table Penalty
PhoneNo varchar(10),
(
LeagueNo
PaymentNo int not null,
varcahr(10),
PlayerNo int,
Primry key (PlayerNo)
Payment_Date datetime,
)
Amount float ,
Primary Key
(PaymentNo) Create table Committee_member
(
PlayerNo int not null,
begin_Date datetime,
Create table Match End_date datetime,
( Postiton varcahr (20),
MatchNo int not null, Primary Key (PlayerNo, Begin_Date)
TeamNo int not null, )
PlayerNo int ,
Won int,
Lost int
Primary key (matchNo)
)
B. Credit Database
payment *
statement * payment_no

statement_no member_no
status
status_code
member_no member * payment_due_dt

statement_dt member_no payment_dt


status_desc
due_dt lastname payment_amt

statement_amt firstname payment_principle

statement_current middleinitial payment_latechg

statement_pastdue street statement_no

statement_latechg city payment_code

statement_code state_prov
country
mail_code
phone_no

region * issue_dt corporation


region_no expr_dt corp_no

region_name region_no corp_name

street corp_no street


provider * city
city prev_balance
provider_no
state_prov curr_balance state_prov
provider_name
country member_code country
street
mail_code mail_code
city
phone_no phone_no
state_prov
region_code expr_dt
mail_code
region_no
country
corp_code
phone_no
issue_dt
expr_dt
charge *
charge_no
region_no
member_no
provider_code
provider_no
category *
category_no
category_no
charge_dt
category_desc
charge_amt
category_code
statement_no
charge_code

You might also like