0% found this document useful (0 votes)
102 views

DBMS LAB Manual FINAL

Here are the key steps to draw an ERD from given business rules: 1. Identify the main entities from the nouns in the business rules. The entities should be things that can have attributes associated with them. 2. Identify the attributes of each entity. Attributes describe properties or characteristics of the entities. 3. Identify the relationships between entities. Relationships are identified from verbs that connect two entities. 4. Draw the entities as rectangles or tables and name them. 5. Draw the attributes inside the entity rectangles. 6. Draw the relationships between entities as lines connecting them. Label the relationships with the type of relationship (one-to-one, one-to-many

Uploaded by

Mohsin Alee Alvi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views

DBMS LAB Manual FINAL

Here are the key steps to draw an ERD from given business rules: 1. Identify the main entities from the nouns in the business rules. The entities should be things that can have attributes associated with them. 2. Identify the attributes of each entity. Attributes describe properties or characteristics of the entities. 3. Identify the relationships between entities. Relationships are identified from verbs that connect two entities. 4. Draw the entities as rectangles or tables and name them. 5. Draw the attributes inside the entity rectangles. 6. Draw the relationships between entities as lines connecting them. Label the relationships with the type of relationship (one-to-one, one-to-many

Uploaded by

Mohsin Alee Alvi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 67

Computer Laboratory Manual

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

February 2018 Muhammad Sajid Qureshi Version 2.0

2
MARKS

LAB Date Max. Marks Marks Instructor


NO Conducted Obtained Sign
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Grand Total

3
Contents
Contents 4

LAB 1 – INTRODUCTION (TRADITIONAL FILE SYSTEM VS DATABASES) 5

LAB 2 – INTRODUCTION TO RDBMS 8

LAB 3 – INTRODUCTION TO SQL 11

LAB 4 – MS SQL Server Installation and Introduction to SQL Management Studios 14

LAB 5 – DATA DEFINITION LANGUAGE (DDL) 17

LAB 6 – DATA MANIPULATION LANGUAGE (DML) 23

LAB 7 – SQL FUNCTIONS 27

LAB 8 – COMPUTED COLUMNS / REFERENTIAL INTEGRITY 30

LAB 9 – CASE STUDY 34

LAB 10 – JOIN ALGORITHMS 39

LAB 11 – SQL PROGRAMMING (STORED PROCEDURES) 45

LAB 12 – SQL PROGRAMMING (TRIGGERS) 49

LAB 13 – SQL SERVER INDEX STRUCTURES 52

LAB 14 – SQL VIEWS 57

LAB 15 – DATABASE CONNECTIVITY IN VISUAL STUDIOS 59

4
LAB 1 – INTRODUCTION (TRADITIONAL FILE SYSTEM VS DATABASES)

OBJECTIVE:

To learn the advantages of databases approach over traditional file system approach

Traditional File Processing Systems

Disadvantages of File Processing

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

The Database Approach

1. Central repository of shared data

2. Data is managed by a controlling agent

3. Stored in a standardized, convenient form

4. Easy to store, manipulate and retrieve

Advantages of Database Approach

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.

DBMS (Database Management Systems)

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.

1. A DBMS is a software program that manages a Database

2. It controls the organization, storage, management and retrieval of data in a database.

Exercise 1.1:

Compare the traditional file processing system with database management system with help of an
example.

Resources:

1. An Introduction to Database Systems by C.J. Date


2. Introduction to Database Systems Itl Education Solutions Limited. Pearson Education

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

Documenting rules and policies of an organization that govern data.

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:

 Entity instance–person, place, object, event, concept (often corresponds to a row in a


table)

 Entity Type–collection of entities (often corresponds to a table)

Relationships:

 Relationship instance–link between entities (corresponds to primary key-foreign key


equivalencies in related tables)

 Relationship type–category of relationship…link between entity types

Attribute–property or characteristic of an entity or relationship type (often corresponds to a field in a


table)

Steps to creating an ERD are as follows:

 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

Exercise 2.1: CLASS ACTIVITY

DRAW ERD from Given Business Rules

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:

Write business rules from the following ER Diagrams

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

To learn the features of SQL

THEORY

Structured Query Language

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.

The database concept based on set theory and predicate logic.

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.

Database vendors: The leading database vendors are:

Microsoft: MS SQL server, Transact SQL

Teradata: Teradata

Oracle: oracle, PL/SQL

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.

Several aspects of SQL:

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

 CHARACTER(n) or CHAR(n) — fixed-width n-character string, padded with spaces as needed


 CHARACTER VARYING(n) or VARCHAR(n) — variable-width string with a maximum size of n
characters
 NATIONAL CHARACTER(n) or NCHAR(n) — fixed width string supporting an international
character set
 NATIONAL CHARACTER VARYING(n) or NVARCHAR(n) — variable-width NCHAR string

Bit strings

 BIT(n) — an array of n bits


 BIT VARYING(n) — an array of up to n bits

Numbers

 INTEGER and SMALLINT


 FLOAT, REAL and DOUBLE PRECISION
 NUMERIC(precision, scale) or DECIMAL(precision, scale)

12
Date and time

 DATE — for date values (e.g., 2011-05-03)


 TIME — for time values (e.g., 15:51:36). The granularity of the time value is usually a tick (100
nanoseconds).
 TIME WITH TIME ZONE or TIMESTAMP — the same as TIME, but including details about the
time zone in question.
 TIMESTAMP — This is a DATE and a TIME put together in one variable (e.g., 2011-05-03
15:51:36).
 TIMESTAMP WITH TIME ZONE or TIMESTAMPTZ — the same as TIMESTAMP, but including
details about the time zone in question.

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.

3. On the Setup Support Rules page, choose OK.

4. On the Product Key page, type your product key or specify a free edition.

5. On the License Terms page, accept the license agreement.

6. On the Setup Support Rules page, choose Next.

7. On the Setup Role page, choose SQL Server Feature Installation.

14
8. On the Feature Selection page, select the check boxes for the following components

o Database Engine Services

o Client Tools Connectivity

o Management Tools.

9. On the Installation Rules page, choose Next.

10. On the Instance Configuration page, choose Default instance. If you choose Named instance,
type the name of the instance.

11. On the Disk Space Requirements page, choose Next.

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.

15. On the Installation Rules page, choose Next.

16. On the Ready to Install page, review the list of components to be installed, and then choose
Install.

Exercise 4.1: Class Activity

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

DDL Commands in RDBMS:


It is used to communicate with database. DDL is used to:

 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:

CREATE TABLE table_name


(
column_name1 data_type constraint,
column_name2 data_type constraint,
column_name3 data_type constraint,
....
)

Example:

CREATE TABLE Customer


(

Customer_Id integer Primary key

First_Name char(50),
Last_Name char(50),
Address char(50),
City char(50),
Country char(25),
Birth_Date date

17
);

Alter Table

Alter command is used to:

1. Add a new column.

3. Modify the existing column definition.

3. To include or drop integrity constraint.

Syntax: alter table table_name add/modify (attribute data type (size));

Example:

1. Alter table customer add (phone_no char (20));

2. Alter table customer modify (phone_no number (10));

3. ALTER TABLE CUSTOMER ADD CONSTRAINT Pkey1 PRIMARY KEY (Customer_ID);

DROP TABLE

It will delete the table structure provided the table should be empty.

Example: drop table customer;

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.

Syntax: TRUNCATE TABLE <TABLE NAME>;

Example: Truncate table customer;

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:

CREATE TABLE Customer


(

SID integer NOT NULL,


Last_Name char (30) NOT NULL,
First_Name char (30)

);

Columns "SID" and "Last_Name" cannot include NULL, while "First_Name" can include NULL.

Alter table customer modify (First_Name not 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:

CREATE TABLE Customer


(

SID integer CHECK (SID > 0),


Last_Name char (30),
First_Name char (30)

);

Column "SID" has a constraint -- its value must only include integers greater than 0.

Alter table student add constraint b2 check (length (regno<=4));

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:

Unique key constraint:

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:

Create table cust(custid number(6) constraint uni unique, name char(10));

Alter table cust add(constraint c unique(custid));

PRIMARY KEY CONSTRAINT:

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

It enforces relationship between tables. To establish parent-child relationship between 2 tables


having a common column definition, we make use of this constraint. To implement this, we should
define the column in the parent table as primary key and same column in the child table as foreign key
referring to the corresponding parent entry.

Foreign key

A column or combination of column included in the definition of referential integrity, which would
refer to a referenced key.

Example:

Create table customer

20
(

SID int primary key,

Last_Name char (20),

First_Name char (20)

);

Create table orders

Order_ID integer primary key,


Order_Date date,
Customer_SID integer references CUSTOMER (SID),
Amount double

);

EXERCISE 5.1

Consider the following Employee and Department tables:

DID Dname Location


11 CS East
12 EE West
13 HBS East

EmpId Fname Lname Salary Date-of- D-O-B DID


joining
1 Ali Murtaza 30000 12-01-2012 20-01-1984 11
2 Omer Kashif 20000 15-06-2012 19-03-1985 11
3 Ayesha Asif 30000 14-02-2011 10-06-1976 13
4 Amna Bilal 25000 07-03-2010 28-03-1988 12

Create above tables in SQL with following constraints:

Constraint No 1: EmpId > 0 , DID > 0

21
Constraint No 2: Fname < 7 characters , Location < 6 characters

Constraint No 3: Salary > 0

22
Constraint No 4: EmpId PK , DID FK in employee table

Constraint No 5: DID pk in department table

Constraint No 6: DoB unique

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.

Inserting a single row into a table:

Syntax:
INSERT INTO table_name
VALUES (value1, value2, value3,...)

Example:
Insert into employee
Values (1,’ali’,3000,’01-12-2000);

Inserting multiple rows:

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;

The retrieval of specific columns from a table:

It retrieves the specified columns from the table

Syntax: Select column_name1, …..,column_namen from table name;

Example: Select empno, empname from emp;

Elimination of duplicates from the select clause:

It prevents retriving the duplicated values .Distinct keyword is to be used.

Syntax: Select DISTINCT col1, col2 from table name;

Example: Select DISTINCT job from emp;

Select command with where clause:

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;

Example: Select empno, empname from emp where sal>4000;

Select command with order by clause:

Syntax: Select column_name1, …..,column_namen from table name where condition order by
colmnname;

Example: Select empno, empname from emp order by empno;

Select command to create a table:


26
Syntax: create table tablename as select * from existing_tablename;

Example: create table emp1 as select * from emp;

Select command to insert records:

Syntax: insert into table_name (select columns from existing_table_name);

Example: insert into emp1 (select * from emp);

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.

Syntax: update table_name set field=values where condition;

Example: Update emp set sal = 10000 where empno=135;

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.

Syntax: Delete from table where conditions;

Example: delete from emp where empno=135;

EXERCISE 6.1:

Write the following queries for above table:

Q1. List out the details of Ali

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

Q4. List out employee’s name who is working in department 10 or 20

Q5. List out employees name whose name start with ‘a’

Q6. List out employee id last name in ascending order based on employee id

Web Resources for Additional Studies


http://www.1keydata.com/
http://www.w3schools.com/

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.

Example: Select max(percentage), deptname from student group by deptname;

Having clause

This is used to specify conditions on rows retrieved by using group by clause

Example: Select max(percentage), deptname from student group by deptname having

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

1. Subqueries that return several values

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

Write the following SQL queries:

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

Q3. List department details where at least 2 employees are working.

Q4. Display the department id, having greater than or equal to 3 employees joined in April 1985

EXERCISE 7.2:

Write the following SQL Queries using subqueries.

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

Web Resources for Additional Studies


http://www.1keydata.com/
http://www.w3schools.com/

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)
);

Insert into studentMarks


values (1,'DB',7,8,22,39),(2,'DS',8,7,21,35),(3,'OOP',6,5,20,40)

Select * from studentMarks

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.

Cascade updates and Deletes to related tables:


In most cases we use stored procedures to update or delete rows from related tables.
But, you can also cascade the actions using foreign key constraints. This is generally not
used due to the fact that it is transparent, and leads to *mysterious* results. Let’s see
how it works.

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.

EXERCISE 8.1 : CLASS ACTIVITY

CREATE TABLE Albums


(
      AlbumID     INT   PRIMARY KEY,
      Name        VARCHAR(50)
)
 
CREATE TABLE Tracks
(
      TrackID     INT   PRIMARY KEY,
      Title       VARCHAR(50),
      AlbumID     INT   REFERENCES Albums(AlbumID)
                        ON DELETE SET NULL
                        ON UPDATE CASCADE,
     Duration    TIME(0)
)

• In the above example, AlbumID in Tracks references AlbumID in Albums. There


are two cascading actions specified here.
• ON DELETE SET NULL = When a row is deleted from Albums, AlbumID will be
set to NULL for all matching rows in Tracks.
• ON UPDATE CASCADE = When AlbumID is updated in Albums, all matching rows
in Tracks will also have the updated AlbumID.

Now, let’s try and update an AlbumID in dbo.Albums:


• UPDATE      Albums
• SET         AlbumID = 2
• WHERE       AlbumID = 4

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.

For delete also it works in the same way:


• DELETE FROM Albums
• WHERE AlbumID = 1

37
LAB 9 – CASE STUDY

OBJECTIVE:
To implement the concepts of relational databases in MS SQL.

LIBRARY MANAGEMENT SYSTEM

Consider the operation of a Library.

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

BOOK SERIAL NO BOOK NAME


BOOK_1200 Introduction to Programming
AUITHOR/ AUTHORS BLOCK INDEX SHELF INDEX
Deitel n Deietel, Rogger Pressman BLK_3 SHELF_15
ISSUED TO ISSUE DUE RETURN ISSUED BY (STAFF ID)
(MEMBER ID) DATE DATE DATE
MEMBER_1011 3rd JAN 30th STAFF_1111
2015 JAN
2015

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

MEMBER ID MEMBER NAME


MEMBER_1011 ABC
CONTACT NO 03xx-xxxxxxxx MEMBERSHIP DATE 3rd December 2014
BOOK ISSUE DUE RETURN LATE FINE ISSUED BY
SERIAL NO DATE DATE DATE (STAFF ID)
BOOK_1200 4th 30 30 none STAFF_1111
December Decembe December
2014 r 2014 2014
BOOK_1200 3rd JAN 30th JAN STAFF_1222
2015 2015

LIST OF BOOKS IN LIBRARY

BOOK BOOK NAME AUTHORS BLOCK NUMBER SHELF


SERIAL NO NUMBER
BOOK_1200 Intro to Deitel n Deietel, BLK_3 SHELF_15
programmin Rogger Pressman
g
BOOK_1300 Software Rogger Pressman BLK_2 SHELF_20
Engineering
BOOK_1302 Computer William Stalling BLK_2 SHELF_15
Architecture

EXERCISE 9.1:

1. Write down the name of entities you think are required.

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

Why we need joins?


Write a query to display the employee names along with their department names.
Output should be like:
Department name Employee name

PROGRAMS

SQL Join Algorithms

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)}

Example query of cross join


• SELECT *
• FROM employee
• CROSS JOIN department;

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.

Example query of inner join


• SELECT *
• FROM employee
• INNER JOIN department
• ON employee.DepartmentID = department.DepartmentID;

Some more types of join

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

Outer Join(Left, Right, Full)

Outer join gives results by taking:


• Cartesian product
• filter (join predicate)
• get outer rows

Left Outer join


In a left outer join, all rows from the first table mentioned in the SQL query is selected,
regardless whether there is a matching row on the second table mentioned in the SQL
query.

Example Query Left Outer Join

44
SELECT * FROM employee LEFT OUTER JOIN department ON employee.DepartmentID
= department.DepartmentID;

Right outer join


In an left outer join, all rows from the second table mentioned in the SQL query is
selected, regardless whether there is a matching row on the first table mentioned in the
SQL query.

Right Outer Join Example Query


SELECT * FROM employee RIGHT OUTER JOIN department ON employee.DepartmentID
= department.DepartmentID;

Full Outer Join


This join combines left outer join and right outer join. It returns row from either table
when the conditions are met and returns null value when there is no match.

Full Outer Join Example Query


SELECT * FROM employee FULL 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

Web Resources for Additional Studies


http://www.1keydata.com/
http://www.w3schools.com/

EXCERCISE 10.1:

46
Write the following SQL queries:

1. List out employees with their manager names.

2. How many employees who are working in different departments and display
with department name.

3. Display employee details with all departments.

4. Display employees with their designations.

5. Which is the department having greater than or equal to 5 employees and


display the department names in ascending order?

47
6. Display all employees in sales or operation departments.

7. Display employees with their designations.

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

A procedure is a block that can take parameters (sometimes referred to as arguments)


and be invoked.

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.

Modularized program development:

· Group logically related statements within blocks.

· Nest sub-blocks inside larger blocks to build powerful programs.

· Break down a complex problem into a set of manageable well defined logical modules
and implement the modules with blocks.

Pre-compiled execution plan:

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

Syntax for procedure: Create [or Replace] PROCEDURE procedur_name

49
(parameter1 [model1] datatype1,

(parameter2 [model2] datatype2,

…)

AS

PL/SQL Block;

Example:

Create PROCEDURE leave_emp

(@v_id int)

AS

BEGIN

DELETE FROm emp

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:

• DECLARE @var int


• Set @var = 1
• Select @var
Control flow constructs

• 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

Output parameter example

Web Resources for Additional Studies


http://www.1keydata.com/
http://www.w3schools.com/

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

A trigger is a PL/SQL block or a PL/SQL procedure that executes implicitly whenever a


particular event takes place. It can either be:

1. Application trigger: Fires whenever an event occurs with a particular application.

2. Database Trigger: Fires whenever a data event (such as DML) occurs on a schema or
database.

• Triggers are special type of stored procedures.


• Automatically executes when DDL and DML statements associated with triggers
executes.

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

ALTER TRIGGER [dbo].[CDRTOBILL] ON [dbo].[CDR]


FOR INSERT
AS

DECLARE @nDFR numeric(13)


DECLARE @nDTO numeric(13)
DECLARE @nCOST FLOAT(9)
DECLARE @dDAT CHAR(50)

SELECT @nDFR = [CDR_D_FR] FROM INSERTED


SELECT @nDTO = [CDR_D_TO] FROM INSERTED
SELECT @nCOST = [CDR_COST] FROM INSERTED
SELECT @dDAT = [CDR_DATE] FROM INSERTED

//if entry already present update

IF (SELECT BILL_MONTH FROM BILLS WHERE BILL_PH_NO=@nDFR AND


BILL_MONTH = MONTH(@dDAT) AND BILL_YEAR=YEAR(@dDAT) ) = MONTH(@dDAT)
BEGIN

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.

Web Resources for Additional Studies


http://www.1keydata.com/
http://www.w3schools.com/

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.

A row locator’s structure depends on whether it points to a clustered table or to a heap.


If referencing a clustered table, the row locator points to the clustered index, using the
value from the clustered index to navigate to the correct data row. If referencing a heap,
the row locator points to the actual data row.

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

In addition to an index being clustered or nonclustered, it can be configured in other


ways:

 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 Index syntax

CREATE UNIQUE CLUSTERED INDEX <index name> ON <table name>(<column


name>)

create unique clustered index idxclu on contact(contact_id)


select * from contact where contact_id =10

CREATE NONCLUSTERED INDEX <index name> ON <table name>(<column


name>)

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)

Force our query to use the index


SELECT * FROM contact WITH(INDEX(idxnon)) WHERE last_name = 'adam'

drop index contact.idxclu

Lab# 12 EXCERCISE

Q1: write SQL query to create clustered index on employee table.

Q2: write SQL query to create non-clustered index on employee table.

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.

Limitations and Restrictions

A view can be created only in the current database.

A view can have a maximum of 1,024 columns.

Create Views

CREATE VIEW HumanResources.EmployeeHireDate


AS
SELECT p.FirstName, p.LastName, e.HireDate
FROM HumanResources.Employee AS e JOIN Person.Person AS p
ON e.BusinessEntityID = p.BusinessEntityID ;

-- Query the view


SELECT FirstName, LastName, HireDate
FROM HumanResources.EmployeeHireDate
ORDER BY LastName;

Modify the view by adding a WHERE clause to limit the rows returned.

ALTER VIEW HumanResources.EmployeeHireDate


AS
SELECT p.FirstName, p.LastName, e.HireDate
FROM HumanResources.Employee AS e JOIN Person.Person AS p
ON e.BusinessEntityID = p.BusinessEntityID
WHERE HireDate < CONVERT(DATETIME,'20020101',101) ;

Modify Data Through a View

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:

o An aggregate function: AVG, COUNT, SUM, MIN, MAX, GROUPING, STDEV,


STDEVP, VAR, and VARP.

o A computation. The column cannot be computed from an expression that


uses other columns. Columns that are formed by using the set operators
UNION, UNION ALL, CROSSJOIN, EXCEPT, and INTERSECT amount to a
computation and are also not updatable.

 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';

INSERT INTO VIEW_NAME (COL1, COL2)


VALUES ('MyDepartment', 'MyGroup');

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.

DROP VIEW HumanResources.EmployeeHireDate;

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.

Working with Data in .NET Framework

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

The namespace we're going to use is, System.Data.SqlClient.

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;

Connecting to a database and execute SQL command

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. 

SqlConnection myConnection = new SqlConnection("user id=username;" +

"password=password;server=serverurl;" +
"Trusted_Connection=yes;" +
"database=database; " +
"connection timeout=30");
myConnection.Open(); // open connection for the connections string

SqlCommand myCommand = new SqlCommand("Command String", myConnection);


myCommand.ExecuteNonQuery(); // EXECUTES THE COMMAND
myConnection.Close(); // CLOSES THE CONNECTION

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

SqlCommand myCommand= new SqlCommand("INSERT INTO table (Column1,


Column2) "
+
"Values ('string', 1)", myConnection);

myCommand.ExecuteNonQuery(); // EXECUTES THE COMMAND

myConnection.Close(); // CLOSES THE CONNECTION

EXAMPLE 2:

private void search_ID()


{
DataTable dt = new DataTable();
SqlConnection sqlConnection = new SqlConnection();

string cmdText = "";

cmdText = "SELECT * FROM SUBJECTINFO WHERE ID like '%H%'";

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();
}
}

EXERCISE 15.1: CLASS ACTIVITY

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

You might also like