100% found this document useful (1 vote)
70 views

LMS-DBMS Lab Manual

The document describes an experiment on creating an entity-relationship (ER) diagram for a pharmacy database. The ER diagram models patients, doctors, pharmaceutical companies, drugs, pharmacies, prescriptions, and their relationships. Constraints like each patient having a primary doctor, doctors prescribing drugs to patients, pharmacies selling drugs and contracting with pharmaceutical companies, and supervisors for contracts are defined. The goal of the experiment is to draw the ER diagram capturing this information and identify any constraints not shown in the diagram.

Uploaded by

JAYA GANESH
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
70 views

LMS-DBMS Lab Manual

The document describes an experiment on creating an entity-relationship (ER) diagram for a pharmacy database. The ER diagram models patients, doctors, pharmaceutical companies, drugs, pharmacies, prescriptions, and their relationships. Constraints like each patient having a primary doctor, doctors prescribing drugs to patients, pharmacies selling drugs and contracting with pharmaceutical companies, and supervisors for contracts are defined. The goal of the experiment is to draw the ER diagram capturing this information and identify any constraints not shown in the diagram.

Uploaded by

JAYA GANESH
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

The ICFAI Foundation of Higher Education

(Declared as Deemed to be University u/s 3 of UGC Act 1956)

Faculty of Science and Technology, Hyderabad

CS 314 - DATABASE MANAGEMENT


SYSTEMS LAB MANUAL
for

III Year CSE


Department of Computer Science and Engineering

List of Experiments
S. No. Name of the Experiment
1
Introduction to SQL & MySQL and Database Design

Implementation of Data Definition Language Commands.


 CREATE
 ALTER
2
 DROP
 TRUNCATE
 RENAME
Implementation of Data Manipulation Language commands

3  INSERT
 UPDATE
 DELETE
Implementation of Constraints
 PRIMARY KEY
 FOREIGN KEY
 UNIQUE
4
 NULL
 NOT NULL
 DEFAULT
 CHECK
Implementation of different types of function
 NUMBER FUNCTION
5  AGGREGATE FUNCTION
 STRING FUNCTION
 DATE FUNCTION
Implementation of different types of operators .
 ARITHMETIC OPERATORS
 LOGICAL OPERATORS
6
 COMPARISON OPERATORS
 SPECIAL OPERATORS
 SET OPERATORS
Implementation of different types of Joins.
 INNER JOIN
7  OUTER JOIN
 NATURAL JOIN
 SELF JOIN
Implementation of GROUP BY, HAVING, ORDER BY
8 clause(s).

Implementation of Views and Indexes.


9
Implementation of Database Connectivity.
10

Exp : 1

Experiment Name ; Introduction to SQL & MySQL and Database Design

SQL (Structured Query Language):


Structured Query Language is a database computer language designed for managing data in
relational database management systems (RDBMS), and originally based upon Relational
Algebra. Its scope includes data query and update, schema creation and modification, and
data access control.

SQL language is sub-divided into several language elements, including:

 Clauses, which are in some cases optional, constituent components of statements and
queries.

 Expressions, which can produce either scalar values or tables consisting of columns
and rows of data.

 Queries which retrieve data based on specific criteria.

 Statements which may have a persistent effect on schemas and data, or which may
control transactions, program flow, connections, sessions, or diagnostics.

 SQL statements also include the semicolon (";") statement terminator. Though not
required on every platform, it is defined as a standard part of the SQL grammar.

 Insignificant white space is generally ignored in SQL statements and queries, making
it
 easier to format SQL code for readability.

There are five types of SQL statements. They are:

1. DATA DEFINITION LANGUAGE (DDL)


2. DATA MANIPULATION LANGUAGE (DML)
3. DATA RETRIEVAL LANGUAGE (DRL)
4. TRANSATIONAL CONTROL LANGUAGE (TCL)
5. DATA CONTROL LANGUAGE (DCL)

MySQL

MySQL is the widely used open source database. MySQL is the backend database of most of
the websites. As a Free Software(Free as in freedom), MySQL can be downloaded and used
by the developer for free.MySQL is robust and it provides excellent performance due to
usage of MyISAM. MySQL occupies very less disk space.MySQL can be easily installed in
all major operating systems like Microsoft Windows, Linux, UNIX. MySQL is best suited for
small and medium applications.

Before creating any tables, MySQL requires you to create a database by executing the
CREATE DATABASE command. To create a database called SaleCo you would type the
following:

mysql> CREATE DATABASE SaleCo;

Notice that you need a semi-colon to end the command.


To view the different databases created in that schema use the show database command.

mysql> SHOW databases;

A specific database has to be chosen to work upon. Databases objects created under one
database will not be available in the other. To choose a particular database use the below
command.

mysql> USE SaleCo;

In order to view the tables created under a specifc databases use the show table command.

mysql> SHOW TABLES;

Database Design :

A database model is a type of data model that determines the logical structure of
adatabase and fundamentally determines in which manner data can be stored, organized and
manipulated. The most popular example of a database model is the relational model, which
uses a table-based format.

Logical database design is the process of deciding how to arrange the attributes of the
entities in a given business environment into database structures, such as the tables of a
relational database. The goal of logical database design is to create well structured tables that
properly reflect the company's business environment. The tables will be able to store data
about the company's entities in a non-redundant manner and foreign keys will be placed in
the tables so that all the relationships among the entities will be supported.

An entity-relationship model (ERM) is a theoretical and conceptual way of showing data


relationships in software development. ERM is a database modeling technique that generates
an abstract diagram or visual representation of a system's data that can be helpful in designing
a relational database.
Example

Consider the Insurance Database given below. The primary keys are underlined and the
datatypes are specified.

PERSON (driver_id: string, name : string, address : string)


CAR ( regno: string, model : string, year: int)
ACCIDENT ( report-number :int, acc_date :date, locations: string)
OWNS(driver_id :string, reg_no: string)
PARTICIPATED(driver_id : string, regno :string, report_number: int , damage_amt :int)

Sample ER diagram

REGNO MODEL YEAR

CAR

NAME OW
NS

ADDRESS
PERSON

DRIVER_I
mak
es

ACCIDENT

REPORT_N DATE LOCATION


Experiment:1 ER DIAGRAM Date: 12.8.2021

The Prescriptions-R-X chain of pharmacies has offered to give you a Free lifetime supply of
medicines if you design its database. Given the rising cost of health care, you agree.
Here's the information that you gather:
 Patients are identified by an SSN, and their names, addresses, and ages must be
recorded.
 Doctors are identified by an SSN. For each doctor, the name, specialty, and years of
experience must be recorded.
 Each pharmaceutical company is identified by name and has a phone number. For
each drug, the trade name and formula must be recorded.
 Each drug is sold by a given pharmaceutical company, and the trade name identifies a
drug uniquely from among the products of that company. If a pharmaceutical
company is deleted, you need not keep track of its products any longer.
 Each pharmacy has a name, address, and phone number.
 Every patient has a primary physician. Every doctor has at least one patient.
 Each pharmacy sells several drugs and has a price for each. A drug could be sold at
several pharmacies, and the price could vary from one pharmacy to another.
 Doctors prescribe drugs for patients. A doctor could prescribe one or more drugs for
several patients, and a patient could obtain prescriptions from several doctors.
 Each prescription has a date and a quantity associated with it. You can assume that if
a doctor prescribes the same drug for the same patient more than once, only the last
such prescription needs to be stored.
 Pharmaceutical companies have long-term contracts with pharmacies. A
pharmaceutical company can contract with several pharmacies, and a pharmacy can
contract with several pharmaceutical companies. For each contract, you have to store
a start date, an end date, and the text of the contract.
 Pharmacies appoint a supervisor for each contract. There must always be a supervisor
for each contract, but the contract supervisor can change over the lifetime of the
contract.
 Draw an ER diagram that captures the above information. Identify any constraints that
are not captured by the ER diagram.
Experiment:2 ER Model to Relational Model Date: 17.8.2021

a. Translate the ER model given below to relational model.

b. Translate the ER model you have drawn in Experiment1 to a corresponding relational model.
Keep all your assumptions and make the translation.
Experiment : 3 DDL COMMANDS

The Data Definition Language (DDL) is used to create and destroy databases and database
objects. It simply deals with descriptions of the database schema and is used to create and
modify the structure of database objects in database..

Let's take a look at the structure and usage of four basic DDL commands:

1. CREATE
2. ALTER
3. DROP
4. RENAME
5. TRUNCATE

1. CREATE:

(a)CREATE TABLE: This is used to create a new relation (table)

Syntax:
CREATE TABLE <relation_name/table_name > (field_1 data_type(size),field_2
data_type(size), .. . );

Example:
SQL> CREATE TABLE Student (sno int, sname CHAR (10), class CHAR (5));

2. ALTER:

(a)ALTER TABLE ...ADD...:


This is used to add some extra fields into existing relation.

Syntax:
ALTER TABLE relation_name ADD (new field_1 data_type(size), new field_2
data_type(size),..);

Example:
SQL>ALTER TABLE std ADD (Address CHAR(10));

(b)ALTER TABLE...MODIFY...:
This is used to change the width as well as data type of fields of existing relations.

Syntax:

ALTER TABLE relation_name MODIFY (field_1 newdata_type(Size), field_2


newdata_type(Size),....field_newdata_type(Size));

Example:
SQL>ALTER TABLE student MODIFY(sname VARCHAR(10),class
VARCHAR(5));
c) ALTER TABLE..DROP...:
This is used to remove any field of existing relations.

Syntax:
ALTER TABLE relation_name DROP COLUMN (field_name);

Example:
SQL>ALTER TABLE student DROP column (sname);

d)ALTER TABLE..RENAME...:
This is used to change the name of fields in existing relations.

Syntax:
ALTER TABLE relation_name RENAME COLUMN (OLD field_name) to (NEW
field_name);

Example:
SQL>ALTER TABLE student RENAME COLUMN sname to stu_name;

3. DROP TABLE:
This is used to delete the structure of a relation. It permanently deletes the records in the table.

Syntax:
DROP TABLE relation_name;

Example:
SQL>DROP TABLE std;

4. RENAME:
It is used to modify the name of the existing database object.

Syntax:
RENAME TABLE old_relation_name TO new_relation_name;

Example:

SQL>RENAME TABLE std TO std1;

5.TRUNCATE:

It is used to remove all the records from the relations.

Syntax :
TRUNCATE TABLE relation_name;

Example:
mysql> TRUNCATE TABLE student;
LAB Exercise:

1. Create a table EMPLOYEE with following schema:

(S.No, Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name,Job_id , Salary)

2. Add a new column; HIREDATE to the existing relation.


3. Change the datatype of JOB_ID from char to varchar2.
4. Change the name of column/field Emp_no to E_no.
5. Modify the column width of the job field of emp table.
6. Remove the column S.No from the relation.
7. Change the table name EMPLOYEE to EMP_INFO.
8. Create a dummy table EMP like EMP_INFO table.
9. Test the truncate and drop command on EMP table.
Experiment : 4 DML COMMANDS

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:

1. INSERT table
2. UPDATE table
3. DELETE table
4. SELECT

1. INSERT

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 < relation/table name> (field_1,field_2……field_n)VALUES
(data_1,data_2,........data_n);
Example:
SQL>INSERT INTO student(sno,sname,class,address)VALUES
(1,’Ravi’,’M.Tech’,’Palakol’);

b) Inserting a multiple record


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

Example:
SQL>INSERT INTO student VALUES (1,’Ravi’,’M.Tech’,’Palakol’),
(2,’Mohan’,’M.Tech’,'Trichy'), (4,’Rio’,’MBA’,'Lucknow');

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:
SQL>INSERT INTO std SELECT sno,sname FROM student WHERE name = ‘Ramu‘;

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


Syntax:
SQL>UPDATE relation name SET Field_name1=data,field_name2=data, WHERE
field_name=data;

Example:
SQL>UPDATE student SET sname = ‘kumar’ 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.

Syntax:
SQL>DELETE FROM relation_name;

Example:
SQL>DELETE FROM std;

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

Syntax:
SQL>DELETE FROM relation_name WHERE condition;

Example:

SQL>DELETE FROM student WHERE sno = 2;

4. SELECT - To Retrieve data from one or more tables.To display all fields for all records.

Syntax :
SELECT * FROM relation_name;

Example :
SQL> select * from dept;

DEPTNO DNAME LOC


-------- ----------- ----------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

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:
SQL> select * FROM dept WHERE deptno<=20;

DEPTNO DNAME LOC


------ ----------- -----------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS

LAB PRACTICE ASSIGNMENT:

Create a table EMPLOYEE with following schema:

(Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name,Job_id , Salary)

Write SQL queries for following question:

1. Insert aleast 5 rows in the table.


2. Display all the information of EMP table.
3. Display the record of each employee who works in department D10.
4. Update the city of Emp_no-12 with current city as Nagpur.
5. Display the Employee Id and Employee Name who works in department MECH.
6. Delete the information of employee James.
7. Display the complete record of employees working in SALES Department.
8. Create a dummy table Emp and copy the records of EMPLOYEE table.
9. Create another dummy table Emp_Dum and copy only specific columns (Emp_no,
E_name,Job_id) of EMPLOYEE table.
Experiment No: 5 CONSTRAINTS

Constraints are used to specify rules for the data in a table. If there is any violation between
the constraint and the data action, the action is aborted by the constraint. It can be specified
when the table is created (using CREATE TABLE statement) or after the table is created
(using ALTER TABLE statement).

1. NOT NULL:
When a column is defined as NOTNULL, then that column becomes a mandatory column. It
implies that a value must be entered into the column if the record is to be accepted for storage
in the table.

Syntax:
CREATE TABLE Table_Name (column_name data_type (size) NOT NULL, );

Example:
CREATE TABLE student (sno NUMBER(3)NOT NULL, name CHAR(10));

2. UNIQUE:
The purpose of a unique key is to ensure that information in the column(s) is unique i.e. a
value entered in column(s) defined in the unique constraint must not be repeated across the
column(s). A table may have many unique keys.

Syntax:
CREATE TABLE Table_Name(column_name data_type(size) UNIQUE, ….);

Example:
CREATE TABLE student (sno NUMBER(3) UNIQUE, name CHAR(10));

3. CHECK: Specifies a condition that each row in the table must satisfy. To satisfy the
constraint, each row in the table must make the condition either TRUE or unknown (due to a
null).

Syntax:
CREATE TABLE Table_Name(column_name data_type(size)
CHECK(logical expression), ….);

Example:
CREATE TABLE student (sno NUMBER (3), name CHAR(10),class
CHAR(5),CHECK(class IN(‘CSE’,’CAD’,’VLSI’));
4. PRIMARY KEY:

A field which is used to identify a record uniquely. A column or combination of columns can
be created as primary key, which can be used as a reference from other tables. A table
contains primary key is known as Master Table.

 It must uniquely identify each record in a table.


 It must contain unique values.
 It cannot be a null field.
 It cannot be multi port field.
 It should contain a minimum no. of fields necessary to be called unique.

Syntax:
CREATE TABLE Table_Name(column_name data_type(size) PRIMARY KEY, ….);

Example:
CREATE TABLE faculty (fcode NUMBER(3) PRIMARY KEY, fname CHAR(10));

5. FOREIGN KEY:

It is a table level constraint. We cannot add this at column level. To reference any primary
key column from other table this constraint can be used. The table in which the foreign key is
defined is called a detail table. The table that defines the primary key and is referenced by
the foreign key is called the master table.

Syntax:
CREATE TABLE Table_Name(column_name data_type(size) FOREIGN
KEY(column_name) REFERENCES table_name);

Example:
CREATE TABLE subject (scode NUMBER (3) PRIMARY KEY, subname
CHAR(10),fcode NUMBER(3), FOREIGN KEY(fcode) REFERENCE faculty );

Defining integrity constraints in the alter table command:

Syntax:
ALTER TABLE Table_Name ADD PRIMARY KEY (column_name);
Example:
ALTER TABLE student ADD PRIMARY KEY (sno);
(Or)
Syntax:
ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY
KEY(colname)

Example:
ALTER TABLE student ADD CONSTRAINT SN PRIMARY KEY(SNO)

Dropping integrity constraints in the alter table command:


Syntax:
ALTER TABLE Table_Name DROP constraint_name;

Example:
ALTER TABLE student DROP PRIMARY KEY;
(or)
Syntax:
ALTER TABLE student DROP CONSTRAINT constraint_name;

Example:
ALTER TABLE student DROP CONSTRAINT SN;

6. DEFAULT :
The DEFAULT constraint is used to insert a default value into a column. The default value
will be added to all new records, if no other value is specified.

Syntax:
CREATE TABLE Table_Name(col_name1,col_name2,col_name3 DEFAULT ‘<value>’);

Example:
CREATE TABLE student (sno NUMBER(3) UNIQUE, name CHAR(10),address
VARCHAR(20) DEFAULT ‘Aurangabad’);

LAB PRACTICE ASSIGNMENT:

1. Create a table called EMP with the following structure.


Name Type
---------- ----------------------
EMPNO NUMBER (6)
ENAME VARCHAR2 (20)
JOB VARCHAR2 (10)
DEPTNO NUMBER (3)
SAL NUMBER (7,2)

Allow NULL for all columns except ename and job. (Either in Create command or
Alter Command)
2. Add constraints to check, while entering the empno value (i.e) empno > 100.
3. Define the field DEPTNO as unique.
4. Create a primary key constraint for the table(EMPNO).
5. Create a default constraint and provide a salary value of "1000" if salary is not provided.

6. Create a table department with the following structure.

Name Type
---------- ----------------------
DEPTNO NUMBER (6)
DNAME VARCHAR2 (20)
LOC VARCHAR2 (10)
create a referential integrity constraint between Employee and Department table.
7.Display the Employee information along with department details
8. Display the Employee details who works in CSE department and salary less than 10000.
9. Delete the Employee details who works in Hyderabad.

Experiment :6 BUILT-IN FUNCTIONS

1. NUMBER FUNCTIONS:

i. Abs(n) : A mathematical function that returns the absolute(positive) value of the


specified numeric expression. (ABS changes negative values to positive values. ABS
has no effect on zero or positive values.)

Select abs(-15) from dual;

ii. Power(m,n): POWER() function returns the value of a number raised to another,
where both of the numbers are passed as arguments.

Select power(4,2) from dual;

iii. Mod(m,n): It is used to get the remainder from a division

Select mod(10,3) from dual;

iv. Round(m,n): Return a number rounded to a certain number of decimal places

Select round(100.256,2) from dual;

v. Truncate(m,n): The TRUNC () function returns date value truncated to the unit
specified by the format.

Select truncate(100.256,2) from dual;

vi. Sqrt(m,n): returns the square root of a given value in the argument.

Select sqrt(16) from dual;

2. AGGREGATE FUNCTIONS:
In addition to simply retrieving data, we often want to perform some computation or
summarization. SQL allows the use of arithmetic expressions. We now consider a powerful
class of constructs for computing aggregate values such as MIN and SUM.

i. Count():

COUNT following by a column name returns the count of tuple in that column. If DISTINCT
keyword is used then it will return only the count of unique tuple in the column. Otherwise, it
will return count of all the tuples (including duplicates) count (*) indicates all the tuples of
the column.

Syntax:
COUNT (Column name)

Example:
SELECT COUNT (Sal) FROM emp;

ii. SUM(): SUM followed by a column name returns the sum of all the values in that
column.

Syntax:
SUM (Column name)

Example:
SELECT SUM (Sal) From emp;

iii. AVG(): AVG followed by a column name returns the average value of that column
values.

Syntax:
AVG (n1, n2...)

Example:
Select AVG (10, 15, 30) FROM DUAL;

iv. MAX():
MAX followed by a column name returns the maximum value of that column.

Syntax:
MAX (Column name)

Example:
SELECT MAX (Sal) FROM emp;

SQL> select deptno, max(sal) from emp group by deptno;

DEPTNO MAX (SAL)


------ --------
10 5000
20 3000
30 2850

SQL> select deptno, max (sal) from emp group by deptno having max(sal)<3000;

DEPTNO MAX(SAL)
----- --------
30 2850

v. MIN(): MIN followed by column name returns the minimum value of that column.

Syntax:
MIN (Column name)

Example:
SELECT MIN (Sal) FROM emp;

SQL> select deptno,min(sal) from emp group by deptno having min(sal)>1000;

DEPTNO MIN (SAL)


----- --------
10 1300

3. STRING/ CHARACTER FUNCTION:

i. lower (char): Converts to lowercase.

select lower( 'HELLO');

ii. upper (char) : Converts to Uppercase.

select upper ('hello');

iii. ltrim (char,[set]): Trims the left space.

select ltrim (' cseit') as new;

iv. rtrim (char,[set]): Trims the right space.

select rtrim (‘cseit ’) as new;

v. replace (char,search ): Finds the given character in a string and replaces with another
character.

select replace(‘jack and jue’,‘j’,‘bl’) from dual;

vi. length(char): calculates the length of the given string.

select length ('DAtabase Systems');

vii. concat(str1,str2): concatenates two strings


select concat('Database', 'Management','Systems');

viii. Substr: Returns part of a character.

select substr(‘ABCDEFGHIJ’,3,4);
CDEF

ix. Instr: The INSTR functions search string for substring. The function returns an integer
indicating the position of the character in string that is the first character of this
occurrence.
select instr('CORPORATE FLOOR','OR',3,2);

4. DATE FUNCTIONS:

i. SYSDATE() /CURDATE():

select sysdate();
2-DEC-08

ii. DATE_ADD()
iii. DATE_SUB()

iv. DATE_FORMAT()
v. DATE()
vi. DATEDIFF()
vii. DAY()

LAB PRACTICE ASSIGNMENT:

Create a table EMPLOYEE with following schema:


(Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name,Job_id, Designation , Salary)

Write SQL statements for the following query.


1. List the E_no, E_name, Salary of all employees working for MANAGER.
2. Display all the details of the employee whose salary is more than the Sal of any IT PROFF..
3. List the employees in the ascending order of Designations of those joined after 1981.
4. List the employees along with their Experience and Daily Salary.
5. List the employees who are either ‘CLERK’ or ‘ANALYST’ .
6. List the employees who joined on 1-MAY-81, 3-DEC-81, 17-DEC-81,19-JAN-80 .
7. List the employees who are working for the Deptno 10 or20.
8. List the Enames those are starting with ‘S’ .
9. Dislay the name as well as the first five characters of name(s) starting with ‘H’
10. List all the emps except ‘PRESIDENT’ & ‘MGR” in asc order of Salaries.

You might also like