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

DMBS Practical

The document discusses setting up MySQL, an open-source relational database. It covers installing MySQL on Windows and Ubuntu, and configuring the database including creating a root password, securing the database, and initializing the data directory. Example commands are provided to check the status, start the database server, and log into MySQL.

Uploaded by

Qwert Qwert
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

DMBS Practical

The document discusses setting up MySQL, an open-source relational database. It covers installing MySQL on Windows and Ubuntu, and configuring the database including creating a root password, securing the database, and initializing the data directory. Example commands are provided to check the status, start the database server, and log into MySQL.

Uploaded by

Qwert Qwert
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Database Management T E (E & TC)

Index

Sr. Experiment Name Date Page Remark


No Number /Sign

Group A- Database Programming Languages – SQL


1 Study of Open-Source Relational Databases: MySQL

2 Design and develop at least 5 SQL DDL statements


which demonstrate the use of SQL objects such as Table,
View, Index, Sequence and Synonym.
3 Design and develop at least 5SQL queries for suitable
database application using SQL DML statements: Insert
and Select with operators and functions.
4 Design and develop at least 5 SQL queries for suitable
database application using SQL DML statements:
Update and Delete with operators and functions.
5 Design and develop at least 5 SQL queries for suitable
database application using SQL DML statements: all
types of Join and Sub-Query.
Group B- Database Programming Languages – PL / SQL

6 Write a PL/SQL block to calculate fine for a library book


by accessing borrower information from the database.
7 Write a PL/SQL block to create cursor to copy contents
of one table into another. Avoid redundancy.
8 To Study and implement PL/SQL programming along
with Procedures and Functions.
9 Write a PL/SQL block to create trigger on Library table
to keep track of updation and deletion of records.
Group C- Mini Project: Database Project Life Cycle

10 Implement MYSQL/Oracle database connectivity with


PHP/python/Java Implement Database navigation
operations (add, delete, edit,) using ODBC/JDBC.

11 Mini Project

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 1
Database Management T E (E & TC)

Experiment No: 1

Subject: Database Management Laboratory

Title: Study of Open-Source Relational Databases: MySQL

Roll No.:

Class: TE (E&TC)

Division:

Signature:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 2
Database Management T E (E & TC)

Group A- Database Programming Languages – SQL


Experiment No. -1

Title: Study of Open-Source Relational Databases: MySQL


Objective: To learn and understand open-source relational databases.
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more,
1 GB Hard Disk or more.
Software requirements: Windows Operating System, MySQL
Theory:
A database-management system (DBMS) is a collection of interrelated data and a set of programs
to access those data. The collection of data, usually referred to as the database, contains information
relevant to an enterprise. The primary goal of a DBMS is to provide a way to store and retrieve
database information that is both convenient and efficient. A relational database management system
(RDBMS) is a program that lets you create, update, and administer a relational database. Most
commercial RDBMS’s use the Structured Query Language (SQL) to access the database, although
SQL was invented after the development of the relational model and is not necessary for its use.
MySQL open-source RDBMS overview: MySQL is a popular open-source relational database
management system (RDBMS) choice for web-based applications. Developers, database
administrators use MySQL to build and manage next-generation web- and cloud-based applications.
With most open-source RDBMS options, MySQL is available in several different editions and runs
on Windows, OS X, Solaris, FreeBSD and other variants of Linux and Unix:
a) MySQL Classic Edition, available to only independent software vendors, OEMs and value-
added resellers, is designed to be an embeddable database for read-intensive applications.
b) MySQL Community Edition is the free downloadable version of MySQL available under
the GNU General Public License (GPL).
c) MySQL Standard Edition is the entry-level RDBMS offering for online transaction
processing
d) MySQL Enterprise Edition adds advanced features, management tools (including OEM for
MySQL) and technical support.
e) MySQL Cluster Carrier Grade Edition is designed for Web and cloud development.

Data types supported by MySQL open-source RDBMS:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 3
Database Management T E (E & TC)

MySQL data types include :


1. numeric types,
2. date and time types,
3. string types (including binary, character and Binary Large Object), and
4. spatial types.
Additionally, MySQL will map certain data types from other DBMSes to MySQL data types for
easier portability.

Install MySQL on windows:


1. Extract the main archive to the desired install directory
2. Create an option file
3. Choose a MySQL server type
4. Initialize MySQL
5. Start the MySQL server
6. Secure the default user accounts
Install MySQL on Ubuntu 14.04: MySQL is an open-source database management system,
commonly installed as part of the popular LAMP (Linux, Apache, MySQL, PHP/Python/Perl) stack.
It uses a relational database and SQL (Structured Query Language) to manage its data. The short
version of the installation is simple: update your package index, install the mysql-server package,
and then run the included security and database initialization scripts.
Step 1 — Installing MySQL: There are two ways to install MySQL. You can either use one of the
versions included in the APT package repository by default (which are 5.5 and 5.6), or you can
install the latest version (currently 5.7) by manually adding MySQL’s repository first. You can just
use the mysql-server APT package, which just installs the latest version for your Linux distribution.
To install MySQL this way, update the package index on your server and install the package with
apt-get.
• sudo apt-get update
• sudo apt-get install mysql-server (You’ll be prompted to create a root password during the
installation. Choose a secure one and make sure you remember it, because you’ll need it later.) Move
on to step two from here.
Installing MySQL 5.5 or 5.6
If you want to install MySQL 5.5 or 5.6 specifically, the process is still very straight forward. First,
update the package index on your server.
• sudo apt-get update Then, to install MySQL 5.5, (install the mysql-server-5.5 package).
PES’s Modern College of Engineering,
Department of Electronics & Telecommunication Engineering. 4
Database Management T E (E & TC)

• sudo apt-get install mysql-server-5.5 (you’ll be prompted to create a root password during the
installation. Choose a secure one and make sure you remember it, because you’ll need it later.)
Step 2 — Configuring MySQL: First, you’ll want to run the included security script. This changes
some of the less secure default options for things like remote root logins and sample users.
• sudo mysql_secure_installation
This will prompt you for the root password you created in step one. You can press ENTER to accept
the defaults for all the subsequent questions, with the exception of the one that asks if you’d like to
change the root password. You just set it in step one, so you don’t have to change it now. Next,
Initialize the MySQL data directory, which is where MySQL stores its data. How you do this
depends on which version of MySQL you’re running. You can check your version of MySQL with
the following command.
• mysql –version If you’re using a version of MySQL earlier than 5.7.6, you should initialize the
data directory by running mysql_install_db.
• sudo mysql_install_db
Step 3 — Testing MySQL: Regardless of how you installed it, MySQL should have started running
automatically. To test this, check its status.
• service mysql status
If MySQL isn’t running, you can start it with
• sudo service mysql start.
For an additional check, you can try connecting to the database using the mysqladmin tool, which
is a client that lets you run administrative commands. For JES’ITMR DBMS LABORATORY
example, this command says to connect to MySQL as root (-u root), prompt for a password (-p), and
return the version.
• mysqladmin -p -u root version
Step 4 — Log in MySQL: Use following command to log in to MySQL in terminal, write
• sudo mysql –u root –p You will be prompted for password.
After log in you can see mysql> prompt to execute queries

RDBMS Terminology:
Before we proceed to explain 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.
PES’s Modern College of Engineering,
Department of Electronics & Telecommunication Engineering. 5
Database Management T E (E & TC)

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.
Referential Integrity: Referential Integrity makes sure that a foreign key value always points to an
existing row. is a fast, easy-to-use RDBMS being used for many small and big businesses. is
developed, marketed, and supported by My SQLAB, which is a Swedish company. is becoming so
popular because of many good reasons:
• Released under an open-source license. So, you have nothing to pay to use it.
• Very powerful program. It handles a large subset of the functionality of the most expensive and
powerful database packages.
• Uses a standard form of the well-known SQL data language.
•Works on many operating systems and with many languages including PHP, PERL, C, C++,
JAVA, etc.
• Works very quickly and works well even with large datasets.
• Friendly to PHP, the most appreciated language for web development.
• Supports large databases, upto 50 million rows or more in a table. The default file size limit for a
table is 4GB, but you can increase this (if your operating system can handle it) to a theoretical limit
of 8 million tera bytes (TB).
• Customizable. The open-source GPL license allows programmers to modify the software to fit their
own specific environments.

SQL General Data Types


Each column in a database table is required to have a name and a data type.
SQL developers have to decide what types of data will be stored inside each table column when
creating a SQL table. The data type is a label and a guideline for SQL to understand what type of
data is expected inside of each column, and it also identifies how SQL will interact with the stored
data.

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 6
Database Management T E (E & TC)

The following table lists the general data types in SQL:

Data Type Description


String Datatype
CHAR (size) A FIXED length string (can contain letters, numbers, and special
characters). The size parameter specifies the column length in characters
- can be from 0 to 255. Default is 1
VARCHAR (size) A VARIABLE length string (can contain letters, numbers, and special
characters). The size parameter specifies the maximum column length in
characters - can be from 0 to 65535
BINARY (size) Equal to CHAR() but stores binary byte strings. The size parameter
specifies the column length in bytes. Default is 1
VARBINARY (size) Equal to VARCHAR(), but stores binary byte strings. The size parameter
specifies the maximum column length in bytes.
TINYBLOB For BLOBs (Binary Large OBjects). Max length: 255 bytes
TINYTEXT Holds a string with a maximum length of 255 characters
TEXT (size) Holds a string with a maximum length of 65,535 bytes
BLOB (size) For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters
LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of
data
ENUM (val1, val2, A string object that can have only one value, chosen from a list of possible
val3, ...) values. You can list up to 65535 values in an ENUM list. If a value is
inserted that is not in the list, a blank value will be inserted. The values
are sorted in the order you enter them
Numeric Data Type
BIT (size) A bit-value type. The number of bits per value is specified in size. The
size parameter can hold a value from 1 to 64. The default value for size is
1.

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 7
Database Management T E (E & TC)

TINYINT (size) A very small integer. Signed range is from -128 to 127. Unsigned range
is from 0 to 255. The size parameter specifies the maximum display width
(which is 255)
BOOL Zero is considered as false, nonzero values are considered as true.
BOOLEAN Equal to BOOL
SMALLINT (size) A small integer. Signed range is from -32768 to 32767. Unsigned range
is from 0 to 65535. The size parameter specifies the maximum display
width (which is 255)
MEDIUMINT (size) A medium integer. Signed range is from -8388608 to 8388607. Unsigned
range is from 0 to 16777215. The size parameter specifies the maximum
display width (which is 255)
INT (size) A medium integer. Signed range is from -2147483648 to 2147483647.
Unsigned range is from 0 to 4294967295. The size parameter specifies
the maximum display width (which is 255)
INTEGER (size) Equal to INT (size)
BIGINT (size) A large integer. Signed range is from -9223372036854775808 to
9223372036854775807. Unsigned range is from 0 to
18446744073709551615. The size parameter specifies the maximum
display width (which is 255)
FLOAT (size, d) A floating point number. The total number of digits is specified in size.
The number of digits after the decimal point is specified in the d
parameter. This syntax is deprecated in MySQL 8.0.17, and it will be
removed in future MySQL versions
FLOAT(p) A floating point number. MySQL uses the p value to determine whether
to use FLOAT or DOUBLE for the resulting data type. If p is from 0 to
24, the data type becomes FLOAT (). If p is from 25 to 53, the data type
becomes DOUBLE ()
DOUBLE (size, d) A normal-size floating point number. The total number of digits is
specified in size. The number of digits after the decimal point is specified
in the d parameter
DOUBLE
PRECISION (size, d)

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 8
Database Management T E (E & TC)

DECIMAL (size, d) An exact fixed-point number. The total number of digits is specified in
size. The number of digits after the decimal point is specified in the d
parameter. The maximum number for size is 65. The maximum number
for d is 30. The default value for size is 10. The default value for d is 0.
DEC (size, d) Equal to DECIMAL (size,d)
Date and Time Data Types
DATE A date. Format: YYYY-MM-DD. The supported range is from '1000-01-
01' to '9999-12-31'
DATETIME (fsp) A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The
supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
Adding DEFAULT and ON UPDATE in the column definition to get
automatic initialization and updating to the current date and time
TIMESTAMP (fsp) A timestamp. TIMESTAMP values are stored as the number of seconds
since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-
DD hh:mm:ss. The supported range is from '1970-01-01 00:00:01' UTC
to '2038-01-09 03:14:07' UTC. Automatic initialization and updating to
the current date and time can be specified using DEFAULT
CURRENT_TIMESTAMP and ON UPDATE
CURRENT_TIMESTAMP in the column definition
TIME (fsp) A time. Format: hh:mm:ss. The supported range is from '-838:59:59' to
'838:59:59'
YEAR A year in four-digit format. Values allowed in four-digit format: 1901 to
2155, and 0000. MySQL 8.0 does not support year in two-digit format.

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 9
Database Management T E (E & TC)

Conclusion:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 10
Database Management T E (E & TC)

Experiment No: 2

Subject: Database Management Laboratory

Title: Design and develop at SQL DDL statements which demonstrate the use of
SQL objects such as Table, View, Index, Sequence and Synonym.

Roll No.:

Class: TE (E&TC)

Division:

Signature:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 11
Database Management T E (E & TC)

Group A- Database Programming Languages – SQL

Experiment No. -2
Title: Design and develop at least 5 SQL DDL statements which demonstrate the use of SQL
objects such as Table, View, Index, Sequence and Synonym.
Objective: To learn all type Data Definition Language commands and their uses.
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements: Windows Operating System, MySQL
Theory:

Introduction to SQL:

➢ SQL stands for Structured Query Language


➢ SQL lets you access and manipulate databases
➢ SQL is an ANSI (American National Standards Institute) standard

Commands of SQL are grouped into four languages.

DDL:

DDL is abbreviation of Data Definition Language. It is used to create and modify the structure of
database objects in database.

Examples: CREATE, ALTER, DROP, RENAME, TRUNCATE statements

DML

DML is abbreviation of Data Manipulation Language. It is used to retrieve, store, modify, delete,
insert and update data in database.

Examples: SELECT, UPDATE, INSERT, DELETE statements

DCL

DCL is abbreviation of Data Control Language. It is used to create roles, permissions, and
referential integrity as well it is used to control access to database by securing it.

Examples: GRANT, REVOKE statements

TCL

TCL is abbreviation of Transactional Control Language. It is used to manage different transactions


occurring within a database.

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 12
Database Management T E (E & TC)

Examples: COMMIT, ROLLBACK statements

Data Definition Language (DDL)

1.Data definition Language (DDL) is used to create, rename, alter, modify, drop, replace, and
delete tables, Indexes, Views,

and comment on database objects; and establish a default database.

2.The DDL part of SQL permits database tables to be created or deleted. It also defines indexes
(keys), specify links

between tables and impose constraints between tables. The most important DDL statements in
SQL are:

• CREATE TABLE- Creates a new table


• ALTER TABLE- Modifies a table
• DROP TABLE- Deletes a table
• TRUNCATE -Use to truncate (delete all rows) a table.
• CREATE INDEX- Creates an index (search key)
• DROP INDEX- Deletes an index

1.The CREATE TABLE Statement

The CREATE TABLE statement is used to create a table in a database.

Syntax

CREATE TABLE tablename

(attr1_name attr1_datatype(size) attr1_constraint,

attr2_name attr2_datatype(size) attr2_constraint,….);

SQL Constraints

Constraints are used to limit the type of data that can go into a table.

Constraints can be specified when a table is created (with the CREATE TABLE statement) or after
the table is created (with the ALTER TABLE statement).

We will focus on the following constraints:

NOT NULL

UNIQUE

PRIMARY KEY
PES’s Modern College of Engineering,
Department of Electronics & Telecommunication Engineering. 13
Database Management T E (E & TC)

FOREIGN KEY

CHECK

DEFAULT

Add constraint after table creation using alter table option

Syntax - Alter table add constraint constraint_name constraint_type (Attr_name) Example - Alter
table stud add constraint

prk1 primary key(rollno);

Drop constraint:

Syntax- Drop Constraint Constraint_name;

Example - Drop constraint prk1;

2.The Drop TABLE Statement

Removes the table from the database

Syntax

DROP TABLE table_name;

3. The ALTER TABLE Statement

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

Syntax

To add a column in a table, use the following syntax:

ALTER TABLE table_name

ADD column_name datatype;

To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):

ALTER TABLE table_name DROP COLUMN column_name;

To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name

MODIFY COLUMN column_name datatype;

4. The RENAME TABLE Statement


PES’s Modern College of Engineering,
Department of Electronics & Telecommunication Engineering. 14
Database Management T E (E & TC)

Rename the old table to new table;

Syntax

Rename old_tabname to new_tabname;

5. The TRUNCATE TABLE Statement

The ALTER TABLE Statement is used to truncate (delete all rows) a table.

Syntax

To truncate a table, use following syntax : TRUNCATE TABLE table_name;

6. CREATE VIEW Statement

In SQL, a view is a virtual table based on the result-set of an SQL statement.A view contains rows
and columns, just like a

real table. The fields in a view are fields from one or more real tables in the database.

Syntax

CREATE VIEW view_name AS

SELECT column_name(s)

FROM table_name

WHERE condition;

7. SQL Dropping a View

You can delete a view with the DROP VIEW command.

Syntax

DROP VIEW view_name;

8 . Create Index Statement

1. Index in SQL is created on existing tables to retrieve the rows quickly. When there are
thousands of records in a

table, retrieving information will take a long time.

2. Therefore indexes are created on columns which are accessed frequently, so that the
information can be

retrieved quickly.

3. Indexes can be created on a single column or a group of columns. When a index is created, it
first sorts the
PES’s Modern College of Engineering,
Department of Electronics & Telecommunication Engineering. 15
Database Management T E (E & TC)

data and then it assigns a ROWID for each row.

Syntax

CREATE INDEX index_name

ON table_name (column_name1,column_name2...);

• index_name is the name of the INDEX.


• table_name is the name of the table to which the indexed column belongs
• column_name1, column_name2.. is the list of columns which make up the INDEX.

9. Drop Index Statement

Syntax

DROP INDEX index_name;

10. Create Synonym statement

1. Use the CREATE SYNONYM statement to create a synonym, which is an alternative name for
a table, view,

sequence, procedure, stored function, package, materialized view.

2. Synonyms provide both data independence and location transparency. Synonyms permit
applications to

function without modification regardless of which user owns the table or view and regardless of
which

database holds the table or view.

3. You can refer to synonyms in the following DML statements: SELECT, INSERT, UPDATE,
DELETE

Syntax - Create synonym synonym-name for object-name;

Example-Create synonym synonym_name for table_name

Create synonym t for test

Conclusion:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 16
Database Management T E (E & TC)

Experiment No: 3

Subject: Database Management Laboratory

Title: Design and develop at least 5SQL queries for suitable database application
using SQL DML statements: Insert and Select with operators and
functions.

Roll No.:

Class: TE (E&TC)

Division:

Signature:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 17
Database Management T E (E & TC)

Group A- Database Programming Languages – SQL

Experiment No. -3

Title: Design and develop at least 5 SQL queries for suitable database application using SQL DML
statements: Insert and Select with operators and functions.
Objective: To learn and understand DML statements in MySQL
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements: Windows Operating System, MySQL
Theory:

DML command

Data Manipulation Language (DML) statements are used for managing data in database. DML

commands are not auto-committed. It means changes made by DML command are not permanent

to database, it can be rolled back.

1) INSERT command

Insert command is used to insert data into a table. Following is its general syntax,

INSERT into table-name values(data1,data2,..)

Lets see an example,

Consider a table Student with following fields.

S_id S_Name age

INSERT into Student values(101,'Adam',15);

The above command will insert a record into Student table.

S_id S_Name age

101 Adam 15

2) UPDATE command

Update command is used to update a row of a table. Following is its general syntax,

UPDATE table-name set column-name = value where condition;

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 18
Database Management T E (E & TC)

Lets see an example,

update Student set age=18 where s_id=102;

Example to Update multiple columns

UPDATE Student set s_name='Abhi',age=17 where s_id=103;

3) Delete command

Delete command is used to delete data from a table. Delete command can also be used with

condition to delete a particular row. Following is its general syntax,

DELETE from table-name;

Example to Delete all Records from a Table

DELETE from Student;

The above command will delete all the records from Student table.

Example to Delete a particular Record from a Table

Consider Student table

DELETE from Student where s_id=103;

SQL Functions

SQL provides many built-in functions to perform operations on data. These functions are useful

while performing mathematical calculations, string concatenations, sub-strings etc. SQL

functions are divided into two catagories,

• Aggregrate Functions

• Scalar Functions

Aggregrate Functions

These functions return a single value after calculating from a group of values.Following are some

frequently used Aggregrate functions.

1) AVG()

Average returns average value after calculating from values in a numeric column.

Its general Syntax is,

SELECT AVG(column_name) from table_name

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 19
Database Management T E (E & TC)

e.g.

SELECT avg(salary) from Emp;

2) COUNT()

Count returns the number of rows present in the table either based on some condition or without

condition.

Its general Syntax is,

SELECT COUNT(column_name) from table-name;

Example using COUNT()

Consider following Emp table

eid name age salary

401 Anu 22 9000

402 Shane 29 8000

SQL query to count employees, satisfying specified condition is,

SELECT COUNT(name) from Emp where salary = 8000;

3) FIRST()

First function returns first value of a selected column

Syntax for FIRST function is,

SELECT FIRST(column_name) from table-name

SQL query

SELECT FIRST(salary) from Emp;

4) LAST()

LAST return the return last value from selected column

Syntax of LAST function is,

SELECT LAST(column_name) from table-name

SQL query will be,

SELECT LAST(salary) from emp;

5) MAX()

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 20
Database Management T E (E & TC)

MAX function returns maximum value from selected column of the table.

Syntax of MAX function is,

SELECT MAX(column_name) from table-name

SQL query to find Maximum salary is,

SELECT MAX(salary) from emp;

6) MIN()

MIN function returns minimum value from a selected column of the table.

Syntax for MIN function is,

SELECT MIN(column_name) from table-name

SQL query to find minimum salary is,

SELECT MIN(salary) from emp;

7) SUM()

SUM function returns total sum of a selected columns numeric values.

Syntax for SUM is,

SELECT SUM(column_name) from table-name

SQL query to find sum of salaries will be,

SELECT SUM(salary) from emp;

Scalar Functions

Scalar functions return a single value from an input value. Following are soe frequently used

Scalar Functions.

1) UCASE()

UCASE function is used to convert value of string column to Uppercase character.

Syntax of UCASE,

SELECT UCASE(column_name) from table-name

Example of UCASE()

SQL query for using UCASE is,

SELECT UCASE(name) from emp;

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 21
Database Management T E (E & TC)

2) LCASE()

LCASE function is used to convert value of string column to Lowecase character.

Syntax for LCASE is:

SELECT LCASE(column_name) from table-name

3) MID()

MID function is used to extract substrings from column values of string type in a table.

Syntax for MID function is:

SELECT MID(column_name, start, length) from table-name

4) ROUND()

ROUND function is used to round a numeric field to number of nearest integer. It is used on

Decimal point values. Syntax of Round function is,

SELECT ROUND(column_name, decimals) from table-name

Operators:

AND and OR operators are used with Where clause to make more precise conditions for fetching

data from database by combining more than one condition together.

1) AND operator

AND operator is used to set multiple conditions with Where clause.

Example of AND

SELECT * from Emp WHERE salary < 10000 AND age > 25

2) OR operator

OR operator is also used to combine multiple conditions with Where clause. The only difference

between AND and OR is their behaviour. When we use AND to combine two or more than two

conditions, records satisfying all the condition will be in the result. But in case of OR, atleast one

condition from the conditions specified must be satisfied by any record to be in the result.

Example of OR

SELECT * from Emp WHERE salary > 10000 OR age > 25

Set Operation in SQL

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 22
Database Management T E (E & TC)

SQL supports few Set operations to be performed on table data. These are used to get meaningful

results from data, under different special conditions.

3) Union

UNION is used to combine the results of two or more Select statements. However it will

eliminate duplicate rows from its result set. In case of union, number of columns and datatype

must be same in both the tables.

Example of UNION

select * from First

UNION

select * from second

4) Union All

This operation is similar to Union. But it also shows the duplicate rows.

Union All query will be like,

select * from First

UNION ALL

select * from second

5) Intersect

Intersect operation is used to combine two SELECT statements, but it only retuns the records

which are common from both SELECT statements. In case of Intersect the number of columns

and datatype must be same. MySQL does not support INTERSECT operator.

Intersect query will be,

select * from First

INTERSECT

select * from second

6) Minus

Minus operation combines result of two Select statements and return only those result which

belongs to first set of result. MySQL does not support INTERSECT operator.

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 23
Database Management T E (E & TC)

Minus query will be,

select * from First

MINUS

select * from second

Conclusion:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 24
Database Management T E (E & TC)

Experiment No: 4

Subject: Database Management Laboratory

Title: Design and develop at least 5 SQL queries for suitable database application
using SQL DML statements: Update and Delete with operators and
functions.

Roll No.:

Class: TE (E&TC)

Division:

Signature:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 25
Database Management T E (E & TC)

Group A- Database Programming Languages – SQL


Experiment No. -4

Title: Design and develop at least 5 SQL queries for suitable database application using SQL DML
statements: Update and Delete with operators and functions.
Objective: To learn and understand DML statements in MySQL
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements: Windows Operating System, MySQL
Theory:

DML command

Data Manipulation Language (DML) statements are used for managing data in database. DML

commands are not auto-committed. It means changes made by DML command are not permanent

to database, it can be rolled back.

1) INSERT command

Insert command is used to insert data into a table. Following is its general syntax,

INSERT into table-name values(data1,data2,..)

Lets see an example,

Consider a table Student with following fields.

S_id S_Name age

INSERT into Student values(101,'Adam',15);

The above command will insert a record into Student table.

S_id S_Name age

101 Adam 15

2) UPDATE command

Update command is used to update a row of a table. Following is its general syntax,

UPDATE table-name set column-name = value where condition;

Lets see an example,

update Student set age=18 where s_id=102;


PES’s Modern College of Engineering,
Department of Electronics & Telecommunication Engineering. 26
Database Management T E (E & TC)

Example to Update multiple columns

UPDATE Student set s_name='Abhi',age=17 where s_id=103;

3) Delete command

Delete command is used to delete data from a table. Delete command can also be used with

condition to delete a particular row. Following is its general syntax,

DELETE from table-name;

Example to Delete all Records from a Table

DELETE from Student;

The above command will delete all the records from Student table.

Example to Delete a particular Record from a Table

Consider Student table

DELETE from Student where s_id=103;

SQL Functions

SQL provides many built-in functions to perform operations on data. These functions are useful

while performing mathematical calculations, string concatenations, sub-strings etc. SQL

functions are divided into two catagories,

• Aggregrate Functions

• Scalar Functions

Aggregrate Functions

These functions return a single value after calculating from a group of values.Following are some

frequently used Aggregrate functions.

1) AVG()

Average returns average value after calculating from values in a numeric column.

Its general Syntax is,

SELECT AVG(column_name) from table_name

e.g.

SELECT avg(salary) from Emp;

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 27
Database Management T E (E & TC)

2) COUNT()

Count returns the number of rows present in the table either based on some condition or without

condition.

Its general Syntax is,

SELECT COUNT(column_name) from table-name;

Example using COUNT()

Consider following Emp table

eid name age salary

401 Anu 22 9000

402 Shane 29 8000

SQL query to count employees, satisfying specified condition is,

SELECT COUNT(name) from Emp where salary = 8000;

3) FIRST()

First function returns first value of a selected column

Syntax for FIRST function is,

SELECT FIRST(column_name) from table-name

SQL query

SELECT FIRST(salary) from Emp;

4) LAST()

LAST return the return last value from selected column

Syntax of LAST function is,

SELECT LAST(column_name) from table-name

SQL query will be,

SELECT LAST(salary) from emp;

5) MAX()

MAX function returns maximum value from selected column of the table.

Syntax of MAX function is,

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 28
Database Management T E (E & TC)

SELECT MAX(column_name) from table-name

SQL query to find Maximum salary is,

SELECT MAX(salary) from emp;

6) MIN()

MIN function returns minimum value from a selected column of the table.

Syntax for MIN function is,

SELECT MIN(column_name) from table-name

SQL query to find minimum salary is,

SELECT MIN(salary) from emp;

7) SUM()

SUM function returns total sum of a selected columns numeric values.

Syntax for SUM is,

SELECT SUM(column_name) from table-name

SQL query to find sum of salaries will be,

SELECT SUM(salary) from emp;

Scalar Functions

Scalar functions return a single value from an input value. Following are soe frequently used

Scalar Functions.

1) UCASE()

UCASE function is used to convert value of string column to Uppercase character.

Syntax of UCASE,

SELECT UCASE(column_name) from table-name

Example of UCASE()

SQL query for using UCASE is,

SELECT UCASE(name) from emp;

2) LCASE()

LCASE function is used to convert value of string column to Lowecase character.

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 29
Database Management T E (E & TC)

Syntax for LCASE is:

SELECT LCASE(column_name) from table-name

3) MID()

MID function is used to extract substrings from column values of string type in a table.

Syntax for MID function is:

SELECT MID(column_name, start, length) from table-name

4) ROUND()

ROUND function is used to round a numeric field to number of nearest integer. It is used on

Decimal point values. Syntax of Round function is,

SELECT ROUND(column_name, decimals) from table-name

Operators:

AND and OR operators are used with Where clause to make more precise conditions for fetching

data from database by combining more than one condition together.

1) AND operator

AND operator is used to set multiple conditions with Where clause.

Example of AND

SELECT * from Emp WHERE salary < 10000 AND age > 25

2) OR operator

OR operator is also used to combine multiple conditions with Where clause. The only difference

between AND and OR is their behaviour. When we use AND to combine two or more than two

conditions, records satisfying all the condition will be in the result. But in case of OR, atleast one

condition from the conditions specified must be satisfied by any record to be in the result.

Example of OR

SELECT * from Emp WHERE salary > 10000 OR age > 25

Set Operation in SQL

SQL supports few Set operations to be performed on table data. These are used to get meaningful

results from data, under different special conditions.

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 30
Database Management T E (E & TC)

3) Union

UNION is used to combine the results of two or more Select statements. However it will

eliminate duplicate rows from its result set. In case of union, number of columns and datatype

must be same in both the tables.

Example of UNION

select * from First

UNION

select * from second

4) Union All

This operation is similar to Union. But it also shows the duplicate rows.

Union All query will be like,

select * from First

UNION ALL

select * from second

5) Intersect

Intersect operation is used to combine two SELECT statements, but it only retuns the records

which are common from both SELECT statements. In case of Intersect the number of columns

and datatype must be same. MySQL does not support INTERSECT operator.

Intersect query will be,

select * from First

INTERSECT

select * from second

6) Minus

Minus operation combines result of two Select statements and return only those result which

belongs to first set of result. MySQL does not support INTERSECT operator.

Minus query will be,

select * from First

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 31
Database Management T E (E & TC)

MINUS

select * from second

Conclusion:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 32
Database Management T E (E & TC)

Experiment No: 5

Subject: Database Management Laboratory

Title: Design and develop at least 5 SQL queries for suitable database application
using SQL DML statements: all types of Join and Sub-Query.

Roll No.:

Class: TE (E&TC)

Division:

Signature:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 33
Database Management T E (E & TC)

Group A- Database Programming Languages – SQL


Experiment No. -5

Title: Design and develop at least 5 SQL queries for suitable database application using SQL DML
statements: all types of Join and Sub-Query.
Objective: To learn and understand DML statements in MySQL
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements: Windows Operating System, MySQL
Theory:

SQL JOIN

A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.

Let's look at a selection from the "Orders" table:

OrderID CustomerID OrderDate

10308 10 8/5/2012

10309 20 9/9/2013

10310 30 10/9/2019

Then, look at a selection from the "Customers" table:

CustomerID CustomerName ContactAddress Country

10 Sachin Pune India

20 Pooja Satara India

30 Kiran Kolhapur India

Note that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers"
table. The relationship between the two tables above is the "CustomerID" column.Then, we can create the
following SQL statement (that contains an INNER JOIN), that selects records that have matching values in
both tables: Example: SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM
Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID; and it will produce
something like this:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 34
Database Management T E (E & TC)

OrderID CustomerName OrderDate

10308 Sachin 8/5/2012

10309 Pooja 9/9/2013

10310 Kiran 10/9/2019

The ability of relational join operator is an important feature of relational systems. A join
makes it possible to select data from more than one table by means of a single statement. This
joining of tables can be done in a many ways.
Types of JOIN
1) Inner
2) Outer(left, right,full)
3) Cross
1) Inner join : - Also known as equi join.
-Statements generally compares two columns from two columns with the equivalence operator =.
-This type of join can be used in situations where selecting only those rows that have values in
common in the columns specified in the ON clause, is required.

Syntax :
(ANSI style)
SELECT<columnname1>, <columnname2> <columnNameN>
FROM <tablename1> INNER JOIN <tablename2>ON
<tablename1>.<columnname> = <tablename2>.<columnname> WHERE <condition> ORDER
BY <columnname1>;
(theta style)
PES’s Modern College of Engineering,
Department of Electronics & Telecommunication Engineering. 35
Database Management T E (E & TC)

SELECT<columnname1>, <columnname2> <columnNameN> FROM <tablename1>,


<tablename2> WHERE <tablename1>.<columnname> = <tablename2>.<columnname>
AND <condition> ORDER BY <columnname1>;

List the employee details along with branch names to which they belong.
Emp(empno,fname,lname,dept,desig,branchno)
Branch(bname,branchno)
Select e.empno,e.fname,e.lname,e.dept, b.bname, e.desig from emp e inner join branch b on
b.branchno=e.branchno;
Select e.empno, e.fname, e.lname, e.dept, b.bname, e.desig from emp e, branch b on where
b.branchno=e.branchno;
Eg. List the customers along with the account details associated with them.
Customer(custno,fname,lname)
Acc_cust_dtls(fdno,custno)
Acc_mstr(accno,branchno,curbal)
Branch_mstr(name,branchno)

Select c.custno, c.fname, c.lname, a.accno,a.curbal,b.branchno,b.name from customer c inner
join acc_cust_dtls k on c.custno=k.custno inner join acc_mstr a on k.fdno=a.accno inner join
branch b on b.branchno=a.branchn
o where c.custno like „C% order by c.custno;


Select
c.custno,
c.fname,
c.lname,
a.accno,a.curbal,b.branchno,b.name
from
customer
c,
acc_cust_dtls
k,
acc_mstr
a,
branch
b
where
c.custno=k.custno
and
k.fdno=a.accno
and
b.branchno=a.branchno and c.custno
like „C% order by c.custno;

Outer Join
Outer joins are similar to inner joins, but give a little bit more flexibility when selecting data from
related tables. This type of joins can be used in situations where it is desired, to select all rows
from the

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 36
Database Management T E (E & TC)

table on left( or right, or both) regardless of whether the other table has values in common & (
usually)
enter NULL where data is missing.

Tables
Emp_mstr(empno,fname,lname,dept)
Cntc_dtls(codeno,cntc_type,cntc_data)
Left Outer Join
List the employee details along with the contact details(if any) using left outer join.

Select e.empno, e.fname, e.lname, e.dept, c.cntc_type, c.cntc_data from emp_mstr e left join
cntc_dtls c on e.empno=c.codeno;

Select e.empno, e.fname, e.lname, e.dept, c.cntc_type, c.cntc_data from emp_mstr e cntc_dtls c
where e.empno=c.codeno(+);

Conclusion:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 37
Database Management T E (E & TC)

Experiment No: 6

Subject: Database Management Laboratory

Title: Write a PL/SQL block to calculate fine for a library book by accessing
borrower information from the database.

Roll No.:

Class: TE (E&TC)

Division:

Signature:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 38
Database Management T E (E & TC)

Group B- Database Programming Languages – PL/SQL

Experiment No. -6

Title: Write a PL/SQL block to calculate fine for a library book by accessing borrower information
from the database.
Problem Statement: Write a PL/SQL block of code for the following requirements:-
Schema: 1. Borrower(Rollin, Name, DateofIssue, NameofBook, Status)
2. Fine(Roll_no,Date,Amt)
3. Accept roll_no & name of book from user.
4. Check the number of days (from date of issue), if days are between 15 to 30 then fine amount will
be Rs 5per day.
5. If no. of days>30, per day fine will be Rs 50 per day & for days less than 30, Rs. 5 per day.
6. After submitting the book, status will change from I to R.
7. If condition of fine is true, then details will be stored into fine table
Objective: To learn the concept of PL/SQL.
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements: Windows Operating System, MySQL
Theory:

PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL
along with

the procedural features of programming languages.It was developed by Oracle Corporation in the
early

90’s to enhance the capabilities of SQL.

Architecture of PL/SQL:

The PL/SQL architecture mainly consists of following 3 components:

1. PL/SQL block

2. PL/SQL Engine

3. Database Server

PL/SQL block:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 39
Database Management T E (E & TC)

• This is the component which has the actual PL/SQL code.


• This consists of different sections to divide the code logically (declarative section for
declaring
• purpose, execution section for processing statements, exception handling section for
handling
• errors)
• It also contains the SQL instruction that used to interact with the database server.
• All the PL/SQL units are treated as PL/SQL blocks, and this is the starting stage of the
• architecture which serves as the primary input.
• Following are the different type of PL/SQL units.
o Anonymous Block
o Function
o Library
o Procedure
o Package Body
o Package Specification
o Trigger
o Type
o Type Body

PL/SQL Engine

➢ PL/SQL engine is the component where the actual processing of the codes takes place.
➢ PL/SQL engine separates PL/SQL units and SQL part in the input (as shown in the image
below).
➢ The separated PL/SQL units will be handled with the PL/SQL engine itself.
➢ The SQL part will be sent to database server where the actual interaction with database
takes
➢ place.
➢ It can be installed in both database server and in the application server.
➢ Database Server:
➢ This is the most important component of Pl/SQL unit which stores the data.
➢ The PL/SQL engine uses the SQL from PL/SQL units to interact with the database server.
➢ It consists of SQL executor which actually parses the input SQL statements and execute the
same.

Advantage of Using PL/SQL

1. Better performance, as sql is executed in bulk rather than a single statement

2. High Productivity

3. Tight integration with SQL

4. Full Portability

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 40
Database Management T E (E & TC)

5. Tight Security

6. Support Object Oriented Programming concepts.

Basic Difference between SQL and PL/SQL

In this section, we will discuss some differences between SQL and PL/SQL

SQL PL/SQL

SQL is a single query that is used to perform PL/SQL is a block of codes that used to write
DML and DDL operations the entire program blocks/ procedure/ function,
etc.

It is declarative, that defines what needs to be PL/SQL is procedural that defines how the
done, rather than how things need to be done. things needs to be done.

Execute as a single statement. Execute as a whole block.

Mainly used to manipulate data. Mainly used to create an application

Interaction with Database server. No interaction with the database server

Cannot contain PL/SQL code in it. It is an extension of SQL, so it can contain


SQL inside it.

PL/SQL Block Structure:

Basic Syntax of PL/SQL which is a block-structured language; this means that the PL/SQL
programs are divided and written in logical blocks of code. Each block consists of three sub-parts:

Declarations :

This section starts with the keyword DECLARE. It is an optional section and defines all variables,

cursors, subprograms, and other elements to be used in the program.

Executable Commands

This section is enclosed between the keywords BEGIN and END and it is a mandatory section. It

consists of the executable PL/SQL statements of the program. It should have at least one
executable line of code, which may be just a NULL command to indicate that nothing should be
executed.

Exception Handling

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 41
Database Management T E (E & TC)

This section starts with the keyword EXCEPTION. This optional section contains exception(s) that

handle errors in the program.

Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other
PL/SQL

blocks using BEGIN and END. Following is the basic structure of a PL/SQL block −

DECLARE

<declarations section>

BEGIN

<executable command(s)>

EXCEPTION

<exception handling>

END;

The 'Hello World' Example

DECLARE

message varchar2(20):= 'Hello, World!';

BEGIN

dbms_output.put_line(message);

END;

The end; line signals the end of the PL/SQL block.

PL/SQL Placeholders

Placeholders are temporary storage area. PL/SQL Placeholders can be any of Variables, Constants
and

Records. Oracle defines placeholders to store data temporarily, which are used to manipulate data
during

the execution of a PL SQL block.

Define PL/SQL Placeholders

Depending on the kind of data you want to store, you can define placeholders with a

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 42
Database Management T E (E & TC)

name and a datatype. Few of the datatypes used to define placeholders are as given below.

Number (n,m) , Char (n) , Varchar2 (n) , Date , Long , Long raw, Raw, Blob, Clob, Nclob, Bfile

PL/SQL Variables

These are placeholders that store the values that can change through the PL/SQL Block.

General Syntax to declare a variable is

variable_name datatype [NOT NULL := value ];

variable_name is the name of the variable.

datatype is a valid PL/SQL datatype.

NOT NULL is an optional specification on the variable.

value or DEFAULT valueis also an optional specification, where you can initialize a variable.

Each variable declaration is a separate statement and must be terminated by a semicolon.

For example, if you want to store the current salary of an employee, you can use a variable.

DECLARE

salary number (6);

The below example declares two variables, one of which is a not null.

DECLARE

salary number(4);

dept varchar2(10) NOT NULL := “HR Dept”;

The below example declares two variables, one of which is a not null.

DECLARE

salary number(4);

dept varchar2(10) NOT NULL := “HR Dept”;

The below example declares two variables, one of which is a not null.

DECLARE

salary number(4);

dept varchar2(10) NOT NULL := “HR Dept”

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 43
Database Management T E (E & TC)

Conclusion:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 44
Database Management T E (E & TC)

Experiment No: 7

Subject: Database Management Laboratory

Title: Write a PL/SQL block to create cursor to copy contents of one table into
another. Avoid redundancy.
Roll No.:

Class: TE (E&TC)

Division:

Signature:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 45
Database Management T E (E & TC)

Group B- Database Programming Languages – PL/SQL


Experiment No. -7

Title: Write a PL/SQL block to create cursor to copy contents of one table into another. Avoid
redundancy.
Problem Statement: Cursors: (All types: Implicit, Explicit, Cursor FOR Loop, Parameterized
Cursor) Write a PL/SQL block of code using parameterized Cursor, that will merge the data available
in the newly created table N_RollCall with the data available in the table O_RollCall. If the data in
the first table already exist in the second table then that data should be skipped.
Objective: To learn the concept of PL/SQL.
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements: Windows Operating System, MySQL
Theory:

CURSOR:-

For the processing of any SQL statement, database needs to allocate memory. This memory is
called context area. The context area is a part of PGA (Process global area) and is allocated on the
server. A cursor is associated with this work area used by for multi row queries. A cursor is a
handle or pointer to the context area. The cursor allows to process contents in the context area row
by row.

There are two types of cursors.

1)Implicit cursor:- Implicit cursors are defined by ORACLE implicitly. ORACLE defines
implicit cursor for every DML statements.

2) Explicit cursor:- These are user-defined cursors which are defined in the declaration section of
the PL/SQL block.

There are four steps in which the explicit cursor is processed.

• Declaring a cursor
• Opening a cursor
• Fetching rows from an opened cursor
• Closing cursor

General syntax for CURSOR:-

DECLARE

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 46
Database Management T E (E & TC)

Cursor cursor_name IS select_statement or query; BEGIN

Open cursor_name;

Fetch cursor_name into list_of_variables;

Close cursor_name;

END;

Where,
Cursor_name : is the name of the cursor.
Select_statement : is the query that defines the set of rows to be processed by the cursor.
Open cursor_name : the cursor that has been previously declared. When cursor is opened
following things happen
i) The active set pointer is set to the first row.
ii) The value of the binding variables are examined.
Fetch statement is used to retrieve a row from the selected rows, one at a time, into PL/SQL
variables.
Close cursor_name:-When all of cursor rows have been retrieved, the cursor should be closed.

Explicit cursor attributes:-

Following are the cursor attributes

1.%FOUND: - This is Boolean attribute. It returns TRUE if the previous fetch returns a row and
false if it doesn‟t.

2. %NOTFOUND:-If fetch returns a row it returns FALSE and TRUE if it doesn‟t. This as the exit
condition for the fetch loop; is often used

3.%ISOPEN:-This attribute is used to determine whether or not the associated cursor is open. If so
it returns TRUE otherwise FALSE.

4.%ROWCOUNT:-This numeric attribute returns a number of rows fetched by the cursor.

Cursor Fetch Loops

1) Simple Loop Syntax:-

LOOP

Fetch cursorname into list of variables;

EXIT WHEN cursorname%NOTFOUND Sequence_of_statements;

END LOOP;

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 47
Database Management T E (E & TC)

2) WHILE Loop Syntax:-

FETCH cursorname INTO list of variables; WHILE cursorname%FOUND LOOP

Sequence_of_statements;

FETCH cursorname INTO list of variables; END LOOP;

3) Cursor FOR Loop Syntax:

FOR variable_name IN cursorname LOOP

-- an implicit fetch is done here.

-- cursorname%NOTFOUND is also implicitly checked.

-- process the fetch records. Sequence_of_statements;

END LOOP;

There are two important things to note about :-

i) Variable_name is not declared in the DECLARE section. This variable is implicitly


declared by the PL/SQL compiler.
ii) Type of this variable is cursorname%ROWTYPE.

Implicit Cursors

PL/SQL issues an implicit cursor whenever you execute a SQL statement directly in your code, as
long as that code does not employ an explicit cursor. It is called an "implicit" cursor because you,
the developer, do not explicitly declare a cursor for the SQL statement.

If you use an implicit cursor, Oracle performs the open, fetches, and close for you automatically;
these actions are outside of your programmatic control. You can, however, obtain information about
the most recently executed SQL statement by examining the values in the implicit SQL cursor
attributes.

PL/SQL employs an implicit cursor for each UPDATE, DELETE, or INSERT statement you execute
in a program. You cannot, in other words, execute these statements within an explicit cursor, even
if you want to. You have a choice between using an implicit or explicit cursor only when you execute
a single-row SELECT statement (a SELECT that returns only one row).

In the following UPDATE statement, which gives everyone in the company a 10% raise, PL/SQL
creates an implicit cursor to identify the set of rows in the table which would be affected by the
update:
PES’s Modern College of Engineering,
Department of Electronics & Telecommunication Engineering. 48
Database Management T E (E & TC)

UPDATE employee

SET salary = salary * 1.1;

The following single-row query calculates and returns the total salary for a department. Once again,
PL/SQL creates an implicit cursor for this statement:

SELECT SUM (salary) INTO department_total FROM employee

WHERE department_number = 10;

If you have a SELECT statement that returns more than one row, you must use an explicit cursor for
that query and then process the rows returned one at a time. PL/SQL does not yet support any kind
of array interface between a database table and a composite PL/SQL datatype such as a PL/SQL
table.

Drawbacks of Implicit Cursors

Even if your query returns only a single row, you might still decide to use an explicit cursor. The
implicit cursor has the following drawbacks:

• It is less efficient than an explicit cursor


• It is more vulnerable to data errors
• It gives you less programmatic control

The following sections explore each of these limitations to the implicit cursor.

Limitations of implicit cursors

An explicit cursor is, at least theoretically, more efficient than an implicit cursor. An implicit cursor
executes as a SQL statement and Oracle's SQL is ANSI-standard. ANSI dictates that a single-row
query must not only fetch the first record, but must also perform a second fetch to determine if too
many rows will be returned by that query (such a situation will RAISE the TOO_MANY_ROWS
PL/SQL exception). Thus, an implicit query always performs a minimum of two fetches, while an
explicit cursor only needs to perform a single fetch.

This additional fetch is usually not noticeable, and you shouldn't be neurotic about using an implicit
cursor for a single-row query (it takes less coding, so the temptation is always there). Look

out for indiscriminate use of the implicit cursor in the parts of your application where that cursor
will be executed repeatedly. A good example is the Post-Query trigger in the Oracle Forms.

Post-Query fires once for each record retrieved by the query (created from the base table block and
the criteria entered by the user). If a query retrieves ten rows, then an additional ten fetches are
needed with an implicit query. If you have 25 users on your system all performing a similar query,
your server must process 250 additional (unnecessary) fetches against the database. So, while it
might be easier to write an implicit query, there are some places in your code where you will want
to make that extra effort and go with the explicit cursor.

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 49
Database Management T E (E & TC)

Vulnerability to data errors

If an implicit SELECT statement returns more than one row, it raises the TOO_MANY_ROWS
exception. When this happens, execution in the current block terminates and control is passed to the
exception section. Unless you deliberately plan to handle this scenario, use of the implicit cursor is
a declaration of faith. You are saying, "I trust that query to always return a single row!"

It may well be that today, with the current data, the query will only return a single row. If the nature
of the data ever changes, however, you may find that the SELECT statement which formerly
identified a single row now returns several. Your program will raise an exception. Perhaps this is
what you will want. On the other hand, perhaps the presence of additional records is inconsequential
and should be ignored.

With the implicit query, you cannot easily handle these different possibilities. With an explicit query,
your program will be protected against changes in data and will continue to fetch rows without
raising execeptions

Conclusion:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 50
Database Management T E (E & TC)

Experiment No: 8

Subject: Database Management Laboratory

Title: To Study and implement PL/SQL programming along with Procedures and
Functions.

Roll No.:

Class: TE (E&TC)

Division:

Signature:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 51
Database Management T E (E & TC)

Group B- Database Programming Languages – PL/SQL


Experiment No. -8

Title: To Study and implement PL/SQL programming along with Procedures and Functions.
Problem Statement: PL/SQL Stored Procedure and Stored Function Write a Stored Procedure
namely proc_Grade for the categorization of student. If marks scored by students in examination is
<=1500 and marks>=990 then student will be placed in distinction category if marks scored are
between 989 and900 category is first class, if marks 899 and 825 category is Higher Second Class.
Write a PL/SQL block for using procedure created with above requirement. Stud_Marks(name,
total_marks) Result(Roll,Name, Class).
Objective: To learn the concept of PL/SQL.
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements: Windows Operating System, MySQL
Theory:

PROCEDURE:-

A procedure is a subprogram that performs a specific action or task. A procedure has two parts.

1) The procedure specification: The procedure specification specifies the procedure name and the
parameters it accepts. It is not necessary to create a procedure that accepts parameters.

2) The procedure body: The procedure body contains the declarative section without DECLARE
keyword, the executable section and an exception section.

Syntax for creating a procedureCreate [or replace] PROCEDURE procedure_name [(argument1


[IN / OUT / IN OUT] type), (argument2 [IN / OUT / IN OUT] type), ….]

IS/AS

Procedure_body

Where,

Procedure_name: – is the name of the procedure to be created Argument:- is the name of the
procedure parameter

Type:- Is the data type of the associated parameter

Procedure_body:-Is a PL/SQL block that makes up the code of the procedure.


PES’s Modern College of Engineering,
Department of Electronics & Telecommunication Engineering. 52
Database Management T E (E & TC)

IN:-This is default mode. The value of the actual parameter is passed into the procedure. Inside the
procedure the formal parameter is considered read only.

OUT:-Any value the actual parameter has when the procedure is called ignored. Inside the
procedure ,the formal parameters are considered as write only.

IN OUT:-this mode is combination of IN and OUT

Deleting procedure:- To remove a procedure from the database.

Syntax:- Drop procedure<procedure_name>;

FUNCTION:-
A function is a subprogram, which is used to compute values. It is similar to a procedure,
function also takes arguments and can be in different modes. Function also can be stored in
the database. It is a PL/SQL block consisting of declarative, executable and exception section.
Difference between procedure and function is that the procedure call is a PL/SQL statement
by itself, while a function call is called as a part of an expression. A function can return more
than one value using OUT parameter. A function can be called using position or named
notation.

Syntax for creating a function:-

Create [or replace] FUNCTION function_name [(argument1 [IN / OUT / IN OUT] type),
(argument2 [IN / OUT / IN OUT] type),

….]

Return return_type IS / AS

Where

Function_body
Function_name: – is the name of the function to be created

Argument: - is the name of the function parameter

Type:- Is the data type of the associated parameter


Function_body:-Is a PL/SQL block containing code for the function.
IN:-This is default mode. The value of the actual parameter is passed into the procedure.
Inside the procedure the formal parameter is considered read only.
PES’s Modern College of Engineering,
Department of Electronics & Telecommunication Engineering. 53
Database Management T E (E & TC)

OUT:-Any value the actual parameter has when the procedure is called ignored.
Inside the procedure ,the formal parameters are considered as write only.
INOUT:-this mode is combination of IN and OUT

Deleting a Function:- To remove the subprogram from the database.

Syntax :
Drop function<function_name>;

Conclusion:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 54
Database Management T E (E & TC)

Experiment No: 9

Subject: Database Management Laboratory

Title: Write a PL/SQL block to create trigger on Library table to keep track of
updation and deletion of records.

Roll No.:

Class: TE (E&TC)

Division:

Signature:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 55
Database Management T E (E & TC)

Group B- Database Programming Languages – PL/SQL

Experiment No. -9
Title: Write a PL/SQL block to create trigger on Library table to keep track of updation and deletion
of records.
Problem Statement: Database Trigger (All Types: Row level and Statement level triggers, Before
and After Triggers). Write a database trigger on Library table. The System should keep track of the
records that are being updated or deleted. The old value of updated or deleted records should be
added in Library_Audit table.
Objective: To learn the concept of PL/SQL.
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements: Windows Operating System, MySQL
Theory:

DATABASE TRIGGERS:-

A database trigger is a PL/SQL program unit, which gets fired automatically whenever the data
event such as DML or DDL system event. Triggers are associated with a specific table and are
fired automatically whenever the table gets manipulated in a predefined way. The act of executing
a trigger is called as firing a trigger. Triggers are similar to procedures in that they are named
PL/SQL blocks with declarative, executable and exception handling sections. But the difference is
a procedure is executed explicitly from another block via a procedure call but a trigger is executed
implicitly whenever the triggering event happens. A procedure can pass arguments but trigger
doesn‟t accept arguments

A database trigger has following components:-

1.A triggering Event

2.A triggering Constraint

3.A triggering Action Trigger categories

Triggers are categorized in various ways.

1)Trigger type

2)Triggering time

3)Triggering event

Trigger types

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 56
Database Management T E (E & TC)

There are two types of triggers

1.Statement Trigger:-A statement trigger is a trigger in which the trigger action is executed once
for the manipulation operation that fires the trigger.

2.Row Trigger:-A row trigger is a trigger in which the trigger action is performed repeatedly for
each row of the table that is affected by the manipulation operation that fires the trigger.

Triggering time

Triggers can specify the time of trigger action.

1) Before the triggering event : The trigger action is performed before the operation that fires
the trigger is executed. This trigger is used when execution of operation depends on trigger
action.
2) After the triggering event : The trigger action is performed after the operation that fires the
trigger is executed. This trigger is used when triggering action depends on the execution of
operation. Triggering Events

Triggering events are the DML operations. These operations are insert, update and delete When
these operations are performed on a table, the trigger which is associated with the operation is
fired. Triggering events divide triggers into three types.

1) DELETE TRIGGER

2) UPDATE TRIGGER

3) INSERT TRIGGER

General syntax for creation of Trigger

Create [or replace] TRIGGER <trigger_name>

<BEFORE | AFTER>

DELETE | [OR] INSERT | [OR] UPDATE[OF <column1>[,<column2>…..]

ON <table_name>

[for each row[when <condition>] Begin

……… ………

………………. End;

Where

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 57
Database Management T E (E & TC)

Trigger_name:-trigger name is the name of the trigger. Table_name :-is thye table name for which
the trigger is defined.

Trigger-condition:-The trigger condition in the when clause,if present is evaluated first.The body
of the trigger is executed only when this condition evaluates to true.

Dropping trigger

Suppose you want to drop trigger then the syntax is

Syntax:-Drop trigger trigger_name;

Enabling and Disabling Triggers

The Trigger can be disabled without dropping them. When the trigger is disabled, it is still exists in
data dictionary but never fired, To disable trigger, use alter command.

Syntax:-

Alter TRIGGER trigger_name DISABLE/ENABLE; For all triggers on a particular table

Syntax:-

Alter TRIGGER trigger_name (DISABLE/ENABLE) all triggers;

Conclusion:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 58
Database Management T E (E & TC)

Experiment No: 10

Subject: Database Management Laboratory

Title: Implement MYSQL/Oracle database connectivity with PHP/python/Java


Implement Database navigation operations (add, delete, edit,) using
ODBC/JDBC.

Roll No.:

Class: TE (E&TC)

Division:

Signature:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 59
Database Management T E (E & TC)

Group C- Mini Project: Database Project Life Cycle

Experiment No. -10

Title: Implement MYSQL/Oracle database connectivity with PHP/python/Java Implement


Database navigation operations (add, delete, edit,) using ODBC/JDBC.
Objective: To learn the concept of ODBC/JDBC
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements:
• Eclipse
• JDK 1.6
• MySQL
• Java-MySQL Connector
Theory:

Installation Steps:
In Eclipse perform following steps:
1. File - New – Java Project –Give Project Name – ok
2. In project Explorer window- right click on project name-newclass- give Class name- ok
3. In project Explorer window- right click on project name- Build
path- Configure build path- Libraries- Add External Jar - JavaMySQL Connector
4. In MySQL first Create one Database with name db1 and one
table with name stud(name,age)
Import packages, Load Driver, Create connection with MySQL Database
1) Import packages : import java.sql.*;
2) Load Driver: Class.forName("oracle.jdbc.driver.OracleDriver");
3) Create connection Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/DatabaseName","username","passwd ");
Create JDBC statement(s)

1) Creates a Statement object for sending SQL statements to the database


2) Statement stmt = con.createStatement() ;

Executing SQL Statements


PES’s Modern College of Engineering,
Department of Electronics & Telecommunication Engineering. 60
Database Management T E (E & TC)

1) executeUpdate – This Method is used for insert, update and delete queries
• Example • String sql = “INSERT INTO stud VALUES (‘Ankita’,21)";
2) stmt.executeUpdate(sql);
3) String sql = “update stud set name=‘sumit’ where name=‘Ankita’; • stmt.executeUpdate(sql);
4) Example • String sql = “delete from stud where name=‘sumit’ "; • stmt.executeUpdate(sql);

Get ResultSet (SELECT Query):

String sql1 = "SELECT name, age FROM stud";

//Write a select query in any string variable ResultSet rs = stmt.executeQuery(sql1);

//executeQuery used to run the select query and store the result in ResultSet while (rs.next())

//Iterate through ResultSet till data is found { String name1 = rs.getString(“name");

//Store name data into name1 variable int age1 = rs.getInt(“age"); //Store age data into age1 variable }

Close connection

stmt.close();

con.close();

Sample program

import java.sql.*;

public class MySQLProcedure {

public static void main(String[] args) {

try{

Class.forName("com.mysql.jdbc.Driver");

Connection c =

DriverManager.getConnection("jdbc:mysql://

localhost: 3306/ db1","root", "");

Statement sm = c.createStatement();

int ch;

do {

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 61
Database Management T E (E & TC)

System.out.println("Enter Chice \n 1.Insert \n 2.Select \n

3.Update \n 4.Delete \n 5.Exit ");

ch=s.nextInt();

switch (ch) {

case 1: sql = “Insert into stud values (‘Ankita’ ,1)";

sm.executeUpdate(sql);

System.out.println(“Record is Inserted");

break;

case 2: String sql = "SELECT name, age FROM stud";

ResultSet rs = sm.executeQuery(sql);

while(rs.next())

String name1 = rs.getString("name");

int rno1 = rs.getInt(“rno");

System.out.print("name " + name1);

System.out.println(", Age: " + rno1);

break;

case 3: sql = “update stud set name=‘Mona’ where name=‘Ankita’ ";

sm.executeUpdate(sql);

System.out.println(“Record is updated");

break;

case 4: sql = “delete from stud where rno=1";

sm.executeUpdate(sql);

System.out.println(“Record is deleted");

break;

} }while(ch<5);

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 62
Database Management T E (E & TC)

catch(Exception e){

e.printStackTrace();

}}}

Conclusion:

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 63
Database Management T E (E & TC)

PES’s Modern College of Engineering,


Department of Electronics & Telecommunication Engineering. 64

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy