DBMS Lab Manual
DBMS Lab Manual
DATABASE MANAGEMENT
SYSTEM
LAB MANUAL
S.E. (INFORMATION TECHNOLOGY)
(A.Y. 2024-25)
Prerequisites:
1. Data structures
2. Software engineering principles and practices.
Course Objectives:
Understand the fundamental concepts of database management. These concepts include
aspects of database design, database languages, and database-system implementation.
To provide a strong formal foundation in database concepts, recent technologies and
best industry practices.
To give systematic database design approaches covering conceptual design, logical
design and an overview of physical design.
To learn the SQL database system.
To learn and understand various Database Architectures and its use for application
development.
To programme PL/SQL including stored procedures, stored functions, cursors and
packages.
Course Outcomes:
After completion of this course student will be able to:
CO1 : To install and configure database systems.
CO2 : To analyze database models & entity relationship models.
CO3 : To design and implement a database schema for a given problem-domain
CO4 : To understand the relational database systems.
CO5 : To populate and query a database using SQL DDL / DML / DCL commands.
CO6 : To design a backend database of any one organization: CASE STUDY
INDEX
Sr. Page
COs Title
No No.
Group-A
Study of MySQL Open source software. Discuss the characteristics like
1 CO1 1
efficiency, scalability, performance and transactional properties.
CO3
Design and implement a database (for assignment no 1) using DDL
5 & 23
statements and apply normalization on them.
CO4
Create Table with primary key and foreign key constraints. a. Alter table
6 CO3 28
with add n modify b. Drop table.
Write and execute suitable database triggers .Consider row level and
10 CO6 47
statement level triggers.
Aim
Objective
Theory
What is Database?
A database is a separate application that stores a collection of data. Each database has one or more distinct APIs for
creating, accessing, managing, searching and replicating the data it holds. So nowadays, we use relational database
management systems (RDBMS) to store and manage huge volume of data. This is called relational database because
all the data is stored into different tables and relations are established using primary keys or other keys known as
foreign keys.
A Relational DataBase Management System (RDBMS) is a software that:
_ Enables you to implement a database with tables, columns and indexes.
_ Guarantees the Referential Integrity between rows of various tables.
_ Updates the indexes automatically.
_ Interprets an SQL query and combines information from various tables.
RDBMS Terminology:
Before we proceed to explain MySQL database system, let's revise few definitions related to database.
_ Database: A database is a collection of tables, with related data.
_ Table: A table is a matrix with data. A table in a database looks like a simple spreadsheet.
_ Column: One column (data element) contains data of one and the same kind, for example the
column postcode.
_ Row: A row (= tuple, entry or record) is a group of related data, for example the data of one
subscription.
_ Redundancy: Storing data twice, redundantly to make the system faster.
_ Primary Key: A primary key is unique. A key value cannot occur twice in one table. With a key,
you can find at most one row.
_ Foreign Key: A foreign key is the linking pin between two tables.
_ Compound Key: A compound key (composite key) is a key that consists of multiple columns,
because one column is not sufficiently unique.
_ Index: An index in a database resembles an index at the back of a book.
The RENAME Clause allows you the change the table name to the new one.
Deleting Tables
To delete table from the database, you can use DROP TABLE statement:
1 DROP [TEMPORARY] TABLE [IF EXISTS] table_name [, table_name,...]
TEMPORARY keyword is used for deleting temporary tables. MySQL allows you to drop multiple tables at once by
listing them and separated each by a comma. IF EXISTS is used to prevent you from deleting
table which does not exist in the database.
Empty Table's Data
1 TRUNCATE TABLE table_name
• TRUNCATE TABLE statement drop table and recreate it therefore it is much faster than DELETE TABLE
statement. However it is not transaction-safe.
• The number of deleted rows is not returned like SQL DELETE TABLE statement.
2. SELECT lastname,firstna
FROM employees;
3. SELECT firstname,lastna
FROM employees
WHERE jobtitle="president”;
5. SELECT firstname,lastna
FROM employees
ORDER BY firstname ASC, jobtitle DESC;
6. SELECT firstname,lastname
FROM employees
LIMIT 5
7. SELECT firstname,lastname
FROM employees
LIMIT 10,5
SELECT column_list
FROM t1
SELECT A.productCode, A
FROM products A
INNER JOIN orderDetails B on A.productCode = B.productCode;
MySQL LEFT JOIN
SELECT c.customerNumber
FROM customers c
LEFT JOIN orders o ON c.customerNumber = o.customerNumber;
References:
1. Raghu Ramkrishanan, Johannes Gehrke 4 th Edition “Database Management Systems” 2. Avi Silberschatz , Henry
F. Korth , S. Sudarshan, “Database System Concepts, Sixth Edition”, ISBN-13: 978-93-3290-138-4, MCGraw Hill
Q. No Questions
1 What is DBMS?
2 What are advantages of DBMS?
3 Explain data model with suitable example.
Marking criteria.
Experiment completion (Timely)
Lab file (neatness and regularity)
Viva (from time to time)
Mock Practical Exam
Exam (end term): Practical + Viva
Assessment Methodology
Timely completion of assignment- 2marks
Program demonstration- 4 marks
Viva-voce -2 marks
Timely submission of journal- 2 marks
Aim
Objective
Theory
Root login
mysql –u root –p
Help
\h for help
Create Database
create database testdb;
create user „testuser‟@‟localhost‟ identified by „password‟
Access MySQL remotely
create user „testuser1‟@‟192.168.100.137‟ identified by „password‟
grant all on testdb.*@192.168.100.137 to testuser1
sudo iptables –I –p udp --dport 3306 –j ACCEPT
sudo iptables –I –p tcp --dport 3306 –j ACCEPT
References:
1. Raghu Ramkrishanan, Johannes Gehrke 4 th Edition “Database Management Systems” 2. Avi Silberschatz , Henry
F. Korth , S. Sudarshan, “Database System Concepts, Sixth Edition”, ISBN-13: 978-93-3290-138-4, MCGraw Hill
Q. No Questions
Marking criteria.
Experiment completion (Timely)
11
Lab file (neatness and regularity)
Viva (from time to time)
Mock Practical Exam
Exam (end term): Practical + Viva
Assessment Methodology
Timely completion of assignment- 2marks
Program demonstration- 4 marks
Viva-voce -2 marks
Timely submission of journal- 2 marks
12
ASSIGNMENT NO. 3
Aim
Study of SQLite: What is SQLite? Uses of Sqlite. Building and installing SQLite.
Objective
Theory
What is SQLite?
• SQLite is a self-contained, high-reliability, embedded, full-featured, public-domain, SQL database engine. It
is the most used database engine in the world. It is an in-process library and its code is publicly available. It is
free for use for any purpose, commercial or private. It is basically an embedded SQL database engine.
Ordinary disk files can be easily read and write by SQLite because it does not have any separate server like
SQL. The SQLite database file format is cross-platform so that anyone can easily copy a database between
32-bit and 64-bit systems. Due to all these features, it is a popular choice as an Application File Format.
History
• It was designed by D. Richard Hipp for the purpose of no administration required for operating a program. in
August 2000. As it is very lightweight compared to others like MySql and Oracle, it is called SQLite.
Different versions of SQLite are released since 2000.
Installation on Windows
• Installation on Windows:
• Visit the official website of SQLite for downloading the zip file.
• Download that zip file.
• Create a folder in C or D ( wherever you want ) for storing SQLite by expanding zip file.
• Open the command prompt and set the path for the location of SQLite folder given in the previous step. After
that write “sqlite3” and press enter.
Installation on Linux
• Sudo apt-get install sqlite3 libsqlite3-dev
• It will automatically install and once it asks Do you want to continue (Y/N) type Y and press enter. After
successful installation, we can check it by command sqlite3.
13
Features
• The transactions follow ACID properties i.e. atomicity, consistency, isolation, and durability even after
system crashes and power failures.
• The configuration process is very easy, no setup or administration needed.
• All the features of SQL are implemented in it with some additional features like partial indexes, indexes on
expressions, JSON, and common table expressions.
• Sometimes it is faster than the direct file system I/O.
• It supports terabyte-sized databases and gigabyte-sized strings and blobs.
• Almost all OS supports SQLite like Android, BSD, iOS, Linux, Mac, Solaris, VxWorks, and Windows
(Win32, WinCE, etc. It is very much easy to port to other systems.
• Complete database can be stored in a single cross-platform disk file.
Applications
• Due to its small code print and efficient usage of memory, it is the popular choice for the database engine in
cellphones, PDAs, MP3 players, set-top boxes, and other electronic gadgets.
• It is used as an alternative for open to writing XML, JSON, CSV or some proprietary format into disk files
used by the application.
• As it has no complication for configuration and easily stores file in an ordinary disk file, so it can be used as a
database for small to medium sized websites.
• It is faster and accessible through a wide variety of third-party tools, so it has great application in different
software platforms.
Disadvantages
• It is only used where there is low to medium traffic requests are there.
• The database size is restricted i.e. it is 2GB in most cases.
Q. No Questions
14
ASSIGNMENT NO. 4
Aim
Design any database with at least 3 entities and relationships between them. Draw suitable ER/EER diagram
for the system.
Objective
Theory
The ER model defines the conceptual view of a database. It works around real-world entities and the associations
among them. At view level, the ER model is considered a good option for designing databases.
Entity
An entity can be a real-world object, either animate or inanimate, that can be easily identifiable. For
example, in a school database, students, teachers, classes, and courses offered can be considered as entities.
All these entities have some attributes or properties that give them their identity.
An entity set is a collection of similar types of entities. An entity set may contain entities with attribute
sharing similar values. For example, a Students set may contain all the students of a school; likewise a
Teachers set may contain all the teachers of a school from all faculties. Entity sets need not be disjoint.
Attributes
Entities are represented by means of their properties, called attributes. All attributes have values. For
example, a student entity may have name, class, and age as attributes.
There exists a domain or range of values that can be assigned to attributes. For example, a student's name
cannot be a numeric value. It has to be alphabetic. A student's age cannot be negative, etc.
Types of Attributes
Simple attribute − Simple attributes are atomic values, which cannot be divided further. For
example, a student's phone number is an atomic value of 10 digits.
Composite attribute − Composite attributes are made of more than one simple attribute. For
example, a student's complete name may have first_name and last_name.
Derived attribute − Derived attributes are the attributes that do not exist in the physical database,
but their values are derived from other attributes present in the database. For example,
average_salary in a department should not be saved directly in the database, instead it can be
derived. For another example, age can be derived from data_of_birth.
15
Single-value attribute − Single-value attributes contain single value. For example −
Social_Security_Number.
Multi-value attribute − Multi-value attributes may contain more than one values. For example, a
person can have more than one phone number, email_address, etc.
Key is an attribute or collection of attributes that uniquely identifies an entity among entity set.
For example, the roll_number of a student makes him/her identifiable among students.
Super Key − A set of attributes (one or more) that collectively identifies an entity in an entity set.
Candidate Key − A minimal super key is called a candidate key. An entity set may have more than
one candidate key.
Primary Key − A primary key is one of the candidate keys chosen by the database designer to
uniquely identify the entity set.
Relationship
The association among entities is called a relationship. For example, an employee works_at a department,
a student enrolls in a course. Here, Works_at and Enrolls are called relationships.
Relationship Set
A set of relationships of similar type is called a relationship set. Like entities, a relationship too can have
attributes. These attributes are called descriptive attributes.
Degree of Relationship
The number of participating entities in a relationship defines the degree of the relationship.
Binary = degree 2
Ternary = degree 3
n-ary = degree
16
how the ER Model is represented by means of an ER diagram. Any object, for example, entities, attributes of an
entity, relationship sets, and attributes of relationship sets, can be represented with the help of an ER diagram.
Entity
Entities are represented by means of rectangles. Rectangles are named with the entity set they represent.
Attributes
Attributes are the properties of entities. Attributes are represented by means of ellipses. Every ellipse
represents one attribute and is directly connected to its entity (rectangle).
If the attributes are composite, they are further divided in a tree like structure. Every node is then
connected to its attribute. That is, composite attributes are represented by ellipses that are connected with
an ellipse.
17
Multivalued attributes are depicted by double ellipse.
Relationship
Relationships are represented by diamond-shaped box. Name of the relationship is written inside the
diamond-box. All the entities (rectangles) participating in a relationship, are connected to it by a line.
A relationship where two entities are participating is called a binary relationship. Cardinality is the
number of instance of an entity from a relation that can be associated with the relation.
One-to-one − When only one instance of an entity is associated with the relationship, it is marked
as '1:1'. The following image reflects that only one instance of each entity should be associated with
the relationship. It depicts one-to-one relationship.
18
One-to-many − When more than one instance of an entity is associated with a relationship, it is
marked as '1:N'. The following image reflects that only one instance of entity on the left and more
than one instance of an entity on the right can be associated with the relationship. It depicts one-to-
many relationship.
Many-to-one − When more than one instance of entity is associated with the relationship, it is
marked as 'N:1'. The following image reflects that more than one instance of an entity on the left
and only one instance of an entity on the right can be associated with the relationship. It depicts
many-to-one relationship.
Many-to-many − The following image reflects that more than one instance of an entity on the left
and more than one instance of an entity on the right can be associated with the relationship. It
depicts many-to-many relationship.
Participation Constraints
Total Participation − Each entity is involved in the relationship. Total participation is represented
by double lines.
19
Partial participation − Not all entities are involved in the relationship. Partial participation is
represented by single lines.
The ER Model has the power of expressing database entities in a conceptual hierarchical manner. As the
hierarchy goes up, it generalizes the view of entities, and as we go deep in the hierarchy, it gives us the
detail of every entity included.
Going up in this structure is called generalization, where entities are clubbed together to represent a more
generalized view. For example, a particular student named Mira can be generalized along with all the
students. The entity shall be a student, and further, the student is a person. The reverse is
called specialization where a person is a student, and that student is Mira.
Generalization
As mentioned above, the process of generalizing entities, where the generalized entities contain the
properties of all the generalized entities, is called generalization. In generalization, a number of entities are
brought together into one generalized entity based on their similar characteristics. For example, pigeon,
house sparrow, crow and dove can all be generalized as Birds.
Specialization
Specialization is the opposite of generalization. In specialization, a group of entities is divided into sub-
groups based on their characteristics. Take a group „Person‟ for example. A person has name, date of birth,
gender, etc. These properties are common in all persons, human beings. But in a company, persons can be
identified as employee, employer, customer, or vendor, based on what role they play in the company.
20
Similarly, in a school database, persons can be specialized as teacher, student, or a staff, based on what role
they play in school as entities.
Inheritance
We use all the above features of ER-Model in order to create classes of objects in object-oriented
programming. The details of entities are generally hidden from the user; this process known
as abstraction.
Multinational Company Manages information of Employees, Department and Project. Each Employee has
unique ID. Each Employee works on project in some department. Every employee is assigned at least one
project.
Design ER Diagram for Employee Management System.
References:
1. Raghu Ramkrishanan, Johannes Gehrke 4 th Edition “Database Management Systems” 2. AviSilberschatz , Henry
F. Korth , S. Sudarshan, “Database System Concepts, Sixth Edition”, ISBN-13: 978-93-3290-138-4, MCGraw Hill
21
Frequently Asked Questions
Q. No Questions
1 What is ER Diagram?
2 What are different graphical notations used?
3 Explain data model with suitable example.
4 Explain Specialization and Generalization?
5 What is importance of ER diagram?
22
ASSIGNMENT NO. 5
Aim
Design and implement a database (for assignment no 4) using DDL statements and apply normalization on
the.
Objective
Understand and design Database and apply normalization.
Theory
MySQL uses many different data types broken into three categories: numeric, date and time, and string
types.
MySQL uses all the standard ANSI SQL numeric data types, so if you're coming to MySQL from a
different database system, these definitions will look familiar to you. The following list shows the common
numeric data types and their descriptions:
INT - A normal-sized integer that can be signed or unsigned. If signed, the allowable range is from -
2147483648 to 2147483647. If unsigned, the allowable range is from 0 to 4294967295. You can specify a
width of up to 11 digits.
TINYINT - A very small integer that can be signed or unsigned. If signed, the allowable range is from -128
to 127. If unsigned, the allowable range is from 0 to 255. You can specify a width of up to 4 digits.
SMALLINT - A small integer that can be signed or unsigned. If signed, the allowable range is from -32768
to 32767. If unsigned, the allowable range is from 0 to 65535. You can specify a width of up to 5 digits.
MEDIUMINT - A medium-sized integer that can be signed or unsigned. If signed, the allowable range is
from -8388608 to 8388607. If unsigned, the allowable range is from 0 to 16777215. You can specify a width
of up to 9 digits.
BIGINT - A large integer that can be signed or unsigned. If signed, the allowable range is from -
9223372036854775808 to 9223372036854775807. If unsigned, the allowable range is from 0 to
18446744073709551615. You can specify a width of up to 20 digits.
FLOAT(M,D) - A floating-point number that cannot be unsigned. You can define the display length (M) and
the number of decimals (D). This is not required and will default to 10,2, where 2 is the number of decimals
and 10 is the total number of digits (including decimals). Decimal precision can go to 24 places for a FLOAT.
DOUBLE(M,D) - A double precision floating-point number that cannot be unsigned. You can define the
display length (M) and the number of decimals (D). This is not required and will default to 16,4, where 4 is
the number of decimals. Decimal precision can go to 53 places for a DOUBLE. REAL is a synonym for
DOUBLE.
DECIMAL(M,D) - An unpacked floating-point number that cannot be unsigned. In unpacked decimals, each
decimal corresponds to one byte. Defining the display length (M) and the number of decimals (D) is required.
NUMERIC is a synonym for DECIMAL.
DATE - A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example, December
30th, 1973 would be stored as 1973-12-30.
DATETIME - A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-01-01
00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30th, 1973 would be
stored as 1973-12-30 15:30:00.
23
TIMESTAMP - A timestamp between midnight, January 1, 1970 and sometime in 2037. This looks like the
previous DATETIME format, only without the hyphens between numbers; 3:30 in the afternoon on
December 30th, 1973 would be stored as 19731230153000 ( YYYYMMDDHHMMSS ).
TIME - Stores the time in HH:MM:SS format.
YEAR(M) - Stores a year in 2-digit or 4-digit format. If the length is specified as 2 (for example YEAR(2)),
YEAR can be 1970 to 2069 (70 to 69). If the length is specified as 4, YEAR can be 1901 to 2155. The default
length is 4.
String Types:
Although numeric and date types are fun, most data you'll store will be in string format. This list describes the
common string datatypes in MySQL.
CHAR(M) - A fixed-length string between 1 and 255 characters in length (for example CHAR(5)), right-
padded with spaces to the specified length when stored. Defining a length is not required, but the default is 1.
VARCHAR(M) - A variable-length string between 1 and 255 characters in length; for example
VARCHAR(25). You must define a length when creating a VARCHAR field.
BLOB or TEXT - A field with a maximum length of 65535 characters. BLOBs are "Binary Large Objects"
and are used to store large amounts of binary data, such as images or other types of files. Fields defined as
TEXT also hold large amounts of data; the difference between the two is that sorts and comparisons on stored
data are case sensitive on BLOBs and are not case sensitive in TEXT fields. You do not specify a length with
BLOB or TEXT.
TINYBLOB or TINYTEXT - A BLOB or TEXT column with a maximum length of 255 characters. You do
not specify a length with TINYBLOB or TINYTEXT.
MEDIUMBLOB or MEDIUMTEXT - A BLOB or TEXT column with a maximum length of 16777215
characters. You do not specify a length with MEDIUMBLOB or MEDIUMTEXT.
LONGBLOB or LONGTEXT - A BLOB or TEXT column with a maximum length of 4294967295
characters. You do not specify a length with LONGBLOB or LONGTEXT.
ENUM - An enumeration, which is a fancy term for list. When defining an ENUM, you are creating a list of
items from which the value must be selected (or it can be NULL). For example, if you wanted your field to
contain "A" or "B" or "C", you would define your ENUM as ENUM ('A', 'B', 'C') and only those values (or
NULL) could ever populate that field.
Table
Index
A database index is a data structure that improves the speed of operations in a table. Indexes can be created
using one or more columns, providing the basis for both rapid random lookups and efficient ordering of
access to records.
While creating index, it should be considered that what are the columns which will be used to make SQL
queries and create one or more indexes on those columns.
24
Practically, indexes are also type of tables, which keep primary key or index field and a pointer to each
record into the actual table.
The users cannot see the indexes, they are just used to speed up queries and will be used by Database Search
Engine to locate records very fast.
INSERT and UPDATE statements take more time on tables having indexes where as SELECT statements
become fast on those tables. The reason is that while doing insert or update, database need to insert or
update index values as well.
index_col_name:
col_name [(length)] [ASC | DESC]
index_type:
USING {BTREE | HASH}
Sequence
In MySQL, a sequence is a list of integers generated in the ascending order i.e., 1,2,3… Many applications need
sequences to generate unique numbers mainly for identification e.g., customer ID in CRM, employee number in HR,
equipment number in services management system, etc.
To create a sequence in MySQL automatically, you set the AUTO_INCREMENT attribute to a column, which
typically is a primary key column. The following rules you must follow when you use
AUTO_INCREMENT attribute:
Each table has only one AUTO_INCREMENT column whose data type is typically integer
The AUTO_INCREMENT column must be indexed, which means it can be either PRIMARY KEY or
UNIQUE index.
The AUTO_INCREMENT column must have NOT NULL constraint. When you set AUTO_INCREMENT
attribute to a column, MySQL will make it NOT NULL for you in case you don‟t define it explicitly.
Start MySQL
mysql -u root -p
DCL
25
DDL
Multinational Company Manages information of Employees. Each Employee has unique ID.
Each Employee works on project in some department.
Design ER Diagram for Employee Management System
Create tables for above.
e.g
create table Employee(empid int, ename varchar(20), doj date);
Normalization
What is Normalization?
Normalization is the process of organizing the data in the database.
Normalization is used to minimize the redundancy from a relation or set of relations. It is also used to eliminate
undesirable characteristics like Insertion, Update, and Deletion Anomalies.
Normalization divides the larger table into smaller and links them using relationships.
The normal form is used to reduce redundancy from the database table.
First Normal Form (1NF)
o A relation will be 1NF if it contains an atomic value.
o It states that an attribute of a table cannot hold multiple values. It must hold only single-valued attribute.
o First normal form disallows the multi-valued attribute, composite attribute, and their combinations.
o A relation will be in 3NF if it is in 2NF and not contain any transitive partial dependency.
o 3NF is used to reduce the data duplication. It is also used to achieve the data integrity.
o If there is no transitive dependency for non-prime attributes, then the relation must be in third normal form.
26
Frequently Asked Questions
Q. No Questions
Marking criteria.
Experiment completion (Timely)
Lab file (neatness and regularity)
Viva (from time to time)
Mock Practical Exam
Exam (end term): Practical + Viva
Assessment Methodology
Timely completion of assignment- 2marks
Program demonstration- 4 marks
Viva-voce -2 marks
Timely submission of journal- 2 marks
27
ASSIGNMENT NO. 6
Aim
Create table with primary key and foreign key constraint.
a Alter table with add and modify b. Drop Table
Objective
Understand and implement DDL statements.
Theory
MySQL uses many different data types broken into three categories: numeric, date and time, and string types.
MySQL uses all the standard ANSI SQL numeric data types, so if you're coming to MySQL from a different database
system, these definitions will look familiar to you. The following list shows the common numeric data types and their
descriptions:
INT - A normal-sized integer that can be signed or unsigned. If signed, the allowable range is from -
2147483648 to 2147483647. If unsigned, the allowable range is from 0 to 4294967295. You can specify a
width of up to 11 digits.
TINYINT - A very small integer that can be signed or unsigned. If signed, the allowable range is from -128
to 127. If unsigned, the allowable range is from 0 to 255. You can specify a width of up to 4 digits.
SMALLINT - A small integer that can be signed or unsigned. If signed, the allowable range is from -32768
to 32767. If unsigned, the allowable range is from 0 to 65535. You can specify a width of up to 5 digits.
MEDIUMINT - A medium-sized integer that can be signed or unsigned. If signed, the allowable range is
from -8388608 to 8388607. If unsigned, the allowable range is from 0 to 16777215. You can specify a width
of up to 9 digits.
BIGINT - A large integer that can be signed or unsigned. If signed, the allowable range is from -
9223372036854775808 to 9223372036854775807. If unsigned, the allowable range is from 0 to
18446744073709551615. You can specify a width of up to 20 digits.
FLOAT(M,D) - A floating-point number that cannot be unsigned. You can define the display length (M) and
the number of decimals (D). This is not required and will default to 10,2, where 2 is the number of decimals
and 10 is the total number of digits (including decimals). Decimal precision can go to 24 places for a FLOAT.
DOUBLE(M,D) - A double precision floating-point number that cannot be unsigned. You can define the
display length (M) and the number of decimals (D). This is not required and will default to 16,4, where 4 is
the number of decimals. Decimal precision can go to 53 places for a DOUBLE. REAL is a synonym for
DOUBLE.
DECIMAL(M,D) - An unpacked floating-point number that cannot be unsigned. In unpacked decimals, each
decimal corresponds to one byte. Defining the display length (M) and the number of decimals (D) is required.
NUMERIC is a synonym for DECIMAL.
DATE - A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example, December
30th, 1973 would be stored as 1973-12-30.
DATETIME - A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-01-01
00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30th, 1973 would be
stored as 1973-12-30 15:30:00.
28
TIMESTAMP - A timestamp between midnight, January 1, 1970 and sometime in 2037. This looks like the
previous DATETIME format, only without the hyphens between numbers; 3:30 in the afternoon on
December 30th, 1973 would be stored as 19731230153000 ( YYYYMMDDHHMMSS ).
TIME - Stores the time in HH:MM:SS format.
YEAR(M) - Stores a year in 2-digit or 4-digit format. If the length is specified as 2 (for example YEAR(2)),
YEAR can be 1970 to 2069 (70 to 69). If the length is specified as 4, YEAR can be 1901 to 2155. The default
length is 4.
String Types:
Although numeric and date types are fun, most data you'll store will be in string format. This list describes the
common string datatypes in MySQL.
CHAR(M) - A fixed-length string between 1 and 255 characters in length (for example CHAR(5)), right-
padded with spaces to the specified length when stored. Defining a length is not required, but the default is 1.
VARCHAR(M) - A variable-length string between 1 and 255 characters in length; for example
VARCHAR(25). You must define a length when creating a VARCHAR field.
BLOB or TEXT - A field with a maximum length of 65535 characters. BLOBs are "Binary Large Objects"
and are used to store large amounts of binary data, such as images or other types of files. Fields defined as
TEXT also hold large amounts of data; the difference between the two is that sorts and comparisons on stored
data are case sensitive on BLOBs and are not case sensitive in TEXT fields. You do not specify a length with
BLOB or TEXT.
TINYBLOB or TINYTEXT - A BLOB or TEXT column with a maximum length of 255 characters. You do
not specify a length with TINYBLOB or TINYTEXT.
MEDIUMBLOB or MEDIUMTEXT - A BLOB or TEXT column with a maximum length of 16777215
characters. You do not specify a length with MEDIUMBLOB or MEDIUMTEXT.
LONGBLOB or LONGTEXT - A BLOB or TEXT column with a maximum length of 4294967295
characters. You do not specify a length with LONGBLOB or LONGTEXT.
ENUM - An enumeration, which is a fancy term for list. When defining an ENUM, you are creating a list of
items from which the value must be selected (or it can be NULL). For example, if you wanted your field to
contain "A" or "B" or "C", you would define your ENUM as ENUM ('A', 'B', 'C') and only those values (or
NULL) could ever populate that field.
Table
Index
A database index is a data structure that improves the speed of operations in a table. Indexes can be created
using one or more columns, providing the basis for both rapid random lookups and efficient ordering of
access to records.
While creating index, it should be considered that what are the columns which will be used to make SQL
queries and create one or more indexes on those columns.
29
Practically, indexes are also type of tables, which keep primary key or index field and a pointer to each
record into the actual table.
The users cannot see the indexes, they are just used to speed up queries and will be used by Database Search
Engine to locate records very fast.
INSERT and UPDATE statements take more time on tables having indexes where as SELECT statements
become fast on those tables. The reason is that while doing insert or update, database need to insert or
update index values as well.
index_col_name:
col_name [(length)] [ASC | DESC]
index_type:
USING {BTREE | HASH}
Sequence
In MySQL, a sequence is a list of integers generated in the ascending order i.e., 1,2,3… Many applications need
sequences to generate unique numbers mainly for identification e.g., customer ID in CRM, employee number in HR,
equipment number in services management system, etc.
To create a sequence in MySQL automatically, you set the AUTO_INCREMENT attribute to a column, which
typically is a primary key column. The following rules you must follow when you use
AUTO_INCREMENT attribute:
Each table has only one AUTO_INCREMENT column whose data type is typically integer
The AUTO_INCREMENT column must be indexed, which means it can be either PRIMARY KEY or
UNIQUE index.
The AUTO_INCREMENT column must have NOT NULL constraint. When you set AUTO_INCREMENT
attribute to a column, MySQL will make it NOT NULL for you in case you don‟t define it explicitly.
Start MySQL
mysql -u root -p
DCL
DDL
1 use mydb;
2 create table Department(did int primary key, dname varchar(20));
3 create table Employee(empid int primary key auto_increment, ename varchar(20) not null, contactno int unique,
salary int, did int, check (salary>15000), foreign key(did) references Department(did));
4. drop table employee;
5. create table Project(Pid int primary key, Pname varchar(20), LocationId int);
6. alter table Employee add Pid int;
7. desc Employee;
8. alter table Employee add foreign key(Pid) references Project(Pid);
9. alter table Project drop LocationId;
10 alter table Project modify Pname varchar(50);
Example of composite key
11. create table Emp(empid int, name varchar(20), primary key(empid, name));
Q. No Questions
31
Marking criteria.
Experiment completion (Timely)
Lab file (neatness and regularity)
Viva (from time to time)
Mock Practical Exam
Exam (end term): Practical + Viva
Assessment Methodology
Timely completion of assignment- 2marks
Program demonstration- 4 marks
Viva-voce -2 marks
Timely submission of journal- 2 marks
32
ASSIGNMENT NO. 7
Aim
Perform following SQL queries on the database created in assignment 1.
• Implementation of relational operators in SQL
• Boolean operators and pattern matching
• Arithmetic operations and built in functions
• Group functions
• Processing Date and Time functions
• Complex queries and set operators
Objective
Understand and implement DML statements.
Theory
Data Manipulation Language (DML) allows you to modify the database instance by inserting, modifying, and
deleting its data. It is responsible for performing all types of data modification in a database.
There are three basic constructs which allow database program and user to enter data and information are:
INSERT
UPDATE
DELETE
Insert
INSERT INTO table_name
(col1, col2,…..)
values
(col1_value, col2_value, ……)
Update
update table_name
set
column_name::expression
….
where condition
Delete
delete from table_name
where condition;
MySQL Inbuilt Functions
The MID() function extracts a substring from a string (starting at any position).
33
STRCMP(string1, string2)
The SUBSTR() function extracts a substring from a string (starting at any position).
SUBSTR(string, start, length)
The LCASE() function converts a string to lower-case.
LCASE(text)
The ABS() function returns the absolute (positive) value of a number.
ABS(number)
The DATE() function extracts the date part from a datetime expression.
DATE(expression)
The NOW() function returns the current date and time.
NOW()
The TIME() function extracts the time part from a given time/datetime.
TIME(expression)
The BIN() function returns a binary representation of a number, as a string value.
BIN(number)
Aggregate Functions
The data that you need is not always stored in the tables. However, you can get it by performing the
calculations of the stored data when you select it.
For example, you cannot get the total amount of each order by simply querying from the order details table
because the order details table stores only quantity and price of each item. You have to select the quantity and
price of an item for each order and calculate the order‟s total.
By definition, an aggregate function performs a calculation on a set of values and returns a single value.
MySQL provides many aggregate functions that include AVG, COUNT, SUM, MIN, MAX, etc. An aggregate
function ignores NULL values when it performs calculation except for the COUNT function.
AVG function
The AVG function calculates the average value of a set of values. It ignores NULL values in the calculation.
SUM function
The SUM function returns the sum of a set of values. The SUM function ignores NULL values. If no matching
row found, the SUM function returns a NULL value.
MAX function
34
MIN function
Nested Queries
A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the
WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be
retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators
like =, <, >, >=, <=, IN, BETWEEN, etc.
There are a few rules that subqueries must follow −
Subqueries must be enclosed within parentheses.
A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query
for the subquery to compare its selected columns.
An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY.
The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery.
Subqueries that return more than one row can only be used with multiple value operators such as the IN
operator.
The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or
NCLOB.
A subquery cannot be immediately enclosed in a set function.
The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be used
within the subquery.
Example Queries:
35
5 select * from employee where salary>20000 and pid=102;
6 select * from employee where did<>11;
7 select * from employee where doj>='2012-01-01' and doj<='2012-12-31';
8 select * from employee where doj>='2012-01-01' and doj<='2012-12-31' and did=12;
9 select * from employee where doj between '2012-01-01' and '2012-12-31';
Inbuilt Functions
select length(EName) from Employee;
select ucase(EName) from Employee;
select lcase(EName) from Employee;
select abs(salary) from Employee;
Join
Natural Join
select * from Employee natural join Department;
Inner Join
select * from Employee inner join Department on Employee.DID=Department.DID;
Outer Join
select * from Employee left join Department on Employee.DID=Department.DID;
select * from Employee right join Department on Employee.DID=Department.DID;
Output
References:
1. Raghu Ramkrishanan, Johannes Gehrke 4 th Edition “Database Management Systems” 2. Avi Silberschatz , Henry
F. Korth , S. Sudarshan, “Database System Concepts, Sixth Edition”, ISBN-13: 978-93-3290-138-4, MCGraw Hill
Q. No Questions
1 Explain DML
2 Explain syntax of select query with suitable exxample?
3 Explain syntax to check null values
4 Explain significance of % and _
37
d. Input: Write input test data/ or program that are used to test program objective to see whether program is
achieving the given objective or not.
e. Output: describe the results in few lines
f. Conclusion: Write complete conclusion whether what the student has learned from this experiment.
g. Source Code: Submit in the form of soft copies.
Marking criteria.
Experiment completion (Timely)
Lab file (neatness and regularity)
Viva (from time to time)
Mock Practical Exam
Exam (end term): Practical + Viva
Assessment Methodology
Timely completion of assignment- 2marks
Program demonstration- 4 marks
Viva-voce -2 marks
Timely submission of journal- 2 marks
38
ASSIGNMENT NO. 8
Aim
Objective
Understand and implement DDL statements to demonstrate views.
Theory
MySQL View:
A database view is a virtual table or logical table which is defined as a SQL SELECT query with joins. Because a
database view is similar to a database table, which consists of rows and columns, so you can query data against it.
You cannot create an index on a view. MySQL uses indexes of the underlying tables when you query data
against the views that use the merge algorithm. For the views that use the temptable algorithm, indexes are
not utilized when you query data against the views.
You cannot use subqueries in the FROM clause of the SELECT statement defined the view before MySQL
5.7.7
If you drop or rename tables that a view is based on, MySQL does not issue any errors. However, MySQL
does invalidate the view. You can use the CHECK TABLE statement to check whether the view is valid.
A simple view can be updatable. A view created based on a complex SELECT statement with join,
subquery, etc., cannot be updatable
Syntax
create view view_name as select query;
Example ;
Simple View
create view v1 as select empname, address, salary from employee;
create view v4 as select * from Employee where salary in (select max(salary) from Employee);
39
Output
Create view.
References:
1. Raghu Ramkrishanan, Johannes Gehrke 4 th Edition “Database Management Systems” 2. Avi Silberschatz , Henry
F. Korth , S. Sudarshan, “Database System Concepts, Sixth Edition”, ISBN-13: 978-93-3290-138-4, MCGraw Hill
Q. No Questions
Marking criteria.
Experiment completion (Timely)
Lab file (neatness and regularity)
Viva (from time to time)
Mock Practical Exam
Exam (end term): Practical + Viva
Assessment Methodology
Timely completion of assignment- 2marks
Program demonstration- 4 marks
Viva-voce -2 marks
Timely submission of journal- 2 marks
Aim
Write and execute PL/SQL stored procedure and function to perform a suitable task on the database.
Objective
To study and implement function and procedure for suitable database application.
Theory
A database stored program (stored module or stored routine) is a computer program that is stored within and executes
within the database server.
When program is executed, it is executed within the memory address of a database server process or thread.
Syntax
Call example();
mysql> delimiter $$
mysql> drop procedure if exists helloworld$$
Query OK, 0 rows affected, 1 warning (0.00 sec)
41
Query OK, 0 rows affected (0.03 sec)
42
Procedure to get the all employee details
create procedure proc_emp()
begin
select * from emp;
end$$
43
mysql> insert into product values(1, 900)$
Query OK, 1 row affected (0.02 sec)
mysql>
44
PL/SQL Function
RETURN (status);
END$$
Output
References:
1. Raghu Ramkrishanan, Johannes Gehrke 4 th Edition “Database Management Systems” 2. Avi Silberschatz , Henry
F. Korth , S. Sudarshan, “Database System Concepts, Sixth Edition”, ISBN-13: 978-93-3290-138-4, MCGraw Hill
Q. No Questions
45
f. Conclusion: Write complete conclusion whether what the student has learned from this experiment.
g. Source Code: Submit in the form of soft copies.
Marking criteria.
Experiment completion (Timely)
Lab file (neatness and regularity)
Viva (from time to time)
Mock Practical Exam
Exam (end term): Practical + Viva
Assessment Methodology
Timely completion of assignment- 2marks
Program demonstration- 4 marks
46
ASSIGNMENT NO. 10
Aim
Objective
Theory
• Stored programs that are executed in respnse to some kind of event that occures in database.
• Triggers fires in response to a DML statement (insert, update delete) on specified table.
• Powerful mechanism for ensuring the integrity of data
• Before|after specifies weather triger fires before of after the DML statement itself has been executed.
• Update|insert|delete specifies DML statement to which trigger is associated
• On table_name associates the trigger with a specific table
• For each row indicates that the trigger will be executed once for every row affected by the DML statement
• With after we are not able to modify the values about to modify the values about to be inserted into or
updated with the table in question
47
CREATE TABLE employees_audit (
id int(11) NOT NULL AUTO_INCREMENT,
employeeNumber int(11) NOT NULL,
lastname varchar(50) NOT NULL,
changedon datetime DEFAULT NULL,
action varchar(50) DEFAULT NULL,
PRIMARY KEY (id)
);
DELIMITER $$
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employees
FOR EACH ROW BEGIN
Output
References:
1. Raghu Ramkrishanan, Johannes Gehrke 4 th Edition “Database Management Systems” 2. Avi Silberschatz , Henry
F. Korth , S. Sudarshan, “Database System Concepts, Sixth Edition”, ISBN-13: 978-93-3290-138-4, MCGraw Hill
Q. No Questions
48
description, method used, fundamental concept and desired output format.
b. Theory: Write brief theory related to practical.
c. Algorithm: Write Algorithm for given task.
d. Input: Write input test data/ or program that are used to test program objective to see whether program is
achieving the given objective or not.
e. Output: describe the results in few lines
f. Conclusion: Write complete conclusion whether what the student has learned from this experiment.
g. Source Code: Submit in the form of soft copies.
Marking criteria.
Experiment completion (Timely)
Lab file (neatness and regularity)
Viva (from time to time)
Mock Practical Exam
Exam (end term): Practical + Viva
Assessment Methodology
Timely completion of assignment- 2marks
Program demonstration- 4 marks
Viva-voce -2 marks
Timely submission of journal- 2 marks
49
ASSIGNMENT NO. 11
Aim
Objective
To study and implement cursor.
Theory
A database stored program (stored module or stored routine) is a computer program that is stored within and executes
within the database server.
When program is executed, it is executed within the memory address of a database server process or thread.
Syntax
Call example1();
To handle a result set inside a stored procedure, you use a cursor. A cursor allows you to iterate a set of
rows returned by a query and process each row accordingly.
Read only: you cannot update data in the underlying table through the cursor.
Non-scrollable: you can only fetch rows in the order determined by the SELECT statement. You cannot fetch
rows in the reversed order. In addition, you cannot skip rows or jump to a specific row in the result set.
Asensitive: there are two kinds of cursors: asensitive cursor and insensitive cursor. An asensitive cursor
points to the actual data, whereas an insensitive cursor uses a temporary copy of the data. An asensitive
cursor performs faster than an insensitive cursor because it does not have to make a temporary copy of data.
However, any change that made to the data from other connections will affect the data that is being used by
an asensitive cursor, therefore, it is safer if you don‟t update the data that is being used by an asensitive
cursor. MySQL cursor is asensitive.
Working of Cursor
50
DECLARE cursor_name CURSOR FOR SELECT_statement;
OPEN cursor_name;
CLOSE cursor_name;
Delimiter $$
Drop procedure if exists empcursor $$
Create procedure empcursor()
Begin
Declare eno int;
Declare ename varchar(20);
Declare esal int;
Declare flag int default 0;
Declare c1 cursor for select eid, empname, Salary from employee;
Open c1;
emp_loop : loop
Fetch c1 into eno, ename, esal;
If flag = 1 then
Leave emp_loop;
End if;
Output
References:
1. Raghu Ramkrishanan, Johannes Gehrke 4 th Edition “Database Management Systems” 2. Avi Silberschatz , Henry
F. Korth , S. Sudarshan, “Database System Concepts, Sixth Edition”, ISBN-13: 978-93-3290-138-4, MCGraw Hill
Ms 51
Frequently Asked Questions
Q.No Questions
1 Explain cursors with example?
2 Explain implicit and explicit cursor?
Marking criteria.
Experiment completion (Timely)
Lab file (neatness and regularity)
Viva (from time to time)
Mock Practical Exam
Exam (end term): Practical + Viva
Assessment Methodology
Timely completion of assignment- 2marks
Program demonstration- 4 marks
Viva-voce -2 marks
Timely submission of journal- 2 marks
Ms 52