DBMS Lab File
DBMS Lab File
Introduction to SQL,
1 Database and database 10/1/20
management system.
VarioussoftwareofDBMSand
2 17/1/20
Databaselanguages.
Introduction to ER Diagram,
3 7/2/20
symbol table.
Case Study :
5 HOSPITALMANAGEMENT 28/2/20
SYSTEM
ER Diagram, constructing
6 entity tables and 27/3/20
relationship tables.
Implementing Aggregate
10 functions, Date 24/4/20
function, Time functions..
Implementing Views ,
11 Triggers, Grant & Revoke 29/4/20
commands
Experiment -1
What is a database:
Database is an organized collection of data. For example, a database of a
college would
be having a collection of data such as –
1. Personal records of Students
2. Students performance history
3. Teachers data
4. Financial department data etc.
Types of Databases
There are two types of databases –
1. Relational Database
2. Non-relational Database
Non-relational databases:
Data is not organized in form of tables. Data is stored in form of key &
value
pairs. The examples of non-relational databases are: JSON & XML.We
cannot
interact with non-relational databases using SQL.
Relational Databases:
In relational database, data is organized in form of tables. A table contains
rows and
columns of data. Table has a unique key to identify each row of the table.
SQL is used to interact with relational databases. We often refer relational
database as
SQL database.
What is SQL?
1. SQL stands for Structured Query Language, which is a standardised
language for
interacting with RDBMS (Relational Database Management System). Some
of
the popular relational database example are: MySQL, Oracle, maria DB,
postgre SQLetc.
2. SQL is used to perform C.R.U.D (Create, Retrieve, Update & Delete)
operation son
relationaldatabases.
3. SQL can also perform administrative tasks on database such as
database
security,backup, user management etc.
4. We can create databases and tables inside database using SQL.
Experiment -2
Theory:
Various software of DBMS:
1) MySQL
2) Microsoft Access
3) Oracle
4) PostgreSQL
5) dBASE
6) FoxPro
7) SQLite
8) IBMDB2
9) LibreOfficeBase
10) MariaDB
11) Microsoft SQL Serveretc.
Database Languages
Read, Update, Manipulate, and Store data in a database using Database
Languages.
The following are the database languages:
● Data Definition Language
● Data Manipulation Language
● Data Control Language
● Transaction Control Language
Theory:
An Entity–relationship model (ER model) describes the structure of a
database with
the help of a diagram, which is known as Entity Relationship Diagram
(ER
Diagram). An ER model is a design or blueprint of a database that can
later be
implemented as a database. The main components of E-R model are:
entity set
and relationship set.
What is an Entity Relationship Diagram (ER Diagram)?
An ER diagram shows the relationship among entity sets. An entity set is a
group of
similar entities and these entities can have attributes. In terms of DBMS, an
entity is a table or attribute of a table in database, so by showing
relationship
among tables and their attributes, ER diagram shows the complete logical
structure of a database.
A simple ER Diagram:
In the following diagram we have two entities Student and College and their
relationship.
The relationship between Student and College is many to one as a college
can
have many students however a student cannot study in multiple colleges at
the
same time. Student entity has attributes such as Stu_Id, Stu_Name &
Stu_Addr
and College entity has attributes such as Col_ID & Col_Name.
Rectangle: Represents Entity sets.
Ellipses: Attributes
Diamonds: Relationship Set
Lines: They link attributes to Entity Sets and Entity sets to Relationship Set
Double Ellipses:Multivalued
AttributesDashed Ellipses: Derived
AttributesDouble Rectangles: Weak
Entity Sets
Double Lines: Total participation of an entity in a relationship set
Components of a ER Diagram
As shown in the above diagram, an ER diagram has three main
components:
1. Entity
2. Attribute
3. Relationship
1. Entity
An entity is an object or component of data. An entity is represented as
rectangle in an
ER diagram.
For example: In the following ER diagram we have two entities Student and
College and these two entities have many to one relationship as many
students
study in a single college. We will read more about relationships later, for
now
focus on entities.
Weak Entity:
An entity that cannot be uniquely identified by its own attributes and relies
on the
relationship with other entity is called weak entity. The weak entity is
represented
by a double rectangle. For example – a bank account cannot be uniquely
identified without knowing the bank to which the account belongs, so bank
account is a weak entity.
2. Attribute
An attribute describes the property of an entity. An attribute is represented
as Oval in an
ER diagram. There are four types of attributes:
1. Key attribute
2. Composite attribute
3. Multivalued attribute
4. Derived attribute
1. Key attribute:
A key attribute can uniquely identify an entity from an entity set. For
example, student roll
number can uniquely identify a student from a set of students. Key attribute
is
represented by oval same as other attributes however thetext of key
attribute is
underlined.
2. Composite attribute:
An attribute that is a combination of other attributes is known as composite
attribute. For
example, In student entity, the student address is a composite attribute as
an
address is composed of other attributes such as pin code, state, country.
3. Multi valued attribute:
An attribute that can hold multiple values is known as multivalued attribute.
It is
represented with double ovalsin an ER Diagram. For example – A person
can
have more than one phone numbers so the phone number attribute is multi
valued.
4. Derived attribute:
A derived attribute is one whose value is dynamic and derived from another
attribute. It is
represented by dashed oval in an ER Diagram. For example – Person age
is a
derived attribute as it changes over time and can be derived from another
attribute (Date of birth).
E-R diagram with multivalued and derived attributes:
3. Relationship
A relationship is represented by diamond shape in ER diagram, it shows
the relationship
among entities. There are four types of relationships:
1. One to One
2. One to Many
3. Many to One
4. Many to Many
1. One to One Relationship
When a single instance of an entity is associated with a single instance of
another entity
then it is called one to one relationship. For example, a person has only
one
passport and a passport is given to one person.
2. One to Many Relationship
When a single instance of an entity is associated with more than one
instances of
another entity then it is called one to many relationship. For example – a
customer can place many orders but a order cannot be placed by many
customers.
3. Many to One Relationship
When more than one instances of an entity is associated with a single
instance of
another entity then it is called many to one relationship. For example –
many
students can study in a single college but a student cannot study in many
colleges at the
sametime.
Theory:
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This
ensures the
accuracy and reliability of the data in the table. If there is any violation
between the
constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints
apply to a
column, and table level constraints apply to the whole table.
The following constraints are commonly used in SQL:
1) NOT NULL-Ensures that a column cannot have a NULL value
2) UNIQUE-Ensures that all values in a column are different
3) PRIMARY KEY-A combination of a NOT NULL and UNIQUE . Uniquely
identifies
each row in a table
4) FOREIGN KEY- Uniquely identifies arow/recordin another table
5) CHECK-Ensuresthat all values in a column satisfies a specific condition
6) DEFAULT-Sets a default value for a column when no value is s p e c I f
I ed
INDEX–U s e d t o c r e a t e a n d r e t r I e v e d a ta f r o m t h e d a t a b
a s e v e r yquickly
Dropping ConstraintsAny constraint that you have defined can be
dropped using the
ALTER TABLE command with the DROP CONSTRAINT option.
Some implementations may provide shortcuts for dropping certain
constraints and
disable constraints. Instead of permanently dropping a constraint from the
database, you
may want to temporarily disable the constraint and then enable it later.
Integrity ConstraintsIntegrity constraints are used to ensure accuracy and
consistency
of the data in a relational database. Data integrity is handled in a relational
database
through the concept of referential integrity.
There are many types of integrity constraints that play a role inReferential
Integrity
(RI). These constraints include Primary Key, Foreign Key, Unique
Constraints and other
constraints which are
Experiment – 5
ER DIAGRAM
Theory: To store the data in the database we need a table to do that. The
CREATE TABLE statement is used to create a table in SQL. We know that
a
table comprises of rows and columns. So while creating tables we have to
provide all the information to SQL about the names of the columns, type
of data to be stored in columns, size of the data etc. Let us now dive into
details on how to use CREATE TABLE statement to create tables in SQL.
Syntax:
CREATE TABLE
table_name (
column1
data_type(size),
column2
data_type(size),
column3
data_type(size),
....
);
table_name: name of the table.
column1 name of the first
column.
Datatype: Type of data we want to store in the particular column.
For example : int for integer data.
Size: Size of the data we can store in a particular column. For example if
for
a column we specify the data_type as int and size as 10 then this column
can store an integer
number of maximum 10 digits.
Example Query:
This query will create a table named Students with three columns,
ROLL_NO, NAME and SUBJECT.
CREATE TABLE Students
(
ROLL_NO int(3),
NAME varchar(20),
SUBJECT varchar(20),
);
This query will create a table named Students. The ROLL_NO field is of
type int
and can store an integer number of size 3. The next two columns NAME
and
SUBJECT are of type varchar and can store characters and the size 20
specifies
that these two fields can hold maximum of 20 characters.
LEARNINGS/FINDINGS
1- We learnt about the basics of the DBMS – creating tables .
2- How to declare several columns of different data types
3- How to make them primary keys and implementingseveral
constraints.
DISCUSSION
From this experiment we learnt about creating tables as per the
different requirements. It is the basic pillar for storing information.
CONCLUSION:
All the DDL commands were successfully understood and implemented on
the
database in the experiment.
Experiment – 7
THEORY
Data Definition Language consists of SQL commands that are used to
define the database schema. It deals with the description of database
schema. It is used to create or modify the structure of database objects in
the database.
1. Create:Used to create atable
2. Alter:Used to alter the structure of thetable
3. Drop:Used to delete the entiretable
4. Truncate:Used to delete all the entries in thetable
Constraints are rules for the table
1. Primary key:The column of the table which can’t be left emptyand
has to be unique at the sametime
2. Foreign key:Uniquely identifies the row/record of another tablei.e. it
is a primary key of anothertable.
3. Check:Ensures that the values in a column satisfy thegiven
condition
4. Unique:Ensures that all values in the table areunique
5. Not null and null:Not null ensures that a column cannot havea
NULLvalue.
6. Default:Used to provide default value for acolumn
QUERIES
Create alter drop truncate
1. CREATETABLEstudents(name varchar(30),roll_noint);
2. ALTER TABLEstudents ADD(emailvarchar(30));
3. DROPTABLEstudents;
4. TRUNCATETABLEstudents;
Constraints
1. CREATE TABLE students (name varchar(30) NOT NULL,
reg_no int PRIMARY KEY , percentage int CHECK(percentage
<=100 and percentage >=0) ,fingerprint_id int UNIQUE , city
varchar(30) DEFAULT 'Delhi', stream_name varchar(30), FOREIGN
KEY(stream_name) REFERENCES stream_list(stream));
OUTPUT
1. Create
2. Alter
3. Truncate
4. Drop
5. Constraints
RESULT
Thus, in this experiment we learned what data definition language is and
how to use the various commands of DDL and their various constraints.
THEORY
Data Manipulation Language consists of the SQL commands that deal
with manipulation of data present in the database.
1. Insert:Used to insert values into a table
2. Select:Used to retrieve data from the table
3. Update:Used to update existing data in the table
4. Delete:Used to delete records from a table
QUERIES
1. INSERT INTO studentsVALUES(‘xyz’,21);
2. SELECT * FROMstudents;
3. UPDATEstudents SET name = ‘abc’ WHERE roll_no =21;
4. DELETE FROM students WHERE roll_no =21;
OUTPUT
1. Insert
2. Select
3. Update
4. Delete
RESULT
Thus, in this experiment we learned what data manipulation language is
and the various commands of DML.
Experiment – 8
Theory:
A select statement is used to select certain columns from a table.
A where clause allows the user to put conditions on what rows to choose
Order by clause orders the rows selected according to the values of the
column provided
and, in the order, provided
Select col1, col2, … from table_name <where condition> <order by
col_number
<order>>;
NOTE: the part enclosed withing <> is optional.
THEORY
In nested queries, a query is written within another query. The result of
inner query is used in the execution of outer query.
Join is used to combine rows from two or more tables based on a related
column between them.
1. Natural Join: Combines table based on columns with samename
andtype
2. Inner Join: Returns records having matching values in bothtable
3. Left Jon: Returns all records from left table and matchedrecords
from righttable
4. Full Join: Returns all records when there is a match in either leftor
righttable
QUERY
1. SELECT * FROM students WHERE marks>(SELECT AVG(marks)
FROM STUDENTS);
2. Joins:
a. SELECT * FROM product NATURAL JOIN company;
b. SELECT * FROM product INNER JOIN company ON
product.cid =company.cid;
c. SELECT * FROM product LEFT JOIN
companyONproduct.cid =company.cid;
d. SELECT * FROM product FULL JOIN companyON
product.cid =company.cid;
OUTPUT
1.Nested Query
2(a) Natural Join
2(b) Inner Join
2(c) Left Join
2(d) Full Join
RESULT
Thus, in this experiment we learned about nested queries and join and
how to implement them in our database.
Experiment – 10
Theory:
AggregateFunctionsCount():
Count(*): Returns total number of records .i.e 6.
Count(BILL_AMT): Return number of Non Null values over the column
BILL_AMT. i.e 5.
Count(Distinct BILL_AMT): Return number of distinct Non Null values over
the column
BILL_AMT
Sum():
sum(BILL_AMT): Sum all Non Null values of Column BILL_AMT i.e., 310
sum(Distinct BILL_AMT): Sum of all distinct Non-Null values i.e., 250.
Avg():
Avg(BILL_AMT) = Sum(BILL_AMT) / count(BILL_AMT) = 310/5
Avg(Distinct BILL_AMT) = sum(Distinct BILL_AMT) / Count(Distinct
BILL_AMT) = 250/4
Min():
Min(BILL_AMT): Minimum value in the BILL_AMT column except NULL
i.e., 40.
Max():
Max(BILL_AMT): Maximum value in the BILL_AMT i.e., 80.
Variance():
Variance(BILL_AMT): returns the variance of the column BILL_AMT
DateFunctions
SYSDATE:
Return the current system date and time of the operating system where the
Oracle
Database resides.
String Queries
LENGTH():
Returns the length of the string expression
LOWER():
Converts character data to lower case
SUBSTR():
Extracts substring from a string
UPPER():
converts character data to upper case.
Theory:
Views
Views in SQL are kind of virtual tables. A view also has rows and columns
as they are in
a real table in the database. We can create a view by selecting fields from
one or more
tables present in the database. A View can either have all the rows of a
table or specific
rows based on certain condition.
Syntax:
Create view view_name as
<Select statement>;
e.g. create view as names as select name from stud;
Trigger
A trigger is a stored procedure in database which automatically invokes
whenever a
special event in the database occurs. For example, a trigger can be
invoked when a row
is inserted into a specified table or when certain table columns are being
updated.
Syntax:
create trigger [trigger_name] [before | after]
{insert | update | delete} on [table_name]
[for each row] [trigger_body]
Grant
To grant privileges to a user account, the GRANT statement is used.
Syntax:
GRANT privileges_names ON object TO user;
Revoke
The Revoke statement is used to revoke some or all of the privileges which
have been
granted to a user in the past.
Syntax:
REVOKE privileges ON object FROM user;
Conclusion
• Weget to know about different entities and relationship and
theirmapping
cardinality in a Hospital, thus enabling us to carve a Hospital
Management
System.Wefirst fed some data into the database to simulate a
hospital, its
patients, doctors, nurses and various departments of ahospital.
• Next we ran JOIN queries on the tables to accumulate data from
different
tables and then performed operations on the pooled data. All the
JOIN
operations -Inner,leftouter,rightouter,full outer were implemented
and we
received null values in some places indicating the columns of one
of the
tables which didn't satisfy the ON condition but are still present in
thetable.
• Next we implemented the SQL Aggregate functions such as
SUM,AVG,MAX, MIN and COUNT to perform operations on the
aggregated
data i.e. after grouping them and applying some additional
conditions if
needed, •We also used Date functions to obtain the current
system time and
date and ran queries based on the time so obtained.
Conclusion
• We can draw clear conclusions about various the entities and
relationships
in a University.
• We got to know about the functioning of join queries used
togather data
from 2 tables into and perform subsequent operations onthem.
• We successfully applied the various SQL aggregate functions
and date
functions and learnt their syntax, working and purpose.
• We successfully implemented all the queries with cent percent.