DBMS LAB Manual FINAL
DBMS LAB Manual FINAL
Introduction to
Database Management Systems
Laboratory Work
(CSC - 221 L)
Version 2.0
DEPARTMENT OF SOFTWARE ENGINEERING (DSE)
FOUNDATION UNIVERSITY RAWALPINDI CAMPUS (FURC)
www.fui.edu.pk
http://www.fui.edu.pk/FURC/
PREFACE
This lab manual has been prepared to facilitate the students of software engineering in
studying and analysing various components of a database system. The lab focuses on
creating and manipulating databases. The programming language for database system
Structured Query Language (SQL) is taught. The manual also addresses advanced concepts
including database connectivity in programming languages.
PREPARED BY
Lab manual is prepared by Mr. Muhammad Usman Khan, Mr.Umar Mehmood and Mr. Hafeez
Javed under the supervision of Head of Department Dr. Muhammad Shaheen in year 2016.
GENERAL INSTRUCTIONS
a. Students are required to maintain the lab manual with them till the end of the semester.
b. All readings, answers to questions and illustrations must be solved on the place
provided. If more space is required, then additional sheets may be attached.
c. It is the responsibility of the student to have the manual graded before deadlines as
given by the instructor
d. Loss of manual will result in re submission of the complete manual.
e. Students are required to go through the experiment before coming to the lab session.
Lab session details will be given in training schedule.
f. Students must bring the manual in each lab.
g. Keep the manual neat clean and presentable.
h. Plagiarism is strictly forbidden. No credit will be given if a lab session is plagiarised and
no re submission will be entertained.
i. Marks will be deducted for late submission.
Version History
Date Update By Details
January 2017 Muhammad Usman Khan Version 1.0
2
MARKS
Grand Total
3
Contents
Contents 4
4
LAB 1 – INTRODUCTION (TRADITIONAL FILE SYSTEM VS DATABASES)
OBJECTIVE:
To learn the advantages of databases approach over traditional file system approach
1. Program-Data Dependence
a. All programs maintain metadata for each file they use
i. It is the tight relationship between data stored in files and the specific programs
required to update and maintain those files
ii. Change in the file format affects both the program and the file
iii. Lack of coordination and central control
iv. Non-standard file formats
2. Duplication of data
a. Different systems/programs have separate copies of the same data
i. Waste of space to have duplicate data
ii. Causes more maintenance headaches
iii. The biggest Problem:
1. When data changes in one file, could cause inconsistencies
2. Compromises data integrity
3. Limited Data Sharing
a. No centralized control of data
i. Limited data for processing
ii. Managers face difficulty in generating reports
5
iii. Incompatible files are separate systems
4. Lengthy Development Times
a. Programmers must design their own file formats
i. The new application must follow the file pattern of the old system
ii. Therefore, programmers prefer developing the program from scratch
iii. System becomes static
5. Excessive Program Maintenance
a. 80% of information systems budget
i. Managing a non-centralized data is more difficult
ii. All replicated data must be consistent
iii. Therefore, more budget is required during maintenance
1. Program-Data Independence
a. Metadata stored in DBMS, so applications don’t need to worry about data formats
b. Data queries/updates managed by DBMS so programs don’t need to process data access
routines
c. Results in: increased application development and maintenance productivity
6
2. Minimal Data Redundancy
a. Leads to increased data integrity/consistency
3. Improved Data Sharing
a. Different users get different views of the data
4. Enforcement of Standards
a. All data access is done in the same way
5. Improved Data Quality
a. Constraints, data validation rules
6. Better Data Accessibility/ Responsiveness
a. Use of standard data query language (SQL)
7. Security, Backup/Recovery, Concurrency
a. Disaster recovery is easier
Database
A database can be summarily described as a repository for data. This makes clear that building
databases is really a continuation of a human activity that has existed since writing began; it can be
applied to the result of any bookkeeping or recording activity that occurred long before the advent of
the computer era.
The creation of a database is required by the operation of an enterprise. We use the term enterprise to
designate a variety of endeavours that range from an airline, a bank, or a manufacturing company to a
stamp collection or keeping track of people to whom you want to write New Year cards.
A database management system (DBMS) is an aggregate of data, hardware, software, and users that
helps an enterprise manage its operational data. The main function of a DBMS is to provide efficient
and reliable methods of data retrieval to many users.
Exercise 1.1:
Compare the traditional file processing system with database management system with help of an
example.
Resources:
7
LAB 2 – INTRODUCTION TO RDBMS
OBJECTIVE:
To learn the basic concepts of RDBMS including Entities, Attributes, Relationships, Business Rules and
ER Diagram.
Data Modelling
1. Business Rules
Statements that define or constrain some aspect of the business
2. Conceptual Modelling
a. Entity-Relationship Model
i. A logical representation of data for an organization
ii. Expressed in terms of entities, attributes and relationships
b. Entity-Relationship Diagram
i. A graphical representation of an entity-relationship model
Entities:
Relationships:
Identify the entities - Entities are easy to recognize as they are represented by nouns.
8
Identify attributes - these are qualities/values associated with entities
Identify the relationships between the entities - relationships are identified by verbs
Link entities to attributes and link entities together via their relationships
Business Rules:
1. A CUSTOMER may submit any number of ORDERs. However, each ORDER must be submitted
by exactly one CUSTOMER.
2. A SUPPLIER may supply many ITEMs. Each ITEM is supplied by any number of SUPPLIERs.
3. A SHIPMENT must include one(or more) ITEMs. An ITEM may be included on several
SHIPMENTs
4. Each ITEM must be used in at least one PRODUCT. Conversely, each PRODUCT must use one or
more ITEMs.
SOLUTION:
ER Diagram:
9
Exercise 2.2:
a)
b)
Resources:
1. https://www.google.com.pk/url?
sa=t&rct=j&q=&esrc=s&source=web&cd=9&cad=rja&uact=8&ved=0ahUKEwifhOPHn8bR
AhXCzxQKHd5ABYUQFghGMAg&url=https%3A%2F%2Fptop.only.wip.la%3A443%2Fhttp%2Fwww.csub.edu%2F~ychoi2%2FMIS
%2FDatabase
%2FDBlecture_2%2FERD_01.ppt&usg=AFQjCNFeMfACBxfM87MzqLiTHm5oQUdGLw&bvm=b
v.144224172,d.d24
2. An Introduction to Database Systems by C.J. Date
3. Introduction to Database Systems Itl Education Solutions Limited. Pearson Education
10
LAB 3 – INTRODUCTION TO SQL
OBJECTIVE
THEORY
SQL (structured query language) is a programming language designed to manage and retrieve data
from RDBMS. RDBMS based on relational model in which we have tables and their relationships. The
relational model gives the semantic representation of data the way in which we think about data.
Set theory: in set theory, we have sets consists of entities having attributes. In database, we map our
real-world entities to set of entities having attributes. Then we use predicate logic to access data from
database. Predicate logic can be true or false. So, from database using predicate logic either we get
data or not.
SQL is used to manage and retrieve data from database. SQL processing based on relational algebra.
Relational algebra
Relational algebra is a procedural query language. Each relational query describes a step-by-step
procedure for computing the desired answer, based on the order in which operators are applied in the
query. The procedural nature of the algebra allows us to think of an algebra expression as a recipe, or
a plan, for evaluating a query, and relational systems in fact use algebra expressions to represent
query evaluation plans. Queries in algebra composed of collection of operators. Three basic operations
involved in relational algebra expressions are selection, projection and cross-product. SQL queries
intuitively correspond to relational algebra expressions involving selections, projections, and cross-
products. For example, consider following SQL query
Select studentName
From Student-table
Where marks>80%
History
SQL was developed at IBM by Donald D. Chamberlin and Raymond F. Boyce in the early 1970s. This
version, initially called SEQUEL (Structured English Query Language), was designed to manipulate
and retrieve data stored in IBM's original quasi-relational database management system. The
acronym SEQUEL was later changed to SQL because "SEQUEL" was a trademark of the UK-based
Hawker Siddeley aircraft company.
Industry-accepted committees are the American National Standards Institute (ANSI) and the
International Standards Organization (ISO), which is affiliated with the International Electro technical
Commission (IEC). Both ANSI and the ISO/IEC have accepted SQL as the standard language for
11
relational databases. When a new SQL standard is simultaneously published by these organizations,
the names of the standards conform to conventions used by the organization, but the standards are
technically identical.
Teradata: Teradata
IBM: DB2
Several vendors (e.g., IBM's DB2, Oracle 8, and Informix2 UDS) extended their systems with the ability
to store new data types such as images and text, and to ask more complex queries. Specialized systems
have been developed by numerous vendors for creating data warehouses, consolidating data from
several databases, and for carrying out specialized analysis.
DDL: data-definition language provides commands for create, alter, truncate and drop tables
DML: data-manipulation language provides commands for insert, delete and update rows.
DCL: Data-control language provides commands for grant and revokes access to users.
Data types
Each column in an SQL table declares the type(s) that column may contain. ANSI SQL includes the
following data types.
Character strings
Bit strings
Numbers
12
Date and time
Web Ressources
http://www.1keydata.com/
http://www.w3schools.com/
13
LAB 4 – MS SQL Server Installation and Introduction to SQL Management Studios
OBJECTIVE
To Install MS SQL Server Express Edition and create database from ERD from LAB 2 using SQL
Management studios GUI.
Installation Guide :
You can download MS SQL server Express Edition for free from Microsoft Website from the given link
and download the file named ExpressAndTools 32BIT\SQLEXPRWT_x86_ENU.exe.
https://www.microsoft.com/en-pk/download/details.aspx?id=42299
1. Launch SQLEXPR_x64_ENU.exe.
2. On the SQL Server Installation Center page, choose Installation, and then choose New
installation or add features to an existing installation.
4. On the Product Key page, type your product key or specify a free edition.
14
8. On the Feature Selection page, select the check boxes for the following components
o Management Tools.
10. On the Instance Configuration page, choose Default instance. If you choose Named instance,
type the name of the instance.
12. On the Server Configuration page, accept the defaults or enter the name of a domain account or
NT AUTHORITY\NETWORK SERVICE in Account Name for every service. If you specify a
domain account, type its password in Password. If you use NT AUTHORITY\NETWORK
SERVICE, leave Password blank.
15
13. In the Startup Type column, verify that Automatic appears for all services that you can edit, and
then click Next.
14. If you selected the Database Engine Services check box in step 8, on the Database Engine
Configuration page, choose Windows authentication mode, choose Add Current User.
Otherwise skip to the next step.
16. On the Ready to Install page, review the list of components to be installed, and then choose
Install.
Launch MS-SQL Server Management Studios and follow the steps as instructed to create new database
using GUI as discussed in Lab 2.
16
LAB 5 – DATA DEFINITION LANGUAGE (DDL)
OBJECTIVE
To learn create, alter, drop and truncate table commands in SQL Management Studios.
THEORY
Create an object
Alter the structure of an object
To drop the object created.
The commands used are:
Create
Alter
Drop
Truncate
PROGRAMS
Create Table
It is used to create a table.
Syntax:
Example:
First_Name char(50),
Last_Name char(50),
Address char(50),
City char(50),
Country char(25),
Birth_Date date
17
);
Alter Table
Example:
DROP TABLE
It will delete the table structure provided the table should be empty.
TRUNCATE TABLE
If there is no further use of records stored in a table and the structure has to be retained, then the
records alone can be deleted.
INTEGRITY CONSTRAINT
An integrity constraint is a mechanism used by oracle to prevent invalid data entry into the table. It
has enforcing the rules for the columns in a table. The types of the integrity constraints are:
a) Domain Integrity
b) Entity Integrity
c) Referential Integrity
A) Domain Integrity
This constraint sets a range and any violations that take place will prevent the user from performing
the manipulation that caused the breach. It includes:
18
Not NULL Constraint:
While creating tables, by default the rows can have null value. The enforcement of not null constraint
in a table ensures that the table contains values.
Example:
);
Columns "SID" and "Last_Name" cannot include NULL, while "First_Name" can include NULL.
Check Constraint:
Check constraint can be defined to allow only a particular range of values. When the manipulation
violates this constraint, the record will be rejected. Check condition cannot contain sub queries.
Example:
);
Column "SID" has a constraint -- its value must only include integers greater than 0.
B) Entity Integrity
Maintains uniqueness in a record. An entity represents a table and each row of a table represents an
instance of that entity. To identify each row in a table uniquely we need to use this constraint. There
are 2 entity constraints:
It is used to ensure that information in the column for each record is unique, as with telephone or
driver’s license numbers. It prevents the duplication of value with rows of a specified column in a set
of column. A column defined with the constraint can allow null value.
19
If unique key constraint is defined in more than one column i.e., combination of column cannot be
specified. Maximum combination of columns that a composite unique key can contain is 16.
Example:
A primary key avoids duplication of rows and does not allow null values. Can be defined on one or
more columns in a table and is used to uniquely identify each row in a table. These values should
never be changed and should never be null.
A table should have only one primary key. If a primary key constraint is assigned to more than one
column or combination of column is said to be composite primary key, which can contain 16 columns.
Example:
Create table stud (regno integer primary key, name char (20));
Note: Can’t be defined using alter command when there is records in the table having null values.
C) Referential Integrity
Foreign key
A column or combination of column included in the definition of referential integrity, which would
refer to a referenced key.
Example:
20
(
);
);
EXERCISE 5.1
21
Constraint No 2: Fname < 7 characters , Location < 6 characters
22
Constraint No 4: EmpId PK , DID FK in employee table
23
Web Resources for Additional Studies
http://www.1keydata.com/
http://www.w3schools.com/
24
LAB 6 – DATA MANIPULATION LANGUAGE (DML)
OBJECTIVE
To learn insert, select, update and delete commands
THEORY
DML commands are the most frequently used SQL commands and is used to query and manipulate the
existing database objects. Some of the commands are:
Insert
Select
Update
Delete
PROGRAMS
Insert Command
This is used to add one or more rows to a table. The values are separated by commas and the data
types char and date are enclosed in apostrophes. The values must be entered in the same order as
they are defined.
Syntax:
INSERT INTO table_name
VALUES (value1, value2, value3,...)
Example:
Insert into employee
Values (1,’ali’,3000,’01-12-2000);
Syntax:
INSERT INTO table_name
VALUES (value1, value2, value3,...), (value1, value2, value3,...), (value1, value2, value3,...);
Example:
Insert into employee
Values (1,’ali’,3000,’01-12-2000), (2,’omer’,5000,’01-12-2012), (3,’humza’,6000,’01-08-1998);
Select Commands
It is used to retrieve information from the table. It is generally referred to as querying the table. We
can either display all columns in a table or only specify column from the table.
Syntax: Select * from table_name; // This query selects all rows from the table.
25
Example: Select * from IT;
To select specific rows from a table we include ‘where’ clause in the select command. It can appear
only after the ‘from’ clause.
Syntax: Select column_name1, …..,column_namen from table name where condition order by
colmnname;
Update Command
It is used to alter the column values in a table. A single column may be updated or more than one
column could be updated.
Delete command
After inserting row in a table we can also delete them if required. The delete command consists of a
from clause followed by an optional where clause.
EXERCISE 6.1:
27
Q2. List out the employee’s annual salary with their names only
Q3. List out employee’s name who are earning salary between 30000 and 40000
Q5. List out employees name whose name start with ‘a’
Q6. List out employee id last name in ascending order based on employee id
28
29
LAB 7 – SQL FUNCTIONS
OBJECTIVE
To learn SQL arithmetic functions, subqueries and implement in SQL Management Studios.
THEORY
SQL has several arithmetic functions, and they are:
• AVG: Average of the column.
• COUNT: Number of records.
• MAX: Maximum of the column.
• MIN: Minimum of the column.
• SUM: Sum of the column.
PROGRAMS
Syntax:
SELECT "function type" ("column_name")
FROM "table_name"
Examples:
Avg: SELECT AVG(Sales) FROM Store_Information;
Count: SELECT COUNT(store_name) FROM Store_Information
Max: SELECT MAX(Sales) FROM Store_Information
Min: SELECT MIN(Sales) FROM Store_Information
Sum: SELECT SUM(Sales) FROM Store_Information
Group by Clause:
This allows us to use simultaneous column name and group functions.
Having clause
count(*)>=50;
SUBQUERY
The query within another is known as a subquery. A statement containing subquery is called parent
statement. The rows returned by subquery are used by the parent statement.
PROGRAMS
Syntax:
SELECT "column_name1"
FROM "table_name1"
WHERE "column_name2" [Comparison Operator]
(SELECT "column_name3"
30
FROM "table_name2"
WHERE [Condition])
Example:
select ename, eno, address where salary >(select salary from employee where
ename =’jones’);
Types
Subqueries can also return more than one value. Such results should be made use along with the
operators in and any.
Example:
select ename, eno, from employee where salary <any (select salary from employee where deptno
=10’);
2. Multiple queries
Here more than one subquery is used. These multiple subqueries are combined by means of ‘and’ &
‘or’ keywords.
3. Correlated subquery
A subquery is evaluated once for the entire parent statement whereas a correlated subquery is
evaluated once per row processed by the parent statement.
Example:
select * from emp x where x.salary > (select avg(salary) from emp where
deptno =x.deptno);
Above query selects the employee’s details from emp table such that the salary of employee is > the
average salary of his own department.
EXERCISE 7.1
Q1. How many employees who are working in different department wise in the organization.
31
Q2. List out department wise maximum annual salaries, minimum anuual salaries and average annual
salaries of employees
Q4. Display the department id, having greater than or equal to 3 employees joined in April 1985
EXERCISE 7.2:
Q1. Display the employee details who got second highest salary.
Q2. List out the employees who earn more than the lowest salary in department 11
Q3. Find out the employees who earn greater than the average salary of their department.
32
Q4. Display the employee who got the maximum salary.
Q5. List out the employees who earn more than every employee in department 11
33
LAB 8 – COMPUTED COLUMNS / REFERENTIAL INTEGRITY
OBJECTIVE
To learn how to create computed columns in SQL.
Computed Columns
A computed column is a column that contains values that are calculated, rather than
inserted.
The expression for a computed column may include the names of other, non-computed
columns from the table.
PROGRAMS
Example:
Create Table studentMarks
(
SID integer primary key,
Cname char(30),
Quizes integer check (Quizes <10),
Assignments integer check (Assignments <10),
Mid integer check (Mid <30),
Final integer check(Final <50),
TotalMarks AS (Quizes + Assignments + Mid + Final)
);
Referential Integrity
Referential integrity is with the relationships between the tables of a database, i.e that
the data of one table does not contradict the data of another table. Specifically, every
foreign key value in a table must have a matching primary key value in the related table.
This is the most common type of integrity constraint. This is used to manage the
relationships between primary and foreign keys.
34
Let's assume the department and employee entities have been implemented as tables in
a relational database system. When entering a new employee, the department in which
they work needs to be specified. Department number is the foreign key in the employee
table and the primary key in the department table. In order to preserve the integrity of
the data in the database there are a set of rules that need to be observed:
If inserting an employee in the employee table, the insertion should only be
allowed if their department number exists in the department table
If deleting a department in the department table, the deletion should only be
allowed if there are no employees working in that department
• If changing the value of a department number in the department table, the
update should only be allowed if there are no employees working in the
department whose number is being changed
• If changing the value of a department number in the employee table, the update
should only be allowed if the new value exists in the department table
• If any of the above is allowed to happen, then we have data in an inconsistent
state. The integrity of the data is compromised - the data does not make sense.
Example:
Consider two different tables Albums and Tracks, they contains a list of Albums and a
list of Tracks in each Album respectively. Tracks contains a foreign key constraint to
AlbumID in Albums. Now, if we update an AlbumID in Albums, this also need to be
updated in Tracks for all Tracks belonging to AlbumID.
35
Cascading can be defined for UPDATE and DELETE. There are four different options
available
1. SET NULL:
This action specifies that the column will be set to NULL when the referenced column is
updated/deleted.
2. CASCADE:
CASCADE specifies that the column will be updated when the referenced column is
updated, and rows will be deleted when the referenced rows are deleted.
3. SET DEFAULT:
Column will be set to DEFAULT value when UPDATE/DELETE is performed on
referenced rows.
4. NO ACTION:
This is the default behavior. If a DELETE/UPDATE is executed on referenced rows, the
operation is denied. An error is raised.
36
Select * from Tracks
• From the above output we can see that AlbumID has also been set to 2 in Tracks,
where it was 4 earlier.
37
LAB 9 – CASE STUDY
OBJECTIVE:
To implement the concepts of relational databases in MS SQL.
A member can borrow up to three books at a time from library. Library staff is responsible to
maintain book card with member details, the issue date and return date on the basis of which
fines can be calculated for late return.
A list of available books and with uniquely assigned serial number is maintain for searching a
book from a particular shelf in a specific block of library.
If a member requests a book from the list, the library staff can check its availability from book
card and inform the member if the book is currently available or not. If it’s available library
staff can direct student to that block and shelf where book is actually placed.
Currently library staff also maintain a membership card for each member and writes the
book serial number (each book have different serial number), issue date and on return the
staff write the return date, calculates the fine in case of late return.
The sample of book card, member card and list of available books is given below.
BOOK CARD
Note: if return date is empty it means book is not available. Also, assume library has
four blocks and in each block 25 shelves are placed.
38
MEMBER CARD
EXERCISE 9.1:
2. Draw complete E-R Diagram showing all the relationship between entities in part a.
39
3. Write Business Rules considering the E-R Diagram you made in part b.
4. Resolve many to many relationships if any and draw new E-R diagram if different
from part b.
40
5. Explain how your database solution is efficient as compared to existing system.
41
LAB 10 – JOIN ALGORITHMS
OBJECTIVE
To learn join algorithms in SQL
THEORY
PROGRAMS
Syntax:
• Select
• From
• Join
• On
• Where
Cross Join
• A cross join (also called a Cartesian join) is a join of tables without specifying the
join condition.
• In this scenario, the query would return all possible combination of the tables in
the SQL query.
• CROSS JOIN returns the Cartesian product of rows from tables in the join.
• In other words, it will produce rows which combine each row from the first table
with each row from the second table.
Cartesian product
• In mathematics, a Cartesian product (or product set) is the direct product of two
sets.
• Specifically, the Cartesian product of two sets X (for example the points on an x-
axis) and Y (for example the points on a y-axis), denoted X × Y, is the set of all
possible ordered pairs whose first component is a member of X and whose
second component is a member of Y (e.g., the whole of the x–y plane):
42
Example:
• A = {1,2}; B = {3,4}
• A × B = {1,2} × {3,4} = {(1,3), (1,4), (2,3), (2,4)}
Inner join
• Inner join creates a new result table by taking
• Cartesian product
• filter (join predicate)
• An inner join in SQL returns rows where there is at least one match on both
tables.
Composite join
• Has more than one condition on single ON clause.
Example:
Select *
FROM Table1 AS T1
INNER JOIN Table2 AS T2
ON T1.col1 = T2.col1 AND T1.col2 = T2.col2
Equijoin
• Has an only equality comparison on join predicate.
Example:
43
Select *
FROM Table1 AS T1
INNER JOIN Table2 AS T2
ON T1.col1 = T2.col1
Non-equijoin
• Has other operator than equality on join predicate.
Select *
FROM Table1 AS T1
INNER JOIN Table2 AS T2
ON T1.col1 != T2.col1
Multitable join
• Use to join more than two tables. Processing starts from left to right.
Select *
FROM Table1 AS T1
INNER JOIN Table2 AS T2
ON T1.col1 = T2.col1
INNER JOIN Table3 AS T3
ON T2.col1 = T3.col1
44
SELECT * FROM employee LEFT OUTER JOIN department ON employee.DepartmentID
= department.DepartmentID;
Self Join
A self-join is joining a table to itself.
45
• Write a query to display the employee and their manager details.
• Output should like:
• Employee Name Manager Name
EXCERCISE 10.1:
46
Write the following SQL queries:
2. How many employees who are working in different departments and display
with department name.
47
6. Display all employees in sales or operation departments.
48
LAB 11 – SQL PROGRAMMING (STORED PROCEDURES)
OBJECTIVE
To learn how to create procedures in SQL
THOERY
Sql server allows you to create three types of programmable objects:
• Stored Procedures
• User Defined Functions
• Triggers
Stored Procedures
Procedures promote reusability and maintainability. Once validated, they can be used in
number of applications. If the definition changes, only the procedure are affected, this
greatly simplifies maintenance.
· Break down a complex problem into a set of manageable well defined logical modules
and implement the modules with blocks.
Sql server compiles each stored procedure once and then store compile and execution
plans in query cache and reuse for subsequent executions. so you get tremendous
performance boost when stored procedures are called repeatedly.
Abstraction:
Stored procedures provide an abstraction layer that shields applications from the
underlying database structure.
PROGRAMS
Procedure:
- No return.
- PROCEDURE name AS
49
(parameter1 [model1] datatype1,
…)
AS
PL/SQL Block;
Example:
(@v_id int)
AS
BEGIN
WHERE empno=@v_id;
END
Variables
•
Sql server provides two types of variables:
•
Local and Global
•
Local variable is instantiated with single @ sign while global variable is
instantiated with double @@ sign.
• Variables are declared with DECLARE clause where you specify name and data
type of variable.
• Either SET or SELECT is used to assign a value to a variable.
Example:
• If/else
• Declare @var int
• Set @var = 1
• If @var = 1
• Print ‘this is the code executed when true’
• Else
• Print ’this is the code executed when false’
50
While loop
Parameters
• Parameters are local variables that are used to pass values into a stored
procedure when it is executed.
• U can create two types of parameters:
• Input and output
• Output parameters are used when u need to return a single value to an
application.
Input parameters example
51
EXERCISE 11.1:
Q NO 1: Create a stored procedure that takes name of the student as input and display
the grades of that student with course code.
Q NO 2: Create a stored procedure that displays the names of students who got
maximum and minimum CGPA.
Q NO 3: Write a stored procedure that takes student name as input and displays course
names along with cgpa for that student.
52
Q NO 4: Create a stored procedure that takes the student ID as input and display either
that student is on avg, below avg or above avg.
53
LAB 12 – SQL PROGRAMMING (TRIGGERS)
OBJECTIVE
To learn how to create triggers in SQL.
TRIGGERS
2. Database Trigger: Fires whenever a data event (such as DML) occurs on a schema or
database.
DDL Triggers
• Create
• Alter
• Drop
• For/After (create/alter/drop)
• AFTER specifies that the DML trigger is fired only when all operations specified
in the triggering SQL statement have executed successfully. All referential
cascade actions and constraint checks also must succeed before this trigger fires.
• AFTER is the default when FOR is the only keyword specified.
DML Trigger
• Insert
• Update
• Delete
• For/After ( insert, update, delete)
• Instead of ( insert, update, delete)
• Specifies that the DML trigger is executed instead of the triggering SQL
statement, therefore, overriding the actions of the triggering statements.
INSTEAD OF cannot be specified for DDL or logon triggers and DML.
• When a trigger is executed, two special tables inserted and deleted are available.
• These tables help to maintain the record of updates.
PROGRAMS
Example of DDL Trigger
54
Example of DML trigger
• Create a DML trigger on CDR table to UPDATE the record of monthly bills in Bills
Table.
CDR TABLE
BILLS TABLE
UPDATE [BILLS]
55
SET BILL_REV = @nCOST+BILL_REV,
BILL_DATE=@dDAT
FROM BILLS
WHERE BILL_PH_NO= @nDFR AND
BILL_MONTH=MONTH(@dDAT) AND BILL_YEAR = YEAR (@dDAT)
END
// else add insert new record in Bills Table
ELSE
BEGIN
INSERT INTO BILLS (BILL_PH_NO,BILL_REV,BILL_DATE) VALUES (@nDFR,@nCOST,@dDAT)
END
EXCERCISE 12.1:
Create the CDR and Bills table and apply the specified trigger on Bills Table for every
new record in CDR Table.
56
LAB 13 – SQL SERVER INDEX STRUCTURES
OBJECTIVE
To learn indexing schemes in SQL server
Indexes are created on columns in tables or views. The index provides a fast way to look
up data based on the values within those columns. For example, if you create an index
on the primary key and then search for a row of data based on one of the primary key
values, SQL Server first finds that value in the index, and then uses the index to quickly
locate the entire row of data. Without the index, a table scan would have to be
performed in order to locate the row, which can have a significant effect on
performance.
You can create indexes on most columns in a table or a view. The exceptions are
primarily those columns configured with large object (LOB) data types, such as image,
text, and varchar(max). You can also create indexes on XML columns, but those indexes
are slightly different from the basic index and are beyond the scope of this article.
Instead, I’ll focus on those indexes that are implemented most commonly in a SQL
Server database.
An index is made up of a set of pages (index nodes) that are organized in a B-tree
structure. This structure is hierarchical in nature, with the root node at the top of the
hierarchy and the leaf nodes at the bottom, as shown in Figure 1.
57
Figure 1: B-tree structure of a SQL Server index
When a query is issued against an indexed column, the query engine starts at the root
node and navigates down through the intermediate nodes, with each layer of the
intermediate level more granular than the one above. The query engine continues down
through the index nodes until it reaches the leaf node. For example, if you’re searching
for the value 123 in an indexed column, the query engine would first look in the root
level to determine which page to reference in the top intermediate level. In this
example, the first page points the values 1-100, and the second page, the values 101-
200, so the query engine would go to the second page on that level. The query engine
would then determine that it must go to the third page at the next intermediate level.
From there, the query engine would navigate to the leaf node for value 123. The leaf
node will contain either the entire row of data or a pointer to that row, depending on
whether the index is clustered or nonclustered.
Clustered Indexes
A clustered index stores the actual data rows at the leaf level of the index. Returning to
the example above, that would mean that the entire row of data associated with the
primary key value of 123 would be stored in that leaf node. An important characteristic
of the clustered index is that the indexed values are sorted in either ascending or
descending order. As a result, there can be only one clustered index on a table or view.
In addition, data in a table is sorted only if a clustered index has been defined on a table.
58
Note: A table that has a clustered index is referred to as a clustered table. A table that
has no clustered index is referred to as a heap.
Nonclustered Indexes
Unlike a clustered indexed, the leaf nodes of a nonclustered index contain only the
values from the indexed columns and row locators that point to the actual data rows,
rather than contain the data rows themselves. This means that the query engine must
take an additional step in order to locate the actual data.
Nonclustered indexes cannot be sorted like clustered indexes; however, you can create
more than one nonclustered index per table or view. SQL Server 2005 supports up to
249 nonclustered indexes, and SQL Server 2008 support up to 999. This certainly
doesn’t mean you should create that many indexes. Indexes can both help and hinder
performance, as I explain later in the article.
In addition to being able to create multiple nonclustered indexes on a table or view, you
can also add included columns to your index. This means that you can store at the leaf
level not only the values from the indexed column, but also the values from non-indexed
columns. This strategy allows you to get around some of the limitations on indexes. For
example, you can include non-indexed columns in order to exceed the size limit of
indexed columns (900 bytes in most cases).
Index Types
Composite index: An index that contains more than one column. In both SQL
Server 2005 and 2008, you can include up to 16 columns in an index, as long as
the index doesn’t exceed the 900-byte limit. Both clustered and nonclustered
indexes can be composite indexes.
Unique Index: An index that ensures the uniqueness of each value in the indexed
column. If the index is a composite, the uniqueness is enforced across the
columns as a whole, not on the individual columns. For example, if you were to
create an index on the FirstName and LastName columns in a table, the names
together must be unique, but the individual names can be duplicated.
A unique index is automatically created when you define a primary key or unique
constraint:
59
o Primary key: When you define a primary key constraint on one or more
columns, SQL Server automatically creates a unique, clustered index if a
clustered index does not already exist on the table or view. However, you
can override the default behavior and define a unique, nonclustered index
on the primary key.
o Unique: When you define a unique constraint, SQL Server automatically
creates a unique, nonclustered index. You can specify that a unique
clustered index be created if a clustered index does not already exist on
the table.
Covering index: A type of index that includes all the columns that are needed to
process a particular query. For example, your query might retrieve the
FirstName and LastName columns from a table, based on a value in the ContactID
column. You can create a covering index that includes all three columns.
Database
As mentioned above, indexes can enhance performance because they can provide a
quick way for the query engine to find data. However, you must also take into account
whether and how much you’re going to be inserting, updating, and deleting data. When
you modify data, the indexes must also be modified to reflect the changed data, which
can significantly affect performance. You should consider the following guidelines when
planning your indexing strategy:
For tables that are heavily updated, use as few columns as possible in the index,
and don’t over-index the tables.
If a table contains a lot of data but data modifications are low, use as many
indexes as necessary to improve query performance. However, use indexes
judiciously on small tables because the query engine might take longer to
navigate the index than to perform a table scan.
For clustered indexes, try to keep the length of the indexed columns as short as
possible. Ideally, try to implement your clustered indexes on unique columns
that do not permit null values. This is why the primary key is often used for the
table’s clustered index, although query considerations should also be taken into
account when determining which columns should participate in the clustered
index.
The uniqueness of values in a column affects index performance. In general, the
more duplicate values you have in a column, the more poorly the index performs.
On the other hand, the more unique each value, the better the performance.
When possible, implement unique indexes.
For composite indexes, take into consideration the order of the columns in the
index definition. Columns that will be used in comparison expressions in the
WHERE clause (such as WHERE FirstName = ‘Charlie’) should be listed first.
Subsequent columns should be listed based on the uniqueness of their values,
with the most unique listed first.
60
There are three types of index structures in sql server:
• Clustered indexes
• Non-clustered indexes on heap
• Non-clustered indexes on clustered index
create a non clustered index on last_name and look up the address by last_name:
non-cluster on cluster index
create nonclustered index idxnon on contact(last_name)
Lab# 12 EXCERCISE
61
LAB 14 – SQL VIEWS
OBJECTIVE
To learn views in SQL server
THEORY
Creates a virtual table whose contents (columns and rows) are defined by a query. Use
this statement to create a view of the data in one or more tables in the database. For
example, a view can be used for the following purposes:
To focus, simplify, and customize the perception each user has of the database.
As a security mechanism by allowing users to access data through the view,
without granting the users permissions to directly access the underlying base
tables.
Create Views
Modify the view by adding a WHERE clause to limit the rows returned.
You can modify the data of an underlying base table through a view, as long as the
following conditions are true:
62
Any modifications, including UPDATE, INSERT, and DELETE statements, must
reference columns from only one base table.
The columns being modified in the view must directly reference the underlying
data in the table columns. The columns cannot be derived in any other way, such
as through the following:
The columns being modified are not affected by GROUP BY, HAVING, or
DISTINCT clauses.
EXAMPLE:
UPDATE VIEW_NAME
SET COL1 = '20110203', COL2 = GETDATE()
WHERE LastName = N'Smith' AND FirstName = 'Samantha';
Delete Views
When you drop a view, the definition of the view and other information about the view
is deleted from the system catalog. All permissions for the view are also deleted.
EXERCISE 14.1:
Create views on any sample database, and update the contents through views.
63
LAB 15 – DATABASE CONNECTIVITY IN VISUAL STUDIOS
OBJECTIVE
To connect to MS SQL server database in visual studios using C# Windows Form
Application.
.NET Framework always provide the basic implementation of working with data and the
basic functions that you can use in your code. Data can be extracted from some files, can
be a data in your application, from a database software etc. In .NET you can work with
them, using the namespaces provided by .NET framework.
System.Data.SqlClient
This assembly (namespace) of .NET Framework contains all of the classes required to
connect to the databases, read/write data to the databases.
Errors, Success reports are generated by it. SqlError is generated for errors, and the
success codes are executed and shown on the screen.
using System.Data.SqlClient;
Connection to a database requires a connection string. This string has the information
about the server you're going to connect, the database you will require and the
credentials that you can use to connect. Each database has its own properties, its own
server, name and type of login information, using which you can connect to the database
to read/write the data from it.
"password=password;server=serverurl;" +
"Trusted_Connection=yes;" +
"database=database; " +
"connection timeout=30");
myConnection.Open(); // open connection for the connections string
EXAMPLE 1:
64
SqlConnection myConnection = new SqlConnection("user id=sa;" +
"password=sa;server=localhost;" +
"Trusted_Connection=yes;" +
"database=database; " +
"connection timeout=30");
myConnection.Open(); // open connection for the connections string
EXAMPLE 2:
try
{
sqlConnection.ConnectionString = “Data Source=localhost\sqlexpress;Initial
Catalog=sampleDB;User ID=sa;Password=sa”;
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand(cmdText,
sqlConnection);
SqlDataAdapter sqlDataAdaptor = new
SqlDataAdapter(sqlCommand);
sqlDataAdaptor.Fill(dt);
if (dt.Rows.Count > 0)
{
dataGridView1.DataSource = dt;
}
else
MessageBox.Show("No Records Found", "Record Management",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
catch (Exception ex)
65
{
MessageBox.Show(ex.Message + " ==> " + cmdText, "Db Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
sqlConnection.Close();
}
}
Follow the step to create windows form application using C#, connect to sample
database, execute DDL queries and view data in data grid view from specified table in
database.
66
“The best charity on a part of Muslim is
to acquire knowledge and impart it to others.”
Prophet Muhammad (P-B-U-H)
67