DBMS Lab Manual - 23-24
DBMS Lab Manual - 23-24
LAB MANUAL
OF
Database Management System
(214456)
Subject Teachers:
1) Prof. M. A. Gade.
3. Study of SQLite: What is SQLite? Uses of Sqlite. Building and installing SQLite
Group B: MySQL
4. Design any database with at least 3 entities and relationships between them.
Draw suitable ER/EER diagram for the system.
6. Create Table with primary key and foreign key constraints. a. Alter table with
add n modify b. Drop table
8. Execute DDL/DML statements which demonstrate the use of views. Update the
base table using its corresponding view. Also consider restrictions on updatable
views and perform view creation from multiple tables.
Group C: PL/SQL
9. Write and execute PL/SQL stored procedure and function to perform a suitable
task on the database. Demonstrate its use.
10. Write and execute suitable database triggers .Consider row level and statement
level triggers.
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.
What is DBMS?
A software system that enables users to define, create, maintain, and control access to the database.
The DBMS is the software that interacts with the users‟ application programs and the database.
Typically, a DBMS provides the following facilities:
It allows users to define the database, usually through a Data Definition Language (DDL).
The DDL allows users to specify the data types and structures and the constraints on the
data to be stored in the database.
It allows users to insert, update, delete, and retrieve data from the database, usually through
a Data Manipulation Language (DML). The most common query language is the
Structured Query Language (SQL, pronounced „S-Q-L‟, or sometimes „See-Quel‟), which
is now both the formal and de facto standard language for relational DBMSs.
Disadvantages
– Complexity
– Size
– Additional hardware costs
– Cost of DBMS
– Performance
– Higher impact of failure
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 relation with collection of data.
Column: It is a field or attribute for that relation.
Row: Tuple or record) is a group of related data,
Primary key: A candidate key chosen as the principal means of identifying tuples within
a relation
Foreign key: A relation schema may have an attribute that corresponds to the primary
key of another relation. The attribute is called a foreign key.
DBMS: A database management system (DBMS) is system software for creating and managing
databases. The DBMS provides users and programmers with a systematic way to create, retrieve,
update and manage data.A DBMS makes it possible for end users to create, read, update and
delete data in a database. The DBMS essentially serves as an interface between the database and
end users or application programs, ensuring that data is consistently organized and remains easily
accessible.
RELATIONAL DATABASE:
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and
for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft
Access.
A Relational database management system (RDBMS) is a database management system
(DBMS) that is based on the relational model
RDBMSs have been a common choice for the storage of information in new databases used for
financial records, manufacturing and logistical information, personnel data, and other
applications since the 1980s. Relational databases have often replaced legacy hierarchical
databases and network databases because they are easier to understand and use. However,
relational databases have received unsuccessful challenge attempts by object database
management systems in the 1980s and 1990s (which were introduced trying to address the so-
called object-relational impedance mismatch between relational databases and object-oriented
application programs) and also by XML database management systems in the 1990s.
DBMS LAB Page 6
Despite such attempts, RDBMSs keep most of the market share, which has also grown over the
years.
SQL:
SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to
communicate with a database. According to ANSI (American National Standards Institute), it is
the standard language for relational database management systems. SQL statements are used to
perform tasks such as update data on a database, or retrieve data from a database. Some common
relational database management systems that use SQL are: Oracle, Sybase, Microsoft SQL
Server, Access, Ingres, etc. Although most database systems use SQL, most of them also have
their own additional proprietary extensions that are usually only used on their system. However,
the standard SQL commands such as "Select", "Insert", "Update", "Delete", "Create", and "Drop"
can be used to accomplish almost everything that one needs to do with a database. This tutorial
will provide you with the instruction on the basics of each of these commands as well as allow
you to put them to practice using the SQL Interpreter.
MySQL Database:
“MySQL is a system that helps store and manage data efficiently. Database generally stores data in
a structured fashion. It is written in C and C++, and it has been tested with a variety of compilers to
check for bugs and inconsistencies.”
MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses.
MySQL is developed, marketed, and supported by MySQL AB, which is a Swedish
company. MySQL is becoming so popular because of many good reasons:
MySQL is released under an open-source license. So you have nothing to pay to use it.
MySQL is a very powerful program in its own right. It handles large subset of the
functionality of the most expensive and powerful database packages.
MySQL uses a standard form of the well-known SQL data language.
MySQL works on many operating systems and with many languages including PHP,
PERL, C, C++, JAVA, etc.
MySQL works very quickly and works well even with large datasets.
MySQL is very friendly to PHP, the most appreciated language for web development.
MySQL supports large databases, upto50millionrowsormoreinatable. The default file size
limit for atableis4GB, but you can increase this (if your operating system can handle it) to
a theoretical limit of 8million terabytes(TB).
MySQL is customizable. The open-source GPL license allows programmers to modify the
MySQL software to fit their own specific environments
High Performance
MySQL is faster, more reliable, and cheaper because of its unique storage engine architecture. It
provides very high-performance results in comparison to other databases without losing an
essential functionality of the software. It has fast loading utilities because of the different cache
memory. MySQL stores data efficiently in the memory ensuring that data is consistent, and not
redundant. Hence, data access and manipulation using MySQL is quick.
DBMS LAB Page 8
.
CONCLUSION:
The study of MYSQL open source software has been done. Also its various features like
scalability, security etc studied.
AIM: Install and configure client and server of MySQL.(Show all commands and necessary
steps for installation and configuration)
PROBLEM STATEMENT / DEFINITION:
MySQL (RDBMS)
OBJECTIVE:
Ease of Management – The software very easily gets downloaded and also uses an event scheduler
to schedule the tasks automatically.
Robust Transactional Support – Holds the ACID (Atomicity, Consistency, Isolation, Durability)
property, and also allows distributed multi-version support.
Comprehensive Application Development – MySQL has plugin libraries to embed the database
into any application. It also supports stored procedures, triggers, functions, views and many more
for application development. You can refer to the RDS Tutorial, to understand Amazon’s
RDBMS.
High Performance – Provides fast load utilities with distinct memory caches and table index
partitioning.
Open Source & 24 * 7 Support – This RDBMS can be used on any platform and offers 24*7
support for open source and enterprise edition.
Secure Data Protection – MySQL supports powerful mechanisms to ensure that only authorized
users have access to the databases.
High Availability – MySQL can run high-speed master/slave replication configurations and it
offers cluster servers.
Scalability & Flexibility – With MySQL you can run deeply embedded applications and create
data warehouses holding a humongous amount of data.
After accepting the Oracle license agreement terms, the first screen you encounter allows you to define
which MySQL products are going to be installed. You can choose between several predefined options
or create your custom setup type.
Developer Default installs all the tools you need to develop and micromanage your MySQL
databases effectively.
Server Only is used to install an instance of the MySQL Server and forgo other MySQL
products.
Client Only installs all products except the MySQL Server and associated tools.
The Full configuration installs all available MySQL products.
A Custom setup allows you to select the individual elements that are to be installed and alter predefined
default settings.
In the example below, we select the Server Only option and click Next.
1. High Availability
The first configuration option affects database availability. It allows you to decide if you want to set up
a Standalone MySQL Server or an InnoDB server cluster to improve availability. In this instance, we
selected the classic, single server option.
The Type and Networking section is used to define several essential features. The Config Type option
lets you choose between three server configuration types. Development Computer, Server Computer,
and Dedicated Computer define whether the server is dedicated solely to running your MySQL
database or is going to share the underlying system with other applications.
The Type and Networking tab can also define the port the MySQL server is listening on. The default
setting is port number 3306 and can be changed to suit your needs.
By checking the Show Advanced and Logging Option box, you can set additional logging options at a
later stage.
DBMS LAB Page 13
Click Next once you’ve selected the options you feel meet your requirements.
3. Authentication Method
It is possible to choose between two authentication methods, the recommended Strong Password
Encryption, and the Legacy Authentication Method. Select the recommended Use Strong Password
Authentication option.
You are now prompted to enter a password for your MySQL root user. You can also create additional
roles for various users and purposes. This is only an initial setup, and credentials can be edited once the
installation is complete.
By defining MySQL as a Windows Service, it can now start automatically whenever the Windows
system boots. If you decide to start MySQL as an executable application, you would need to configure
it manually.
6. Apply Configuration
You have successfully configured the MySQL server and need to confirm for the MySQL Installer to
apply the configuration. An overview of the configurations steps appears on the screen.
Click Execute to apply the configuration.
Clipboard.
If you need to start the MySQL Server on Windows for the first time enter the following command in
the Windows Command Prompt:
The path in this command is the default installation folder. In case you have installed MySQL in a
different folder, the command needs to reflect that to launch the mysqld executable file successfully.
The --console option displays output directly on your console. Omitting this option sends the output
directly to the MySQL logs.
Conclusion
Installing MySQL on a Windows server is simple when using the MySQL Installer tool.
AIM: Study the SQLite database and its uses and installation.
OBJECTIVE:
THEORY:
SQLite:
SQLite is a self-contained, high-reliability, embedded, full-featured, public-domain, SQL
database engine. SQLite is the most used database engine in the world.
SQLite is ACID-compliant and implements most of the SQL standard, using a dynamically and
weakly typed SQL syntax that does not guarantee the domain integrity.[5]
SQLite is a popular choice as embedded database software for local/client storage in application
software such as web browsers. It is arguably the most widely deployed database engine, as it is
used today by several widespread browsers, operating systems, and embedded systems (such as
mobile phones), among others.[6] SQLite has bindings to many programming languages.
Installing SQLite:
1. type in the following command –
Uses of SQLite:
SQLite is not directly comparable to client/server SQL database engines such as MySQL,
Oracle, PostgreSQL, or SQL Server since SQLite is trying to solve a different problem.
Client/server SQL database engines strive to implement a shared repository of enterprise data.
They emphasis scalability, concurrency, centralization, and control. SQLite strives to provide
local data storage for individual applications and devices. SQLite emphasizes economy,
efficiency, reliability, independence, and simplicity.
SQLite does not compete with client/server databases.
Websites
Data analysis
Server-side database
File archives
REFERENCE URL:
1. https://sysads.co.uk/2014/08/05/install-sqlite-database-browser-3-2-0-on-ubuntu-14-04/
2. http://www.sqlitetutorial.net/
CONCLUSION:
Studied of installation and configuration steps of SQLite database.
AIM:
Design any database with at least 3 entities and relationships between them. Draw suitable ER/EER
diagram for the system.
OBJECTIVE:
THEORY:
Entity set: An entity set is a set of entities of the same type that share the same properties.
Example: set of all persons, companies, trees, holidays
Symbolic notations:
Components to draw entity relationship diagram.
Rectangles: represent entity sets.
Diamonds: represent relationship sets.
Lines: link attributes to entity sets and entity sets to relationship sets.
Ellipses: represent attributes
Double ellipses: represent multivalued attributes.
Dashed ellipses: denote derived attributes.
Underline: indicates primary key attributes (will study later)
1. Specialization:
Top-down design process; we designate sub groupings within an entity set that
are distinctive from other entities in the set. These sub groupings become
lower-level entity sets that have attributes or participate in relationships that do
not apply to the higher- level entity set. Depicted by a triangle component
labeled ISA (E.g. customer “is a” person).
2. Attribute inheritance – a lower-level entity set inherits all the attributes
and relationship participation of the higher-level entity set to which it is
linked
3. Generalization:
A bottom-up design process – combine a number of entities sets that share the
same features into a higher-level entity set. Specialization and generalization
are simple inversions of each other; they are represented in an E-R diagram in
the same way. The terms specialization and generalization are used
interchangeably.
4. Aggregation:
Consider the ternary relationship works-on, which we saw earlier. Suppose we
want to record managers for tasks performed by an employee at a branch
Relationship sets works-on and manages represent overlapping information.
Every manages relationship corresponds to a works- on relationship
Primary keys allow entity sets and relationship sets to be expressed uniformly as tables which
represent the contents of the database. A database which conforms to an E-R diagram can be
represented by a collection of tables. For each entity set and relationship set there is a unique table
which is assigned the name of the corresponding entity set or relationship set. Each table has a
number of columns (generally corresponding to attributes), which have unique names.Converting
an E-R diagram to a table format is the basis for deriving a relational database design from an E-
R diagram.A strong entity set reduces to a table with the same attributes.
Ex. Customer (customer-id, customer-name, customer-street, customer-city)Schema can be reduce
as follows.
CONCLUSION:
Understand to draw ER diagram and EER diagram for the given database.
AIM:
Design and implement a database using DDL statements and apply normalization on them
Design and implement a database using DDL statements and apply normalization on it.
OBJECTIVE:
THEORY:
Introduction to SQL:
The Structured Query Language (SQL) comprises one of the fundamental building blocks of
modern database architecture. SQL defines the methods used to create and manipulate relational
databases on all major platforms. SQL comes in many flavors. Oracle databases utilize their
proprietary PL/SQL. Microsoft SQL Server makes use of Transact-SQL. However, all of these
variations are based upon the industry standard ANSI SQL.
SQL commands can be divided into two main sublanguages.
1. Data Definition Language
2. Data Manipulation Language
Example 2
Example
ALTER TABLE personal_info ADD salary money null
This example adds a new attribute to the personal_info table -- an employee's salary. The "money"
argument specifies that an employee's salary will be stored using a dollars and cents
format. Finally, the "null” keyword tells the database that it's OK for this field to contain no value
for any given employee.
d. TRUNCATE:
It is used to delete all the rows from the table and free the space containing the table.
Syntax:
Example:
Example
All Basic commands of MySql .Like :
mysql> create database ManageCust;
Query OK, 1 row affected (0.00 sec) // to user ur own database,
other than default.
mysql> use ManageCust;
Database changed
mysql> QUIT To exit the MySQL Shell, just type QUIT or EXIT:
mysql> exit
mysql> SHOW TABLES;
mysql> DESCRIBE <Table Name>;
CONCLUSION:
The structure of table is designed by applying all the DDL commands.
AIM: Create Table with primary key and foreign key constraints.
OBJECTIVE:
THEORY:
DATA INTEGRITY:
Enforcing data integrity ensures the quality of the data in the database. For example, if an employee
is entered with an employee_id value of “123”, the database should not allow another employee
to have an ID with the same value. Two important steps in planning tables are to identify valid
values for a column and to decide how to enforce the integrity of the data in the column. Data
integrity falls into four categories:
• Entity integrity
• Domain integrity
• Referential integrity
• User-defined integrity
There are several ways of enforcing each type of integrity.
ENTITY INTEGRITY:
Entity integrity defines a row as a unique entity for a particular table. Entity integrity enforces the
integrity of the identifier column(s) or the primary key of a table (through indexes, UNIQUE
constraints, PRIMARY KEY constraints, or IDENTITY properties).
DBMS LAB Page 29
DOMAIN INTEGRITY:
Domain integrity is the validity of entries for a given column. You can enforce domain integrity
by restricting the type (through data types), the format (through CHECK constraints and rules), or
the range of possible values (through FOREIGN KEY constraints, CHECK constraints,
DEFAULT definitions, NOT NULL definitions, and rules).
REFERENTIAL INTEGRITY:
Referential integrity preserves the defined relationships between tables when records are entered
or deleted. In Microsoft® SQL Server™, referential integrity is based on relationships between
foreign keys and primary keys or between foreign keys and unique keys. Referential integrity
ensures that key values are consistent across tables. Such consistency requires that there be no
references to nonexistent values and that if a key value changes, all references to it change
consistently throughout the database.
Definition: - The primary key of a relational table uniquely identifies each record in the table. A
primary key constraint ensures no duplicate values are entered in particular columns and that
NULL values are not entered in those columns.
Properties :
1. No duplicate values are allowed, i.e. Column assigned as primary key should have UNIQUE values
only.
2. NO NULL values are present in column with Primary key. Hence there is Mandatory value in
column having Primary key.
3. Only one primary key per table exist although Primary key may have multiple columns.
4. No new row can be inserted with the already existing primary key.
5. Classified as : a) Simple primary key that has a Single column 2) Composite primary key has
Multiple column.
6. Defined in Create table / Alter table statement.
The primary key can be created in a table using PRIMARY KEY constraint. It can be created at two
levels.
- Column
- Table.
b. UNIQUE CONSTRAINT:
This constraint ensures that no duplicate values are entered in those columns.
c. CHECK CONSTRAINT:
The CHECK constraint enforces column value restrictions. Such constraints can restrict a column,
for example, to a set of values, only positive numbers, or reasonable dates.not working in mysql.
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in
another table.
The table with the foreign key is called the child table, and the table with the primary key is called the
referenced or parent table.
Persons Table
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20
Orders Table
DBMS LAB Page 32
OrderID OrderNumber PersonID
1 77895 3
2 44678 3
3 22456 2
4 24562 1
The above table "PersonID" column in the "Orders" table points to the "PersonID" column in the
"Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key column,
because it has to be one of the values contained in the parent table.
The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table is
created:
To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is already
created, use the following SQL:
Assignment: 7
AIM: Write SQL queries on the database created already to implement various operations and use
built in functions in the queries.
PROBLEM STATEMENT /DEFINITION:
Write queries using all of the following operators-
DBMS LAB Page 34
Implementation of relational operators in SQL
Boolean operators and pattern matching
Arithmetic operations and built in functions
Group functions /Aggregate Functions
Processing Date and Time functions/Built in Functions
Complex queries and set operators
OBJECTIVE:
1. To understand use of various DML, and DQL statement with clause and nested queries, DCL
commands.
2. To understand use of various functions: Aggregate, Arithmetic and nested queries.
3. To understand the SQL Built in functions (now (), date (), day (), time () etc)
THEORY:
SELECT COMMAND:
The SELECT command is the most commonly used command in SQL. It allows database users to
retrieve the specific information they desire from an operational database. Syntax
SELECT A1, A2…….. FROM table name WHERE predicate
A1, A2 is the list of attributes and predicate is the condition which must be satisfied by the resulting
rows.
Example 1
It displays list of all last names in personal_info table
SELECT last_name FROM personal_info
The command shown below retrieves all of the information contained within the personal_info table.
The asterisk is used as a wildcard in SQL. This means "Select everything from the personal_info table."
Example 2
SELECT * FROM account
Finally, the WHERE clause can be used to limit the records that are retrieved to those that meet
specified criteria. The CEO might be interested in reviewing the personnel records of all highly paid
employees. The following command retrieves all of the data contained within personal_info for
records that have a salary value greater than $50,000:
Example 3
SELECT * FROM account WHERE balance > $50000
INPUT: A specific query set.
DBMS LAB Page 35
OUTPUT: Result of the given query set.
AGGREGATE FUNCTIONS:
If we want to summarize our data to produce top-level reports (For example, the purchasing manager
may not be interested in a listing of all widget sales, but may simply want to know the number of
widgets sold this month),
SQL provides aggregate functions to assist with the summarization of large volumes of data.
1. SUM:
It is used within a SELECT statement and, predictably, returns the summation of a series of values. If
the widget project manager wanted to know the total number of widgets sold to date, we could use the
Following query:
Example:
2. AVG:
The AVG (average) function works in a similar manner to provide the mathematical average of a
series of values. To find out the average amount of all orders placed on the North American continent.
Example:
SELECT AVG (balance) as AveragePrice FROM account WHERE branch-name=’delhi’;
SQL provides the COUNT function to retrieve the number of records in a table that meet given criteria.
We can use the COUNT (*) syntax alone to retrieve the number of rows in a table. Alternatively, a
WHERE clause can be included to restrict the counting to specific records.
Example:
SELECT COUNT(*) AS 'Number of Large Orders' FROM account WHERE BALANCE > 100000 ;
Above query displays how many orders are processed by company that requested over 100 widgets.
SQL provides Min and Max functions to locate the records containing the smallest and largest values
for a given expression
The MAX () function returns the largest value in a given data series. We can provide the function with
a field name to return the largest value for a given field in a table. To find the order in our database that
produced the most revenue for the company, following query will be used:
Example:
SELECT MAX (BALANCE) as ‘largest balance’ FROM account;
The MIN () function functions in the same manner, but returns the minimum value for the expression.
SQL Server comes with the following data types for storing a date or a date/time value in the database:
DBMS LAB Page 37
DATE - format YYYY-MM-DD
DATETIME - format: YYYY-MM-DD HH:MI:SS
SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS
TIMESTAMP - format: a unique number
Note: The date types are chosen for a column when you create a new table in your database!
Now we want to select the records with an OrderDate of "2008-11-11" from the table above.
OrderId ProductName
1 Geitost
3 Mozzarella di Giovanni
Now, assume that the "Orders" table looks like this (notice the time component in the "OrderDate"
column):
we will get no result! This is because the query is looking only for dates with no time portion.
Arithmetic function:
A mathematical function executes a mathematical operation usually based on input values that
are provided as arguments, and return a numeric value as the result of the operation.
Mathematical functions operates on numeric data such as decimal, integer, float, real, smallint,
and tinyint.
By default, the precision of built-in operations on float data type data is six decimal places.
The Arithmetic Operators perform the mathematical operation on the numerical data of the SQL tables.
These operators perform addition, subtraction, multiplication, and division operations on the numerical
operands.
Following are the various arithmetic operators performed on the SQL data:
The Addition Operator in SQL performs the addition on the numerical data of the database table. In
SQL, we can easily add the numerical values of two columns of the same table by specifying both the
column names as the first and second operand. We can also add the numbers to the existing numbers of
the specific column.
DBMS LAB Page 39
Syntax of SQL Addition Operator:
This example consists of an Employee_details table, which has four columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_Monthlybonus.
o Suppose, we want to add 20,000 to the salary of each employee specified in the table. Then, we
have to write the following query in the SQL:
In this query, we have performed the SQL addition operation on the single column of the given table.
o Suppose, we want to add the Salary and monthly bonus columns of the above table, then we have
to write the following query in SQL:
In this query, we have added two columns with each other of the above table.
The Subtraction Operator in SQL performs the subtraction on the numerical data of the database table.
In SQL, we can easily subtract the numerical values of two columns of the same table by specifying both
the column names as the first and second operand. We can also subtract the number from the existing
number of the specific table column.
The Multiplication Operator in SQL performs the Multiplication on the numerical data of the database
table. In SQL, we can easily multiply the numerical values of two columns of the same table by specifying
both the column names as the first and second operand.
DBMS LAB Page 40
Syntax of SQL Multiplication Operator:
The Division Operator in SQL divides the operand on the left side by the operand on the right side.
The Modulus Operator in SQL provides the remainder when the operand on the left side is divided by
the operand on the right side.
The Comparison Operators in SQL compare two different data of SQL table and check whether they
are the same, greater, and lesser. The SQL comparison operators are used with the WHERE clause in the
SQL queries
Following are the various comparison operators which are performed on the data stored in the
SQL database tables:
Functions Description
ABS() This SQL ABS() returns the absolute value of a number passed as
an argument.
CEIL() This SQL CEIL() will rounded up any positive or negative decimal
value within the function upwards.
FLOOR() The SQL FLOOR() rounded up any positive or negative decimal
DBMS LAB Page 41
value down to the next least integer value.
EXP() The SQL EXP() returns e raised to the n-th power(n is the numeric
expression), where e is the base of natural algorithm and the value
of e is approximately 2.71828183.
LN() The SQL LN() function returns the natural logarithm of n, where n
is greater than 0 and its base is a number equal to approximately
2.71828183.
MOD() This SQL MOD() function returns the remainder from a division.
POWER() This SQL POWER() function returns the value of a number raised
to another, where both of the numbers are passed as arguments.
CONCLUSION:
Understand to retrieve data from database with the help of sql statement using various operators like
arithmetic operators, group functions comparison operators etc.
Assignment: 08
AIM:
Write DDL/DML statements to create VIEWS on single and multiple tables from above DB.
What are the restrictions applicable while creating or modifying views? Demonstrate using
suitable queries.
THEORY:
VIEW:
Database view is known as a “virtual table” that allows you to query the data in it. Understanding
the database views and using them correctly are very important. In this section, we will discuss the
database views, how they are implemented in MySQL, and how to use them more effectively.
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. Most database management systems, including
MySQL, allow you to update data in the underlying tables through the database view with some
prerequisites.
A database view allows you to simplify complex queries: a database view is defined by an
SQL statement that associates with many underlying tables. You can use database view to
hide the complexity of underlying tables to the end-users and external applications.
Through a database view, you only have to use simple SQL statements instead of complex
ones with many joins.
A database view helps limit data access to specific users. You may not want a subset of
sensitive data can be queryable by all users. You can use a database view to expose only non-
sensitive data to a specific group of users.
A database view provides extra security layer. Security is a vital part of any relational
database management system. The database view provides extra security for a database
management system. The database view allows you to create the read-only
We can create View using CREATE VIEW statement. A View can be created from a single
table or multiple tables.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;
Sample Tables:
Table- student_details
Table- Student_marks
Examples:
Creating View from a single table:
In this example we will create a View named DetailsView from the table StudentDetails.
Query:
DBMS LAB Page 45
CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;
To see the data in the View, we can query the view in the same manner as we query a table.
SELECT * FROM DetailsView;
Output:
Creating View from multiple tables: In this example we will create a View named MarksView from two
tables StudentDetails and StudentMarks. To create a View from multiple tables we can simply include
multiple tables in the SELECT statement. Query:
CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
To display data of View MarksView:
SELECT * FROM MarksView;
Output:
DELETING VIEWS:
We have learned about creating a View, but what if a created View is not needed any more? Obviously we
will want to delete it. SQL allows us to delete an existing View. We can delete or drop a View using the
DROP statement.
SELECT column1,coulmn2,..
FROM table_name
WHERE condition;
For example, if we want to update the view MarksView and add the field AGE to this View
from StudentMarks Table, we can do this as:
CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS,
StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
If we fetch all the data from MarksView now as:
SELECT * FROM MarksView;
Output:
CONCLUSION:
The DML commands are implemented using views. Views are created from single
table and multiple tables as well. Alongwith it updated the views.
DBMS LAB Page 47
Assignment: 9
OBJECTIVE
To understand PL/SQL
To understand the concept of procedures /Functions
THEORY:
LANGUAGE SQL
DETERMINISTIC
BEGIN
END//
The first part of the statement creates the procedure. The next clauses defines the optional
characteristics of the procedure. Then you have the name and finally the body or routine code.
Stored procedure names are case insensitive, and you cannot create procedures with the same
name. Inside a procedure body, you can't put database-manipulation statements.Modify a Stored
Procedure
CREATE PROCEDURE proc1 (IN varname DATA-TYPE) : One input parameter. The word IN
is optional because parameters are IN (input) by default.
CREATE PROCEDURE proc1 (INOUT varname DATA-TYPE) : One parameter which is both
input and output.
Of course, you can define multiple parameters defined with different types.
IN example
DELIMITER //
BEGIN
END//
OUT example
DELIMITER //
BEGIN
END //
INOUT example
DELIMITER //
BEGIN
Step 4 - Variables
The following step will teach you how to define variables, and store values inside a procedure.
You must declare them explicitly at the start of the BEGIN/END block, along with their data types.
Once you've declared a variable, you can use it anywhere that you could use a session variable, or
literal, or column name.
DECLARE strVARCHAR(50);
Once the variables have been declared, you can assign them values using the SET or SELECT
command:
DELIMITER //
BEGIN
DECLARE strVARCHAR(50);
END //
MySQL supports the IF, CASE, ITERATE, LEAVE LOOP, WHILE and REPEAT constructs
for flow control within stored programs. We're going to review how to use IF, CASE and
WHILE specifically, since they happen to be the most commonly used statements in routines.
IF statement
With the IF statement, we can handle tasks which involves conditions:
DELIMITER //
BEGIN
IF variable1 = 0 THEN
SELECT variable1;
END IF;
IF param1 = 0 THEN
ELSE
END IF;
END //
CASE statement
The CASE statement is another way to check conditions and take the appropriate path. It's an
excellent way to replace multiple IF statements. The statement can be written in two different
ways, providing great flexibility to handle multiple conditions.
DELIMITER //
BEGIN
CASE variable1
WHEN 0 THEN
WHEN 1 THEN
ELSE
END CASE;
END //
or:
DELIMITER //
BEGIN
CASE
ELSE
END CASE;
END //
DELIMITER //
BEGIN
SET variable1 = 0;
END WHILE;
END //
Conclusion:
PL/SQL stored procedure is created and function is also created.
Write and execute PL/SQL block to implement all types of triggers on above DB.
OBJECTIVE:
To understand PL/SQL
To understand the concept of triggers, pl /sql block.
THEORY:
BEFORE UPDATE
ON account
BEGIN
IF (NEW.bal< 0) THEN
END IF;
END;
BEGIN
end;
2. Write a PL/SQL block to display the Information of given student on following table
Stud (sno, sname, address, city).
3. Write a PL/SQL block for preparing a Net Salary, given employee on following table
Emp (eno, ename, address, city)
Salary (eno, basic, da, hra, it)
Net_Salary (eno, total_allowance, total_deduction, netpay)
Notes : D.A. = 59% of basic , H.R.A. = 500, I.T. = 2% of basic
Total_Allowance = Basic + D.A. + H.R.A., Total_Deduction = I.T.
Netpay = Total_Allowance – Total_Deduction.
4. Write a PL/SQL block to raise the salary by 20% of given employee on following table.
5. Write an Implicit Cursor to accept the employee number from the user. You have to
delete this record and display the appropriate message on the following table.
Emp (eno, ename, address, city)
6. Write a Cursor to display the employee number, name, department and salary of first
employee getting the highest salary.
7. Write a Cursor to display the first five records on the following table.
CONCLUSION:
AIM:
Write and execute PL/SQL block to implement all types of cursor on above DB.
OBJECTIVE
To understand PL/SQL
To understand the concept of cursor
THEORY:
Cursor:
Oracle creates a memory area, known as the context area, for processing an SQL statement, which
contains all the information needed for processing the statement; for example, the number of rows
processed, etc.
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A
cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds
is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process the rows
returned by the SQL statement, one at a time. There are two types of cursors −
Implicit cursors
Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit
cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement. For INSERT operations, the cursor holds the data that needs to be
inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be
affected.
%FOUND
%NOTFOUND
%ISOPEN
3
Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
4
Returns the number of rows affected by an INSERT, UPDATE, or DELETE
statement, or returned by a SELECT INTO statement.
Any SQL cursor attribute will be accessed assql%attribute_name as shown below in the
example.
Example
We will be using the CUSTOMERS table we had created and used in the previous chapters.
+ + + + ++
| ID | NAME| AGE | ADDRESS | SALARY |
+ + + + ++
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi| 1500.00 |
| 3 | kaushik | 23 | Kota| 2000.00 |
| 4 | Chaitali | 25 | Mumbai| 6500.00 |
| 5 | Hardik | 27 | Bhopal| 8500.00 |
| 6 | Komal| 22 | MP| 4500.00 |
++++++
The following program will update the table and increase the salary of each customer by 500
and use the SQL%ROWCOUNTattribute to determine the number of rows affected −
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
6 customers selected
CURSOR c_customers IS
SELECT id, name, address FROM customers;
OPEN c_customers;
CLOSE c_customers;
Example
Following is a complete example to illustrate the concepts of explicit cursors &minua;
DECLARE
c_id customers.id%type;
c_name customerS.No.ame%type; c_addr customers.address%type; CURSOR c_customers is
SELECT id, name, address FROM customers; BEGIN
OPEN c_customers; LOOP
FETCH c_customers into c_id, c_name, c_addr; EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr); END LOOP;
CLOSE c_customers;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
CONCLUSION:
References
Annexure: