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

FDM Manual

This document is a laboratory manual for a database fundamentals course. It provides instructions on installing and connecting to Microsoft SQL Server. It then covers topics like data definition language, creating and modifying databases and tables, adding constraints, and manipulating data using data manipulation and retrieval languages. The lab experiments provide hands-on practice in skills like creating a database called "university", modifying it to be called "MAU_university", and deleting the database. Overall, the document serves as a guide for students to gain practical skills in key database concepts.

Uploaded by

Abera Brhanu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
80 views

FDM Manual

This document is a laboratory manual for a database fundamentals course. It provides instructions on installing and connecting to Microsoft SQL Server. It then covers topics like data definition language, creating and modifying databases and tables, adding constraints, and manipulating data using data manipulation and retrieval languages. The lab experiments provide hands-on practice in skills like creating a database called "university", modifying it to be called "MAU_university", and deleting the database. Overall, the document serves as a guide for students to gain practical skills in key database concepts.

Uploaded by

Abera Brhanu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

MEKDELA AMBA UNIVERSITY

Collage of Natural and computational science

DEPARTEMENT OF COMPUTER SCINCE

Laboratory Manual

for

Fundamentals of Database

Prepared by: Abera Brhanu (BSc.)


Contents

Table of Contents
Session 1: introduction to database and Generally laboratory instruction .................................... 1
Installing SQL Server software ............................................................................................................. 2
opening and connecting Microsoft SQL server .................................................................................. 7
Session 2 Data Definition language ......................................................................................................... 7
CREATING, MODIFYING AND Dropping DATABASES ............................................................... 8
LAB EXPERIMENTS 1 ....................................................................................................................... 11
Session 3 DATA DEFINITION, CONSTRAINTS, AND SCHEMA CHANGES.............................. 11
CREATING, MODIFYING AND DELETING TABLES .............................................................. 12
LAB EXPERIMENTS 2 ....................................................................................................................... 14
Session 3 DATA MANIPULATION LANGUAGE (DML) .................................................................. 15
INSERT UPDATE DELETE TABLES .............................................................................................. 15
Session 4 DATA RETRIEVAL LANGUAGE (DRL) .............................................................................. 17
Retrieve data from one or more tables. .............................................................................................. 17
Implementation of different types of operators in SQL. .................................................................. 18
Session 5 join index and view ................................................................................................................. 20
Joins ........................................................................................................................................................ 20
INDEXING ............................................................................................................................................. 21
VIEW ...................................................................................................................................................... 21

Prepared by: Abera Brhanu (BSc.) ii


Session 1: introduction to database and Generally laboratory
instruction
A. Introduction to database

This is a laboratory manual for the course Fundamentals of Database.

The content is organized into lessons corresponding to the lecture content outlined on the
curriculum. And the code in this manual is written (edited), debug and Execute using Microsoft
SQL server.
Database: a collection of Logical related data.it is a collection of table

Database Management Systems (DBMS): a computerized system that system enables user to
create and maintain a database.

The DBMS is a general-purpose software system that facilitate of defining, constructing and
sharing database users and applications.

DBMS Software
❖ Microsoft access
❖ Oracle
❖ PostgreSQL
❖ Dbase
❖ SQLite
❖ IBM DB2
❖ Maria DB
❖ Microsoft SQL server
❖ My SQL

In this manual we use software is Microsoft SQL Server

As a final notice, this manual is now ready to be given to the trainees (students) to help them
acquire the necessary skills and understandings, and then lead them to the level that they

Prepared by: Abera Brhanu (BSc.) 1


would produce software-based solutions to the miscellaneous societal problems we have
today!
B. Generally, laboratory instruction

Installing SQL Server software


1. Run Setup.Exe to start the setup of SQL Server Software install, if prompted, click Yes to
allow this app to make changes to your device.

2. Once the SQL Server Installation Center launches choose Installation tab (second from the
right).

3. In most cases you will want to run a New SQL Server New SQL Server stand-alone
installation, but other options are available, for example if you have SQL Server 2014 installed,
you have an option to update.

Step 1: New SQL stand-alone installation

Prepared by: Abera Brhanu (BSc.) 2


Step 2 : License Terms

Step 3: Install Rules

Step 4: Feature Selection

Prepared by: Abera Brhanu (BSc.) 3


Step 5: Instance Configuration

Otherwise

Prepared by: Abera Brhanu (BSc.) 4


Step 6: Server Configuration

Prepared by: Abera Brhanu (BSc.) 5


Step 7: Database Engine Configuration

Step 8: Complete

Prepared by: Abera Brhanu (BSc.) 6


opening and connecting Microsoft SQL server
To open SQL SSMS, use the following steps:

In window 7

1. Start All Programs Microsoft SQL server SQL Server Management Studio.
Other way in window 10
2. Start All apps Microsoft SQL server SQL Server Management Studio.

Click on Connect to your default instance as shown in the following figure

Fig 1 connecting SQL server

Session 2 Data Definition language


✓ Used to define the database structure or Schema
✓ Allows the designers to specify datatype, structures and constraints on the datatype to be
stored in the database

Prepared by: Abera Brhanu (BSc.) 7


CREATING, MODIFYING AND Dropping DATABASES
CREATING A DATABASE IN GRAPHICAL USER INTERFACE

1. Start SQL Server Management Studio by selecting Start Programs Microsoft


SQL server 2012 Management Studio.
2. Click on Connect to your default instance of SQL Server as in Figure 1.1
3. Open Query editor window
4. Expand your Databases folder.

5. Right-click either the Databases folder in the console tree or the white space in the right
pane, and choose New Database from the context menu.
6. You should now see the General tab of the Database properties sheet. Enter the
database name, and leave the owner as <default>.

Fig 2.1 opening new Query editor window

Prepared by: Abera Brhanu (BSc.) 8


Fig 2.2 create New database

CREATING A DATABASE IN TRANSACT SQL STATEMENT(T-SQL)

1. Start SQL Server Management Studio by selecting Start Programs Microsoft


SQL server 2012 Management Studio.
2. Click on Connect to your default instance of SQL Server as in Figure 1.1
3. Open Query editor window as in Figure 2.1
4. Write the database creation statement
5. Execute the statement

Syntax: CREATE DATABASE database_name

database_name Is the name of the new database. Database names must be unique within an
instance of SQL Server

For example, to create a database with name ‘University, we write the following statement:

CREATE DATABASE University

1. Expand your database Right Click on Tables and specify columns with their data
types

Prepared by: Abera Brhanu (BSc.) 9


2.Enter database name Fig 2.3 create database by GUI

Syntax: create database database_name

CREATE DATABASE MAU_University

Fig 2.4 create database by T-SQL

MODIFYING A DATABASE

Syntax: create database database_name

ALTER DATABASE student MODIFY FILE (NAME = N'test', FILEGROWTH = 2048KB)

Alter database database_name modify file (name=’new name’ filegrowth=2048 kb

Prepared by: Abera Brhanu (BSc.) 10


Dropping A DATABASE

We can drop a database either by right clicking the database and pressing Delete on the
context menu or using the following Drop

Syntax: DROP DATABASE <databaseName>

Example: DROP DATABASE Mau_university

LAB EXPERIMENTS 1
Question

1. Create database called “university”.


2. modify the database “university” into “MAU_university”
3. delete database “MAU_university”

Solution

1. create database UNIVERSITY


2. create schema school
3. ALTER DATABASE UNIVERSITY
MODIFY NAME =MAU_UNIVERSITY;
---- Other method Rename Data and Log Files
Alter Database UNIVERSITY
MODIFY FILE (
NAME='UNIVERSITY1',
NEWNAME='MAU_UNIVERSITY'
);
4. DROP DATABASE MAU_UNIVERSITY

Session 3 DATA DEFINITION, CONSTRAINTS, AND SCHEMA


CHANGES

Prepared by: Abera Brhanu (BSc.) 11


CREATING, MODIFYING AND DELETING TABLES
table…………………………………….……relation

row……………………………………...……. tuple

column………………………………….……attribute

DATA TYPES

• Numeric: NUMBER, NUMBER(s,p), INTEGER, INT, FLOAT, DECIMAL


• Character: CHAR(n), VARCHAR(n), VARCHAR2(n), CHAR
VARYING(n)
• Boolean: true, false, and null
• Date and Time: DATE (YYYY-MM-DD) TIME( HH:MM:SS)
• Timestamp: DATE + TIME
• USER Defined types
1. CHAR (Size): This data type is used to store character strings values of fixed length. The
size in brackets determines the number of characters the cell can hold. The maximum
number of character is 255 characters.

2. VARCHAR (Size) / VARCHAR2 (Size): This data type is used to store variable length
alphanumeric data. The maximum character can hold is 2000 character.

3. NUMBER (P, S): The NUMBER data type is used to store number (fixed or floating
point).

4. DATE: This data type is used to represent date and time

CREATE SCHEMA

Specifies a new database schema by giving it a name

Prepared by: Abera Brhanu (BSc.) 12


Syntax: create schema Schema_Name

CREATE TABLE

Specifies a new data base relation by giving it a name, and specifying each of its
attributes and their data types

Syntax of CREATE Command:

CREATE TABLE <table name> ( <Attribute A1> <Data Type D1> [<
Constraints>], <Attribute A2> <Data Type D2> [< Constraints>], …….

<Attribute An> <Data Type Dn> [< Constraints>]);

DROP TABLE

• Used to remove a relation (base table) and its definition.


• The relation can no longer be used in queries, updates, or any other commands since its
description no longer exists

Syntax: DROP TABLE tabl_name;

DROP A COLUMN AN ATTRIBUTE

Syntax: DROP TABLE tabl_name DROP COLUMN COLUMN_NAME

Example: alter table grade_report drop column result

ALTER TABLE

• Used to add an attribute to/from one of the base relations drop constraint -- The new
attribute will have NULLs in all the tuples of the relation right after the command is
executed; hence, the NOT NULL constraint is not allowed for such an attribute.

Syntax: ALTER TABLE tabl_name ADD COLUMN_NAME DATATYPE (SAIZE);

• The database users must still enter a value for the new attribute JOB for each
EMPLOYEE tuple.
This can be done using the UPDATE command.

Prepared by: Abera Brhanu (BSc.) 13


LAB EXPERIMENTS 2
1. create schema called “School” under this database.
2. create “department, student, course, Section, Gred_Report, prerequisite”
table inside “school” schema under “university” database based on a given
bellow in each table data

Solution
1. create schema school
2. Create table
2.1. Department table
create table school.departement(Did char(8) primary key not null,

Dname varchar(30) unique not null,Dlocation varchar(30));


2.2. Student table
create table student(Sid char(10) primary key not null,Fname varchar(30) not null,
Lname varchar(30)not null,
sex char(1) default 'f' check(sex='f' or sex='m'),
--check(sex in('f' or 'm'))
Year_ofstudy int not null,Dbirth date,age as datediff(year,Dbirth,getdate()),
--as year(getdat())-year(Dbirth)
sem_payment decimal(6,2),
paid as case when(sem_payment is not null)then 'yes'
when(sem_payment is null)then 'no'end,

Prepared by: Abera Brhanu (BSc.) 14


Did char(8) foreign key references school.departement(Did));

2.3. Course table


create table course(Cno char (10) primary key not null,
Cname varchar (20) unique not null,Chour int check (Chour>=2 and Chour <=4),
Did char(8) foreign key references school.departement(Did));

2.4. Section table


create table section(section_id int identity(10,1) primary key not null,
Cno char(10) not null foreign key references course(Cno),semester char(4) not null ,
acadamic_year int check(acadamic_year >=2015 and acadamic_year <=2018)default
year(getdate()),
instructur varchar(10));

Session 3 DATA MANIPULATION LANGUAGE (DML)


The Data Manipulation Language (DML) is used to retrieve, insert and modify database
information. These commands will be used by all database users during the routine
operation of the database. Let's take a brief look at the basic DML commands:

INSERT UPDATE DELETE TABLES


1. INSERT INTO: This is used to add records into a relation. These are three type of INSERT
INTO queries which are as

a) Inserting a single record

Syntax: INSERT INTO < table name> (field_1,field_2……field_n)VALUES

(data_1,data_2,........data_n);

Example: insert into school.departement(Did,Dname,Dlocation)


values('d01','Cscince','ethiopia');

Prepared by: Abera Brhanu (BSc.) 15


b) Inserting a single record

Syntax: INSERT INTO < table name>VALUES (data_1,data_2,........data_n); Example:

insert into school.departement values('d01','Cscince','ethiopia');

c) Inserting all records from another relation

Syntax: INSERT INTO relation_name_1 SELECT Field_1,field_2,field_n FROM


relation_name_2 WHERE field_x=data;

Example: insert into school.departement SELECT Dname,Dlocation FROM department


WHERE NAME=’Almaz’;

2.UPDATE-SET-WHERE: This is used to update the content of a record in a relation.

Syntax: UPDATE table_name SET column_name1=data,column_name2=data, WHERE


column_name=data;

Example: UPDATE student SET sname = ‘Almaz’ WHERE sno=1;

3. DELETE-FROM: This is used to delete all the records of a relation but it will
retain the structure of that relation.

a) DELETE-FROM: This is used to delete all the records of relation.

Syntax: SQL>DELETE FROM table_name;

Example: delete from student


b) DELETE -FROM-WHERE: This is used to delete a selecte record from a relation.

Syntax: DELETE FROM relation_name WHERE condition;

Example: delete from student where sno=14


4.TRUNCATE: This command will remove the data permanently. But structure will not be
removed.

Difference between Truncate & Delete:-

Prepared by: Abera Brhanu (BSc.) 16


• By using truncate command data will be removed permanently & will not get back where
as by using delete command data will be removed temporally & get back by using roll
back command.
• By using delete command data will be removed based on the condition where as by
using truncate command there is no condition.
• Truncate is a DDL command & delete is a DML command.

Syntax: TRUNCATE TABLE <Table name>

Example : TRUNCATE TABLE STUDENT

Session 4 DATA RETRIEVAL LANGUAGE (DRL)


Retrieve data from one or more tables.
1. SELECT FROM: To display all fields for all records.

Syntax : SELECT * FROM relation_name;

Example : select *from student

2. SELECT FROM: To display a set of fields for all records of relation.

Syntax: SELECT a set of fields FROM relation_name;

Example: select FNAME,LNAME from student


3. SELECT - FROM -WHERE: This query is used to display a selected set of
fields for a selected set of records of a relation.

Syntax: SELECT a set of fields FROM relation_name WHERE condition;

Example: select * from student WHERE SNO=15

Prepared by: Abera Brhanu (BSc.) 17


Implementation of different types of operators in SQL.
✓ Arithmetic Operator
✓ Logical Operator
✓ Comparison Operator
✓ Special Operator
✓ Set Operator

❖ ARIHMETIC OPERATORS:
(+): Addition - Adds values on either side of the operator.
(-): Subtraction - Subtracts right hand operand from left hand operand.
(*): Multiplication - Multiplies values on either side of the operator.
(/): Division - Divides left hand operand by right hand operand.
(^): Power- raise to power of.
(%): Modulus - Divides left hand operand by right hand operand and returns remainder.
❖ LOGICAL OPERATORS:
AND: The AND operator allows the existence of multiple conditions in an SQL statement's
WHERE clause.
OR: The OR operator is used to combine multiple conditions in an SQL statement's WHERE
clause.
NOT: The NOT operator reverses the meaning of the logical operator with which it is used.
Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.
❖ COMPARISION OPERATORS:
(=): Checks if the values of two operands are equal or not, if yes then condition becomes true.
(! =): Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true.
(< >): Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true.
(>): Checks if the value of left operand is greater than the value of right operand, if yes then
condition becomes true

Prepared by: Abera Brhanu (BSc.) 18


(<): Checks if the value of left operand is less than the value of right operand, if yes then
condition becomes true.
(>=): Checks if the value of left operand is greater than or equal to the value of right operand, if
yes then condition becomes true.
(<=): Checks if the value of left operand is less than or equal to the value of right operand, if yes
then condition becomes true.

SPECIAL OPERATOR:
BETWEEN: The BETWEEN operator is used to search for values that are within a set of
values, given the minimum value and the maximum value.
IS NULL: The NULL operator is used to compare a value with a NULL attribute value.
ALL: The ALL operator is used to compare a value to all values in another value set
ANY: The ANY operator is used to compare a value to any applicable value in the list according
to the condition.
LIKE: The LIKE operator is used to compare a value to similar values using wildcard operators.
It allows to use percent sign (%) and underscore (_) to match a given string pattern.
IN: The in operator is used to compare a value to a list of literal values that have been specified.
EXIST: The EXISTS operator is used to search for the presence of a row in a specified table that
meets certain criteria.
SET OPERATORS:
The Set operator combines the result of 2 queries into a single result. The following are the
operators:
• Union
• Union all
• Intersect
• Minus
Union: Returns all distinct rows selected by both the queries
Union all: Returns all rows selected by either query including the duplicates.
Intersect: Returns rows selected that are common to both queries.
Minus: Returns all distinct rows selected by the first query and are not by the second

Prepared by: Abera Brhanu (BSc.) 19


Session 5 join index and view
Joins
Joins is used to combine records from two or more tables in a
database. A JOIN is a means for combining fields from two tables by using values common
to each.The join is actually performed by the ‘where’ clause which combines specified rows
of tables.
Syntax:
SELECT column 1, column 2, column 3...
FROM table_name1, table_name2
WHERE table_name1.column name = table_name2.columnname;
They are deferent types of Joins
➢ Simple Join
➢ Self-Join
➢ Outer join
Simple Join:
It is the most common type of join. It retrieves the rows from 2 tables having a
common column and is further classified into
Equi-join:
A join, which is based on equalities, is called equi-join.
Example:
Select * from item, cust where item.id=cust.id;
In the above statement, item-id = cust-id performs the join statement. It retrieves rows
from both the tables provided they both have the same id as specified by the where clause.
Since the where clause uses the comparison operator (=) to perform a join, it is said to be
equijoin. It combines the matched rows of tables. It can be used as follows:
• To insert records in the target table.
• To create tables and insert records in this table.
• To update records in the target table.
• To create views.
Non Equi-join:
It specifies the relationship between columns belonging to different tables by
making use of relational operators other than’=’.
Example:
Select * from item, cust where item.id<cust.id;
Table Aliases
Table aliases are used to make multiple table queries shorted and more readable. We give
an alias name to the table in the ‘from’ clause and use it instead of the name throughout
the query.
Self join:
Joining of a table to itself is known as self-join. It joins one row in a table to another.
It can compare each row of the table to itself and also with other rows of the same table.
Example:
select * from emp x ,emp y where x.salary >= (select avg(salary) from x.emp

Prepared by: Abera Brhanu (BSc.) 20


where x. deptno =y.deptno);
Outer Join:
It extends the result of a simple join. An outer join returns all the rows returned by simple
join as well as those rows from one table that do not match any row from the table. The
symbol(+) represents outer join.
– Left outer join
– Right outer join
– Full outer join
INDEXING
INDEXING: An index is an ordered set of pointers to the data in a table. It is based on
the data values in one or more columns of the table. SQL Base stores indexes separately
from tables.
An index provides two benefits:
It improves performance because it makes data access faster.
It ensures uniqueness. A table with a unique index cannot have two rows with
the same values in the column or columns that form the index key.
Syntax:
CREATE INDEX <index_name> on <table_name> (attrib1,attrib 2….attrib n);
Example:
CREATE INDEX id1 on emp(empno,dept_no);

VIEW
VIEW: In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as
if the data were coming from one single table.
A view is a virtual table, which consists of a set of columns from one or more tables. It is
similar to a table but it does not store in the database. View is a query stored as an object.
Syntax: CREATE VIEW <view_name> AS SELECT <set of fields>
FROM relation_name WHERE (Condition)
Example:
SQL> CREATE VIEW employee AS SELECT empno,ename,job FROM EMP
WHERE job = ‘clerk’;
SQL> View created.
Example:
CREATE VIEW [Current Product List] AS
SELECT ProductID, ProductName
FROM Products
WHERE Discontinued=No;
UPDATING A VIEW : A view can updated by using the following syntax :
Syntax : CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name

Prepared by: Abera Brhanu (BSc.) 21


WHERE condition
DROPPING A VIEW: A view can deleted with the DROP VIEW command.
Syntax: DROP VIEW <view_name> ;

Prepared by: Abera Brhanu (BSc.) 22

You might also like