Csn44 Rdbms Notes
Csn44 Rdbms Notes
Data Data is a collection of facts, which is an unorganized but they can be organized
into useful form.
Two types:
1.Raw Data – It is a data which are collected from different sources and has no
meaning.
2. Derived Data - It is a data that are extracted from raw data and used for
getting useful information. Example: NAME, DOB, MARK, etc.
Database (DB) The database is a collection of inter-related data which is used to retrieve,
insert and delete the data efficiently. Example: Bank Database, Hospital
Database, etc.
CHARACTERISTICS OF DBMS:
Shared The data in the database are stored in such a way that it can be shared
among different users.
Security The data in the database must be protected from the unauthorized Users.
Correctness The data in the database should be correct with real world.
1
Persistence The data in the database must exist permanently.
Independent The data in the database should be independent i.e. changes made to
one data should not affect the other data.
Non redundant The database should not consist of two or more data items representing
same entity.
COMPONENTS OF DATABASE
USER n: Request
Response
USER 2: Request
Database Response
Administrator Database
i. User
Users or end users are requests the needed data from the database.
The DBMS uses query and application program.
ii. DBMS Software
Gets the request from the users, translates and give response
It shares the database among the multiple users.
iii. Database
Database is a collection of interrelated data stored in database.
Two types of data
a. End user data – raw facts of an end user
b. Meta data – data about the data
iv. Hardware
All physical devices are called hardware. They are Processor, RAM, hard disk & I/O
Devices.
v. Database Administrator
Database administrator is a privileged user who is in charge of the DBMS.
This decides user privileges i.e. single user or Multiuser etc.
DATA DICTIONARY
The data dictionary stores the definition of all database tables. It is called data about
the data. This gives the description about the stored data. The content of the data dictionary are
a) What data is available?
b) Where is the data stored?
c) Who owns the data?
d) How is the data used?
e) Who can access the data?
2
DBMS ARCHITECTURE
DBMS architecture helps us to understand the components of database system and the
relationship among them. The architecture of DBMS depends on the computer system on which it
runs.
a) Overall Architecture of DBMS
Based on the computer system on which DBMS runs, the architecture of DBMS is classified
into three types. They are i) Single tier architecture
ii) Two tier architecture
iii) Three tier architecture
1-Tier Architecture
o In this architecture, the database is directly available to the user. It means the user can directly
sit on the DBMS and uses it.
o Any changes done here will directly be done on the database itself. It doesn't provide a handy
tool for end users.
o The 1-Tier architecture is used for development of the local application, where programmers
can directly communicate with the database for the quick response.
2-Tier Architecture
o The 2-Tier architecture is same as basic client-server. In the two-tier architecture, applications
on the client end can directly communicate with the database at the server side. For this
interaction, API's like: ODBC, JDBC are used.
o The user interfaces and application programs are run on the client-side.
o The server side is responsible to provide the functionalities like: query processing and
transaction management.
o To communicate with the DBMS, client-side application establishes a connection with the
server side.
3
3-Tier Architecture
o The 3-Tier architecture contains another layer between the client and server. In this
architecture, client can't directly communicate with the server.
o The application on the client-end interacts with an application server which further
communicates with the database system.
o End user has no idea about the existence of the database beyond the application server. The
database also has no idea about any other user beyond the application.
o The 3-Tier architecture is used in case of large web application.
1. External level
It is also called view level. The reason this level is called “view” is because several users can
view their desired data from this level which is internally fetched from database with the help of
conceptual and internal level mapping.
4
The user doesn’t need to know the database schema details such as data structure, table
definition etc. user is only concerned about data which is what returned back to the view level
after it has been fetched from database (present at the internal level).
External level is the “top level” of the Three Level DBMS Architecture.
2. Conceptual level
It is also called logical level. The whole design of the database such as relationship among
data, schema of data etc. are described in this level.
Database constraints and security are also implemented in this level of architecture. This level
is maintained by DBA (database administrator).
3. Internal level
This level is also known as physical level. This level describes how the data is actually stored
in the storage devices. This level is also responsible for allocating space to the data. This is the
lowest level of the architecture.
5
Note: GM-General Manager, DGM-Deputy General manager, QC-Quality Control
In the above example, for searching the details of a employee emp4, the DBMS should start from the
root node and move downwards. EMP- Employee.
Advantage : Simple design, it is an efficient model and provides data integrity.
Dis-Advantage : Needs good knowledge to implement and Programming.
A11 ANAND
CHENNAI
100 10
6
Fields/Attributes/Columns
Each row in the table is called tuple or record and the column headings are called attributes or
fields
SL
NO Hierarchical Database Relational Database Network Database Model
Model Model
1 Represents database as Represents database as Represents database as
Tree structure a collection of Tables Graph
2 Simple design Simple Design Complex Design
3 Complex programming Simple programming Complex programming
4 Single data structure is Table structure is used Two data structures are
used used 1. Record type 2. Set type
5 Example Example Example
Refer its diagram, given Refer its diagram, Refer its diagram, given
above. given above above
7
Attributes
The attributes are the properties of an entity.
Attributes are represented by an ellipse.
Example: Acc no, Address & Name are the attributes of entity named Customer.
The figure given below shows the entity with attributes.
RELATIONSHIPS
Relationships are defined as an association between the entities. Relationships are
represented by “diamond” symbol with the name of the relationship. The following are the
different types of relationship among the entities
1. one to one
2. one to many
3. many to one
4. many to many
8
Many students enroll one course.
ER DIAGRAM
The overall logical structure of a database can be expressed graphically by ER Diagram.
E –R diagram Symbols and its meaning
9
2. E-R Diagram for customer – loan
Server
10
2. Client
Client is a low-end computer used by individual user. The client can access data and
software stored in the server. The client requests the server and the server responds to
the client.
Advantages:
i) Easy to manage and control
ii) It supports multiple users
Disadvantages
i) Server supports more time for processing
ii) This requires powerful DBMS that runs on the server.
iii) The DBMS is more complex and requires more administrative tasks than
personal computer system.
Distributed Concept
In distributed system, the data and software are stored on several computers.
These computers vary in size and configuration, ranging from workstations to mainframes.
The computers communicate with one another through high speed networks or through
telephone line.
The computers are referred by different names such as “sites” or “nodes”.
11
DBA Definition
It is a process of installing, running and updating a DBMS needs a good administration. This is
done by a person called Database Administrator (DBA).
DBA TASKS
The following are the important tasks [jobs] of DBA.
1. Account Creation
DBA create the new account and password for a user or a group of users
for using the DBMS.
2. Privilege Granting
DBA grants privileges such as read or write or execute or all to the users.
3. Privilege Cancellation
DBA has the right to cancel certain privileges that were previously given to the users
5. Maintenance
DBA is incharge of upgrading and maintaining the DBMS.
6. Co-Ordination
DBA must co-ordinate with the DBMS vendor and plans for Changes.
7. Recovery
DBA must maintain backups so as to recover from accidental damage.
8. Performance Monitoring
DBA must monitor the performance and make necessary changes to achieve maximum
performance.
DATABASE MAINTENANCE
12
Database Maintenance includes the following
1. Data and log file management
2. Index Defragmentation
3. Statistics
4. Corruption detection
5. Integrity Check
6. Backups
7. File/Data compaction
Backup and recovery are the operations done by DBA to protect the data
1. Backup
Backup is a process of copying the whole database onto a cheap storage medium.
Backups help to avoid the following failures:
i. System crashes
ii. Natural and physical disasters
iii. Network failure
iv. Transaction error
v. Exception condition
vi. Disk failure
i. Physical backup
In the type of backup, the actual physical database files are copied on a
magnetic tape or CD.
2. Recovery
It is a process of restoring a database to the correct state in case of any failure.
This varies with the type of the failure. The recovery procedure is given below.
If there is any damage to the database due to disk crash, the data base is
recovered by copying the files from the backup.
If there is damage such as transaction error, system failure etc., the database
is recovered by redoing the operations or by reversing the changes that
cause inconsistency.
13
DATABASE REPLICATION
It is the process of repetition and upholding database objects such as relations, where
numerous databases that make up a distributed database system. Changes done at one site are
captured and stored locally before being forwarded and applied at each of the database's remote
locations. Replication employs distributed database technology for sharing data among various sites,
but a replicated database and a distributed database have some differences between them. In a
distributed database, data is available at different locations, but a particular relation has to reside at
only one location.
Advantages of replication
Replication in a database offers database users various benefits that are termed below
Availability
Has Reliability
Gives high Performance
Facilitates load reduction
Provide disconnected computing
Supports many users
Supports latest versions or advanced applications
Applications of Replication
Replication maintains a diverse variety of applications that have very different requirements.
Some applications are sufficiently supported with only partial synchronization between the copies of
the database and the corporate database system, while many other applications insist continuous
synchronization between all copies of the database.
DATA WAREHOUSING
Data warehousing is defined as a method of collecting information from many sources and
storing it under a unique model at a single site.
The figure given below shows the overall function of the data warehouse.
14
i) Gathering data from various data sources
Data warehouse collects data from various data sources such as relational databases,
flat files and on-line records.
The collected data are stored in databases inside the warehouse.
The type of data collection used depends on data warehouse architecture.
In a source the data are collected continuously or periodically.
But in destination periodically sends request to the data source to send data.
Knowledge
Patterns
3. Evaluation and Presentation
Data Mining
2. Selection and Transformation
Data warehouse
1. Cleaning and Integration
15
(i) Data cleaning :T o r em o ve t h e no i s e a n d inconsistent data
(ii) Data integration : Data from multiple sources are combined
(iii) Data selection : The relevant data are retrieved from database for analysis.
(iv) Data transformation : The selected data are made ready for mining by performing
aggregation operations
(v) Data Mining : intelligent methods are applied to extract data patterns
(vi) Pattern evaluation : Identify the needed patterns, representing knowledge based on some
measures.
(vii) Knowledge presentation: Present mined knowledge t o t h e u s e r b y u s i n g knowledge
representation techniques.
4. Banking Industry
Banking Market research (about Prof it and loss) .
Developing marketing programs.
Performance analysis of each product (Example: Loan, mortgage etc)
Interchange and exchange rates for various currencies .
5. Telephone Industry
They use warehouses for
Consolidating and integrating historical data.
Analysis of fixed assets of industry.
Tracking of customer queries, etc.
6. Manufacturing Industry
They utilizes for
To predict market changes, analyze current business trends.
Detect warning conditions, view marketing developments, etc.
16
DATA MARTS
17
Dependent Data Mart is created by extracting the data from central repository,
Datawarehouse.
First data warehouse is created by extracting data (through ETL tool) from external sources
and then data mart is created from data warehouse.
Dependent data mart is created in top-down approach of datawarehouse architecture.
This model of data mart is used by big organizations.
ii. Independent Data Mart
Independent Data Mart is created directly from external sources instead of data warehouse.
First data mart is created by extracting data from external sources and then datawarehouse
is created from the data present in data mart.
Independent data mart is designed in bottom-up approach of datawarehouse architecture.
This model of data mart is used by small organizations and is cost effective comparatively.
This type of Data Mart is created by extracting data from operational source or from data
warehouse.
1Path reflects accessing data directly from external sources and 2Path reflects dependent
data model of data mart.
18
BIG DATA
Big data is a data that are enormous in size and exceeds the processing capacity of regular or
traditional database system.
Thus big data includes huge volume, high velocity and extensible variety of data
Big data are produced from search engines, Social networks, weather forecast, etc.
It is used in enterprises, organizations, companies, business, etc.
Some of its applications are banking, agriculture, chemistry, data mining, cloud
computing, finance, marketing, stocks, health care, etc.
Given below are some of the fields that come under the big data
Black Box data: Airplane, jet etc. used to capture voice which helps during aircraft
Pow er Grid Data: Holds information about a particular node to a base station.
Social Media Data: Facebook, Twitter etc. are used big data across the globe.
Transport data: Includes model, capacity, distance and availability of a vehicle.
Stock Exchange Data : Hold information about the 'buy' and 'sell' decisions.
Search Engine Data: Retrieve lots of data from different databases.
1. Variety
Variety refers to the type of data that big data can contain. i.e.,
The variety may be structured or unstructured.
The structured data such as Table, data with its type etc.
The unstructured data such as Word, PDF, text, media logs.
19
2. Vel oci t y
Velocity refers to the time in which big data can be processed.
It measures the speed of data generation, filtering and arithmetic operation.
It is used for time sensitive processes. Ex. Fraud detection, big data flows.
3. Vol ume
Volume refers to the quantity of data collected by a company.
This data is used further to gain important knowledge.
Example: Using 700 billion annual meter reading to predict power consumption.
4. Veracit y
Veracity refers to the degree of trusted information to make a decision.
Finding the trusted data in big data is very important for business future.
When the number of data sources grows, the trust in big data is a big challenge.
5. Value
Value refers the usefulness of data in making decisions.
Data value depends on processes. It is required to collect data, stored longer.
Hence the data value is closely related to the data volume and variety.
I. Apache Hadoop
Hadoop can effectively store large amount of data in a cluster.
It is java based open source framework.
HDFS (Hadoop Distributed File System) is the storage system of Hadoop.
HDFS splits and distributes big data across many nodes in a cluster.
Hadoop has 3 components i.e.1. HDFS, 2. Map reduce, 3. YARN
II. Microsoft HD insight
It is a big data solution from Microsoft.
It is powered , by Apache Hadoop.
It is available as a service in the cloud.
III. NoSQL [Not Only SQL]
NoSQL deals with the unstructured unpredictable kind of data.
NoSQL gives better performance in storing massive amount of data.
It is not based on table formats.
It is scalable i.e., no need to expand server size.
Here data is stored as key value or document.
It refers to Hbase, Cassandra, Mongodb, Riak, and CouchDB.
IV. Hive
This is a distributed data management for Hadoop.
It supports SQL like query option Hive SQL (HSQL) to access big data.
It is used for data mining purpose.
20
V. Sqoop
It is a tool that connects Hadoop with various databases to transfer data.
This is effectively used to transfer structural data to Hadoop or Hive.
VI. PIG
PIG in Hadoop is similar to Hive developed by Yahoo.
PIG consists of a ‘Pert-like’ Language that allows for query execution.
It is fully open-source.
OVERVIEW OF NOSQL
NoSQL deals with the unstructured unpredictable kind of data.
NoSQL is defined as a database which has a set of common observations such as
NoSQL also called non-relational storage systems.
In this not using the relational model
It is running well on clusters
Execution steps are very less (i.e. Schema)
Mostly open-source
Reason for using NoSQL database as follows
Avoid complexity in relational databases.
No complexity in cost.
High throughput(Passing higher volume of data)
Running on any hardware easily.
21
DIFFERENCES BETWEEN RDBMS AND NOSQL
S.No RDBMS NoSQL
1 It is called Relational Database It is called non- relational database
2 It is table based It is document based
3 It is used as SQL - Structured Query Language It is used as un structured query
[Structured Means length & type of data] language
4 It is Vertically Scalable It is horizontally scalable
5 It is fit for Complex queries It is not fit for Complex queries
6 It is not fit for hierarchical database It is fit for hierarchical database
7 Example: MySQL, Oracle, SQLite, Postgres, Example: MongoDB, Big Table, Redis,
MS-SQL Server 2008 HBase, CouchDB and Neo4
1. Hadoop: Apache tool, used by many large corporations. This handles huge amount
of data sets in cluster based.
2. Cloudera: It is the most popular provider and supporter of Apache Hadoop. It reduces
business risks and gives the business a competitive advantage. This tool is used by all
corporate users who use the data for different purposes.
4. S t o r m : Storm does data processing capabilities in real time. It integrates with many other
tools such as Apache slider to manage and secure the data.
5. Cassandra: It is widely used tool, Manages large amount of data, Fault tolerance,
Durability and scalability. Users: eBay, Netflix
22
UNDERSTANDING STORAGE ARCHITECTURE
Big data architecture is the logical and physical layout of how big data will be stored,
accessed and managed within a big data or IT environment.
The storage architecture design is shown in fig.
Access-Request
Client Network
Message Sync.
Master Node
Local Balancing
Storage system access flow begins with ‘access request’ sent by ‘client’.
Then the message accesses near ‘master node’ server through network.
Now the ‘master node’ locates ‘data block’ in specified slave node depending on the client
request.
As long as connecting to the Internet, client terminal can access the system.
The terminal can be hardware, mobile devices, fixed devices, embedded devices, etc.
23
UNIT II RELATIONAL DATA MODEL & MYSQL ADMINISTRATION
Relational database is a collection of organized set of tables from which data can be accessed
easily.
CODD’S Rules
1
11. Logical data independence
Logical changes in the tables such as adding or deleting columns or changing field
lengths should not require modification on the program.
12. Systematic treatment / Null rule:
RDBMS distinguishes between zeros, blanks and nulls in the records and handles it. If
any constraints or rule is not provided, RDBMS must provide null value for the missed
values.
Components of RDBMS
1. Table Structure
Tables are the basic building blocks of relational database system. All the data are stored in
the tables in rows and columns. Headings are called attributes. Table can have zero or more rows
of data values. For example employee table is given below.
Explanation
3. Tuples: A table consists of number of rows. These rows are called tuples.
2
4. Degree: The number of attributes in a relation is called degree of the relation.
Example: The degree of the STUDENT table is 4 (columns).
6. Keys: Key is defined as an attribute or group of attributes are used to uniquely identify a tuple or
row in a relation.
Keys
Key is defined as an attribute or group of attributes that is used to uniquely identify a row in a
relation. The different types of keys are
Primary key is a column or a set of columns that is used to uniquely identify a row in a
relation. The primary key column values should be unique and not null. If more than one
column is used in primary key, it is called “Composite key”.
where
Example:
mysql > create table employee (empid int primary key , name varchar(40) , deptno int ,
salary int);
3
2) Composite key
If more than one column is used in primary key, it is called “Composite key”.
where
tablename - name of the table
Example:
mysql > create table employee (empno int , name varchar(40) , deptno int ,
3) Unique key
Unique key is a column or a set of columns that is used to uniquely identify a row in a
relation. It is similar to primary key in enforcing values to be unique, but allows null values.
where
Example:
mysql > create table employee (empno int , name varchar(40) , deptno int ,
4
4) Foreign Key
A foreign key is a column or set of columns in one table whose values must have matching
values in the primary key column of another table.
Consider a table “t1” has a column “c1” which is the primary key in another table “t2”. Then
the column “c1” in table “t1” which refers to the primary key of table “t2” is called “foreign
key”. Here, the table “t1” is called “child table” and the table “t2” is called “parent table”. The
data type and size of the foreign key should be same as that of the referring primary key.
Syntax :
where
Example:
mysql > create table employee (empno int , name varchar(40) , deptno int ,
Meta Data
5
Data Dictionary
The Data Dictionary holds the definitions of all the data tables. The data dictionary is also
called as catalog.
Data Integrity
2. Domain Integrity: Enforces valid entries for the given column by type format or range of
values.
3. Referential Integrity: Rows can’t be deleted which are used by other records.
4. User Defined Integrity: Enforces some business rules that don’t fall into entity, domain or
referential integrity.
Constraints are policies used to maintain the accuracy and integrity of data in the database.
Any one of the following constraints can be applied to the table.
Types of constraints
6
Table Name:
Using the above diagram, creating of 2 tables with constraint and without constraint
Syntax(Primary key):
Syntax(foreign key):
Example:
Parent table:
create table customer(custid int primary key, name varchar(25), address varchar(5));
Child Table:
create table accounts(accid int primary key, balance float(8,2), custid int, foreign key(custid)
references customer(custid));
Syntax:
7
Example:
Syntax:
Example:
Example:
create table student(rollno int primary key, name char(25), address varchar(5));
Example:
Create table student (rollno int, name varchar(25), address varchar(5),primary key(rollno));
It is used to verify whether the data entered is in proper form and range. It has
2 commands.
Example:
create table student(rollno int not null, name varchar(25), address varchar(5));
Syntax:
create table student(rollno int, name varchar(25), address varchar(5), not null(rollno));
Examples:
iv. LIKE: This is used to perform pattern matching. They are Percentage (%) &
underscore(_).
Example2: CHECK(name LIKE ‘R_j’); // Name; 1st letter is R & 3rd letter is J
Create table student(rollno int check(roll between 1001 and 1100), name varchar(25),
address varchar(10));
Example:
like ‘A%’));
9
Difference between MySQL & SQL
MySQL SQL
4 Selected data can be displayed, update and Selected data can be displayed, updated and
saved again with different name. saved with same name.
5 More Features like stored procedures, Features of procedures, triggers and cursor are
triggers and cursors are with sample in PL/SQL only.
procedure.
6 It has some constraints to update and delete No restrictions for Update and delete data.
data.
2.2 Normalization
Normalization
It is a process of building relational database structures without data redundant or duplicate
Benefits
Types of Normalization
• If every attribute of the table is atomic, that is the values should not be multi-
valued or composite.
10
Multi-valued attribute
Multi-valued attribute is the attribute that can have more than one value in a single
record. Consider the table “employee” where an employee can work in more than one
project as given below
2 babu web
Here, “proj_name” attribute is multi-valued and the table is not in 1NF. To conform to
1NF, the table is split into two as given below
Employee1: Employee2:
Composite attribute
Composite attribute is an attribute that follows some structure and can be split further
into meaningful data.
Here, “address” attribute is composite attribute and hence the table is not in 1NF. To
conform to 1NF, the structure of the table is changed as given below
11
2. Second Normal Form (2NF)
A relation is said to be in “second normal form” if both the following conditions hold
• table is in 1NF
The table is in 1NF because each attribute has atomic values. Here, (emp_id,
proj_id) is the primary key. The non-key attributes emp_name and emp_address are
dependent only on emp_id and not on proj_id. The non-key attributes proj_name and
proj_months are dependent only on proj_id and not on emp_id. So the table is not in 2NF.
To conform to 2NF, the table is split into 3 tables as follows
Table “employee”
E1 arun puducherry
E2 babu cuddalore
Table “project”
P1 bank 24
P2 school 12
P3 web 6
12
Table “emp_project”
emp_id proj_id
E1 P1
E1 P2
E2 P3
A relation is said to be in “third normal form” if both the following conditions hold
• Table is in 2NF.
The primary key is “emp_id”. Here, the non-key attributes “name” and “city” are
directly dependent on the primary key “emp_id”; the non-key attribute “state” is dependent
on “city” and transitively dependent on “emp_id”. This violates the rule of 3NF. To conform to
3NF, the table is split into two table as follows.
Table “employee”
13
Table “city_state”
CITY STATE
Puducherry Puducherry
Cuddalore Tamilnadu
chennai Tamilnadu
MYSQL FEATURES
Relational Database Management System (RDBMS)
Easy to use
It is secure
Client/ Server Architecture
Free to download
Compatible on many operating systems
Allows roll-back
High Performance
High Flexibility
High Productivity
DOWNLOADING MYSQL
To install MySQL server version 8.0 on windows, the minimum operating system requirements is
windows 10.
The installation procedure is given below.
1) Execute MySQL installer.
2) In the License Agreement window, enable I accept the license terms and click it.
3) In the Choosing a setup type window, choose the appropriate setup type for your system.
i) Choose Developer default to install MySQL server and other MySQL tools
related to MySQL development, helpful tools like MySQL workbench.
ii) Or choose the custom setup type to manually select your desired MySQL
products.
Click next.
4) Next installation window appears. It shows the products to be installed. Click Execute.
5) After the products are installed, installation window shows next button. Click it.
6) Next Product Configuration window appears. Click next.
7) Next Type and Networking window appears. In the Config Type, Select Development Machine
and Click Next.
14
8) Next Accounts and Role Window appears. Here give MySQL root password. If necessary, add
one user and click next.
9) In the windows service window, keep the default options as it is and click next.
10) Now Plugins and Extensions window appears. Click next.
11) In the Apply server configuration window, with Configuration steps tab chosen by default, click
Execute.
12) After the configuration is completed, click Finish.
13) Finally, connect to server window appears which indicates that MySQL server 8.0 is
successfully installed. Now to check whether the main user root is connected successfully with
the server, click the button check. Connection successful message appears. Click next.
14) Next Apply server configuration window with log tab enabled appears. Click Execute.
15) After the configuration is completed, finish button appears, Click it.
16) Now in the product configuration window, click next.
17) And finally installation complete window appears. Click finish for completion.
Click start All programs MYSQL From that choose MYSQL Administrator Give Password for
root.
Enter password: ****
After connecting to the MySQL server, the mysql> prompt appears. Now user can
enter the sql commands. To see the command line help type ‘\h’ on the mysql prompt.
mysql>
mysql> QUIT
mysql> exit
15
2.4 Working with MYSQL Admin
1. Creating Database
Create database command is used to create a new database.
Once the database has been created, you will need to select it in order to begin working.
i. Use()
ii. Select()
Output:
DATABSES()
polytechnic
4. Showing Database
Show database command is used to list all the existing databases in the server.
16
Output
Databases
------------------------
Information_schema
Mysql
Performance_schema
Test
Polytechnic_college
5. Describing Database
Backing up Databases
Restore Database
To restore the database MPC available in the file d:\backupfile.sql, give the
following command.
Syntax
mysql –u root –p database name < drivename:\backupfilename.sql.
Example
17
UNIT –III INTERACTIVE MYSQL
MySQL uses many different data types broken into four categories
Strings can have anything, even arbitrary binary data such as images or sounds.
4. Spatial Types
Data Definition commands are used to do the following operations on the database objects. The
operations are,
1. Creating tables
2. Altering tables
3. Renaming tables
4. Copying tables
5. Deleting tables
2
1. Creating Table
The MySQL CREATE TABLE command is used to create a new table into the
database. A table creation command requires three things:
Name of the table
Names of fields
Definitions for each field
Syntax
CREATE TABLE tablename (columnname1 datatype, columnname2 datatype ...);
Example
Here, we will create a table named as "stud" in the database "student".
Create table stud (id int primary key, name varchar (50));
2. Altering Table
Syntax
Example
Syntax
Example
It changes the width of the address field from 50 to 60 in the table student.
3
III. Datatype of the column can be dropped
Syntax
Example
Syntax
Example
It changes the column dateofbirth in table student to dob with the column definition date;
3. Renaming Table
Syntax
RENAME TABLE oldtablename TO newtablename;
4. Copying Table
Syntax2 CREATE TABLE newtablename select col1, col2, col3 from existing table;
4
5. Deleting Tables
Truncate
TRUNCATE statement removes the complete data without removing its structure.
Drop
It is used to delete a structure of table permanently.
1. Insert
The Insert command is used to add one or more rows to a table.
Output
ROLLNO NAME M1
1 ANU 98
Output
ROLLNO NAME M1
1 Anu 98
2 Balu
Syntax Insert into table name (col1, col2, ..) Values (value1, value2...), (value1, value2...),
(value1, value2...);
Example insert into student (rollno, name, m1) values (3,'banu',100), (4,'pavi',79), (5,'senthil',99);
5
Output
ROLLNO NAME M1
1 Anu 98
2 Balu
3 Banu 100
4 Pavi 79
5 Kumar 99
2. Update
Output
ROLLNO NAME M1
1 Anu 98
2 Balu 100
3 Banu 97
4 Pavi 79
5 Kumar 99
3. Delete
The delete command is used to delete rows from a table. To delete a row
Example
i. To delete a specified row: Delete from student where rollno =1;
Output
ROLLNO NAME M1
2 Balu 100
3 Banu 97
4 Pavi 79
5 Kumar 99
6
Data retrieval commands
The SELECT command is used to retrieve the stored data from the table.
Output
ROLLNO NAME M1
2 Balu 100
3 Banu 97
4 Pavi 79
5 Kumar 99
ROLLNO NAME
Output 2 Balu
3 Banu
4 Pavi
5 Kumar
7
5. Selects rows in ascending / descending order
MySQL Operators
Generally there are three types of operators in SQL:
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
Let's assume two variables "a" and "b". Here "a" is valued 50 and "b" valued 100.
+ It is used to add containing values of both operands a+b will give 150
- It subtracts right hand operand from left hand operand a-b will give -50
/ It divides left hand operand by right hand operand b/a will give 2
% It divides left hand operand by right hand operand and b%a will give 0
returns reminder
Let's take two variables "a" and "b" that are valued 50 and 100.
= Examine both operands value that are equal or not,if yes condition (a=b) is not true
become true.
!= This is used to check the value of both operands equal or not,if not (a!=b) is true
condition become true.
<> Examines the operand?s value equal or not, if values are not equal (a<>b) is true
condition is true
> Examine the left operand value is greater than right Operand, if yes (a>b) is not true
condition becomes true
< Examines the left operand value is less than right Operand, if yes (a<="" td="">
condition becomes true
8
>= Examines that the value of left operand is greater than or equal to (a>=b) is not true
the value of right operand or not,if yes condition become true
<= Examines that the value of left operand is less than or equal to the (a<=b) is true
value of right operand or not, if yes condition becomes true
Operator Description
AND This operator allows the existence of multiple conditions in an SQL statement.
NOT the NOT operator reverse the meaning of any logical operator
Expressions
Expressions are formed using operands and operators. Mostly expressions are used in select
commands after where clause.
Example 1 select * from student where dept=’cse’;
Example 2 select * from student where dept=’cse’ and marks > =75;
Pattern Matching
We can perform pattern matching using operator LIKE with wildcard characters. The wildcard ‘_‘
matches any single character, ‘%’ matches any number of characters.
To find names containing exactly five characters, use five instances of the _ pattern character:
9
Importing Data
We can keep our raw data in a text file, and load them into the table via the LOAD DATA
command.
For example, use a text editor to create a new file called “production.CSV” under
“d:\mysqlprograms”.
The file contains the following records.
Here the values are separated by ‘,’.
The file extension of “.CSV” stands for Comma Separated Value text file.
Pnc, pencil 3B, 600,0.52
Pnc, pencil 4B, 300,0.62
Pnc, pencil 5B, 200, 0.73
Pnc, pencil 6B, 600, 0.47
We can load (import) the raw data into the products table as follows.
Example
load data local infile ‘d:/mysqlprograms/productin.csv’ into table products
columns terminated by ‘,’ lines terminated by ‘\r\n’;
Exporting Data
We can use select ….. into outfile filename from tablename to export data from a table to a text
file.
Example
Select * from products into outfile ‘d: /mysqlprograms/productin.csv’
columns terminated by ‘,’ lines terminated by ‘\r\n’;
3.3 Built-in Functions
i. Numeric Functions
ii. STRING Functions
iii. Date and Time Functions
iv. Conversions functions
10
i. Numeric Functions
S. Function
Meaning Example Result
No Name
1 ABS(X) Returns the absolute value of x Abs(-12.5) 12.5
2 Exp(x) Returns ex Exp(1) 2.718
3 Log 10(x) Returns the logarithm of x to the base 10 Log10(10) 1
Returns xy Pow(2,3) 8
7 Pow(x,y)
Returns the largest integer not greater than
Floor(3.8) 3
8 Floor(x) x
Returns the smallest integer not greater
Ceil(3.6) 4
9 Ceil(x) than x
11
concatenates two concat(‘poly’,’technic’)
4 Concat(str1,str2)
strings str1 and str2
‘polytechnic’
and returns the
resultants string
Returns the Hex(16)
5 hex(n)
hexadecimal
10
representation of the
number n.
Converts str into Lcase(‘COLLEGE’)
6 Lcase(str) college
lowercase letters
Converts str into ucase(‘college’)
7 Ucase(str) COLLEGE
uppercase letters
Reverses the string str Reverse(‘college’)
egelloc
8 Reverse(str)
Returns a substring Substr(‘polytechnic’,5)
9 Substr(str,pos)
from the string str,
Technic
beginning at position
pos.
Returns the right most Right(‘polytechnic’,7)
10 Right(str,len)
len characters from the Technic
string str
Returns the left most Left(‘polytechnic’,4)
11 Left(str,len)
len characters from the poly
string str
12
5 Date(expr) Returns the date part of the Date(‘2017-06-12 2017-06-12
expression 13:14:22’)
6 Day(date) Returns the numeric value of 12
Day(‘2017-06-12’)
the day of the month for date
7 Last_day(date) Returns the date for the last Last_day(‘2017-06-12’) 2017-06-30
day of the month in which the
argument falls
8 Minute(time) Returns the numeric value of Minute(’12:31:58’) 31
the minute for the time value
time, in the range from 0 to 59
9 Month(date) Returns the numeric value of Month(‘2003-12-01’) 12
the month of the year for date
10 Time(expr) Returns the time part of expr. Time(‘2006-03-11, 16:15:05
16:15:05’)
S.
Function Name Meaning Example Result
No
1 Cast(expr as type) Converts an expression Cast(404 as binary) ‘404’
value expr to a given Cast(13 as decimal (5,2)) 013.00
type Cast(20080202 as date) 2008:02:02
2 Convert(expr,type) Same a cast(), but Convert(304,binary) ‘304’
different syntax Convert(13,decimal(5,2)) 13.00
Convert(20080202,date) 2008:02:02
2. Aggregate / Group Functions
13
5 Std(expr) Returns the standard deviation of Select std(mark) from 2.5
expr for all non-NULL values student;
6 Sum(expr) Returns the sum of expr for all Select sum(mark) from 750
non-NULL values student;
7 Variance(expr) Returns the variance of expr for all Select variance(mark) 6.29
non-NULL values from student;
Example
1. WHERE Clause
The WHERE clause is used to select some specific rows from table according to a given condition.
Syntax Select columnname from tablename where condition;
50 REKHA EEE C
2. GROUP BY Clause
This clause is used to group the rows from a table based on some condition.
GRADE
A
B
C
3. HAVING Clause
The HAVING clause is used in the select statement to specify filter conditions for a group of
rows.
This clause is often used with the group by clause.
Syntax Select columnname from tablename group by columnname having condition;
14
Example Select branch from students group by branch having count (*) =2;
Explanation This query groups the 2 CSE rows from the specified table
BRANCH
CSE
4. ORDER BY Clause
This query is used to display the rows from the table in the ascending order or
descending order.
Syntax Select columnname from tablename order by columnname [desc/asc];
To display the selected row in descending order:
SNO SNAME
50 REKHA
40 RAJ
30 POOJA
20 INDIRA
10 KUMAR
To order the student table by displaying name starting from R
Example2 Select sno, sname from students where sname like ‘r%’ order by sno desc;
SNO SNAME
50 REKHA
40 RAJ
MYSQL Subquery
Sub-query is defined as a query within a query.
That is one select query contains another select query.
The inner query will be executed first.
Operators Used in Sub-Query
1) ANY
2) ALL
3) SOME
4) IN
5) NOT IN
6) EXISTS
7) NOT EXISTS
Syntax
Let us consider the table’s students & marks to understand sub queries.
15
Students table
1. IN
It compares two tables and lists the common records.
Example
Select sno, sname from students where sno IN (Select no from marks);
Output
Sno Sname
10 Kumar
20 Indira
Explanation
The outer query displays the ‘sno, sname’ of the students from the table students whose
sno is present in marks table also.
2. NOT IN
It compares two tables and lists the common records.
Example Select sno, sname from students where sno NOT IN (Select no from marks);
Output
Sno Sname
30 Pooja
40 Raj
50 Rekha
Explanation
The outer query displays the ‘sno, sname’ of the students from the table students whose
sno is not present in marks table .
3. ANY
It compares two tables and selects any value based on some condition.
Example Select sno, sname from students where sno>=ANY (Select no from marks where
no>=40);
Output
Sno Sname
40 Raj
50 Rekha
Explanation
The outer query displays the ‘sno, sname’ of the students whose no>=40.
16
4. ALL
It compares two tables and lists all the fields under the given condition.
Example Select * from students where sno ALL (select no from marks where total>=400);
Output
Correlated Sub-queries
Inner query is evaluated first and then the outer query is evaluated first and then the
outer query inner query is evaluated
1. IF()
2. IF NULL()
3. CASE
4. LOOP
5. LEAVE
6. ITERATE
7. REPEAT
8. WHILE
1. IF()
Syntax if (expr1,expr2,expr3)
Explanation
2. IF NULL()
Syntax ifnull(expr1,expr2)
3. CASE
Syntax
case casevalue
when compare_value1 then statementlist1
when compare_value2 then statementlist2
...
else statement listN
end case
Here, casevalue is an expression.
This value is compared to the comparevalue expression in each When clause until one of
them is equal.
When an equal comparevalue is found the corresponding Then clause Statementlist executes.
If no comparevalue is equal, the Else clause Statementlist execute.
Example
Begin
Declare V int default 3 ;
Case V
When 1 THEN 'one'
When 2 THEN 'two'
else 'invalid input'
END case;
END;
Output 'invalid input'
18
4. LOOP
Example
BEGIN
Declare p1 int default 1;
start: LOOP
SET p1 = p1 + 1;
IF p1 < 10 THEN
ITERATE start;
END IF;
LEAVE start;
END LOOP start;
END;
5. REPEAT
Syntax
REPEAT
statement_list
UNTIL searchcondition
END REPEAT;
The statement list within a REPEAT statement is repeated until
the search_condition expression is true.
Thus, a REPEAT always enters the loop at least once.
statement_list consists of one or more statements, each terminated by a
semicolon (;) statement delimiter.
A REPEAT statement can be labeled.
19
Example
BEGIN
Declare x int default 1;
REPEAT
SET x = x + 1;
UNTIL x <5
END REPEAT;
END
6. WHILE
Syntax
WHILE condition DO
statement_list
END WHILE
The statement list within a WHILE statement is repeated as long as the
condition expression is true.
statement_list consists of one or more SQL statements, each terminated by a
semicolon (;) statement delimiter.
A WHILE statement can be labeled.
Example
BEGIN
DECLARE v1 INT DEFAULT 5;
WHILE v1 > 0 DO
SET v1 = v1 - 1;
END WHILE;
END;
7. LEAVE
This statement is used to exit the flow control construct that has the given label.
If the label is for the outermost stored program block, LEAVE exits the program.
LEAVE can be used within BEGIN ... END or loop constructs (LOOP, REPEAT,WHILE).
8. ITERATE
ITERATE can appear only within LOOP, REPEAT, and WHILE statements.
ITERATE means “start the loop again.”
20
UNIT IV: MYSQL PERFORMANCE TUNING
4.1.1 Indexes
MySQL uses the indexes to select exact physical corresponding rows of the table.
Index uses pointer that points a particular record directly
Indexes are used to speed up execution of SQL statements on a table
It is used to search and find a particular row in a table faster.
Creating Index
Indexes can be created on selected column to facilitate fast search.
TYPES OF INDEX
The index can be created on selected columns to facilitate fast search. But it requires more
memory. The types are
1. Simple Index (or UNIQUE Index)
2. Composite Index (or Compound Index)
1. Simple index
This index has with single column to prevent duplicate and null value.
[Now the object idx1 (user defined) is applied on rollno column of student table]
2. Composite Index
This index has with more than one column to prevent duplicates and null values.
[Now the object idx1 (user defined) is applied on rollno & regno columns of student table]
Dropping Index
1
4.1.2 Sequences
The sequences are list of integers generated in the ascending order i.e. 1.2.3..
Example: CustomerId, RegisterNumber, RollNumber, TransactionNo
Rules
- It must be integers only
- In MYSQL the sequences uses auto_increment keyword
- It must be indexed by PRIMARY KEY or UNIQUE
- Generally NOT NULL keyword is Implicit or we can represent explicitly.
1. Creating sequences
Sequence can be created in the create table with auto_increment and primary key.
Example Create table student (rollno int auto_increment primary key, name
varchar (20), address varchar (20));
For testing
insert into student (name, address) values ('balan', 'chennai'), ('saravanan', 'trichy');
Output
Select * from student;
Rollno Name Address
1 Balan Chennai
2 Saravanan trichy
[In the output we didn’t input the Roll number but it is automatically generated]
2. Altering Sequences
For testing
In this output, the starting value was generated from 1001 by auto_increment.
2
3. Deleting sequences
4.2 VIEWS
1. Creating views
Example Create view stud_view as select rollno, total from college where total>=500;
[From College base table we select only Rollno & Total Columns about those are taken
total>=500. Now the output ‘2 rows returned’ will get. ]
Rollno Total
100 500
103 600
3
2. Updating Views
Now the Name field is updated in the same View name ‘stud_view’
Types of Joins
1. Natural join
2. Inner join
3. Left join
4. Right join
5. Self-join
Student Table
Rollno Name
100 Abi
101 Bala
102 Chiti
4
Mark Table
Rollno Name Marks
100 Abi 500
101 Bala 400
103 Dinesh 300
1. Natural Join
Columns with same name of multiple tables will appear once only.
ON clause should not be used.
The identical columns should have same data types.
3. Left join
It returns all records from the left hand side table of LEFT JOIN command and the
matched records from the right table.
Image representation
Example Select student.rollno, mark.name from student left join mark on student.rollno=mark.rollno;
Output
Rollno Name
100 Abi
101 Bala
102 null
5
4. Right Join
It returns all records from the right hand side table of RIGHT JOIN command and the
matched records from the left table.
Image representation
Example Select student.rollno, mark.name from student right join mark on student.rollno=mark.rollno;
5. Self Join
Joining a table itself called self join. This combines the rows with other rows of the same table.
It uses both table for left hand and right hand side.
Syntax select columnnames from table1 as object1 join table1 as object2 on
object1.column=object2.column;
Output
Rollno Name Name
10 Kumar Indra
15 Kannan Indra
20 Indira Kannan
25 selvi Kannan
6
4.3.2 UNIONS
It is a set operator used to combine the result of two queries into a single one.
The types are
1. Union [or Union Distinct]
2. Union All
Student Table
rollno name
100 raj
101 nagaraj
102 mala
103 raj
104 mala
Mark Table
This operator combines rows of data from two SELECT statements and returns all
distinct values.
Syntax select columnames from tablename1 union select columnnames from
tablename2;
Example select name from student union select name from mark;
Output
name
raj
nagaraj
mala
suresh
Example select name from student union select name from mark order by name asc;
Output
name
mala
nagaraj
raj
suresh
7
ii) Union or Union Distinct with LIMIT handling
Example Select name from student union select name from mark limit 2;
Output
name
raj
nagaraj
2. Union all
This operator combines rows of data from two select statements and Returns all the
rows including duplicate rows.
Syntax Select columnames from tablename1 union all select columnnames from
tablename2;
Example Select name from student union all select name from mark;
Output name
raj
nagaraj
mala
raj
mala
raj
suresh
mala
4.4.1 USER
The USER is actually a record in the 'USER' table of the MySQL server which contains the
following.
Login information (username & password).
The corresponding account privileges.
Client information for MySQL account.
We can use the MySQL USER for the web applications also.
1. Creating Users
Now the user can login into the user name: ‘student’ and password: ‘admin123’
8
2. Showing Users
Output User
Staff
Student
root
3. Renaming Users
4. Dropping Users
Generally the new users have no any permission to do the operations. Hence the GRANT
command is used to give the rights to the new users.
It has 2 types.
1. Grant all privileges
2. Grant specific privileges.
Where,
New user : refers the name of the user which is already exists.
9
2. Grant Specific Privileges
Where the user ‘kumar’ has create rights to ‘polytechnic’ database only
Where the user ‘kumar’ has insert and granting rights to someone else
Once we have finalized the permissions that we want to set up for the new users, always we
have to be sure to reload all the privileges.
The REVOKE command is used to cancel the rights from the users.
It has 2 types.
1. Revoke all privileges
2. Revoke specific privileges.
OPTION
Where the user ‘kumar’ cancels his create rights from ‘polytechnic’ database.
10
Example2 Revoke create on *.* from kumar;
Where the user ‘kumar’ cancels his create rights from any database.
Where the user ‘kumar’ cancels his insert and grant option rights from all databases
1. COMMIT
It is used to end the transactions and make them permanent of changes.
Syntax commit;
Example
Creating a table
Using Commit
MYSQL> commit;
Output
id
1
2
11
2. ROLLBACK
It is used to undo changes made during transaction.
Syntax rollback;
Example
Starting transaction:
MYSQL> start transaction;
Inserting rows into the table test:
MYSQL> rollback;
Output id
1
2
SAVEPOINTS
MySQL enables us to perform a partial rollback of a transaction.
Save point statement is used within the transaction to set a marker.
Example
Creating a table
MYSQL> create table stud (regno int);
Starting transaction
12
UNIT V: STORED PROGRAM CONCEPTS AND DEVELOPMENT
Stored Procedure
Stored procedure is a group of query that are compiled, verified and Stored in the server data
base.
Stored Procedures do not return a result directly but can be used to perform general computations
or produce result sets.
Then the results are passed back to the client.
A stored procedure can be invoked by triggers, other stored procedures and applications such as Java,
Python, PHP, etc,.
Syntax:
MYSQL> delimiter $$
MYSQL> create procedure procedurename (arguments)
begin
Declaration statements
Executable statements
end $$
MYSQL> delimiter ;
a) Specification
b) Body
Specification part begins with the keyword create procedure and ends with the parameter list or
parameter name.
Body part begins with the keyword begin and ends with the keyword end.
1
MYSQL stored procedures variables
MYSQL>delimiter $$
MYSQL> create procedure getoffice (countryname varchar(10))
begin
select * from emp where country=countryname;
end $$
MYSQL> delimiter;
Suppose, we want to get all offices in ‘India’, we just need to pass a value i.e. India to the
stored procedure as follows:
Mysql> call getoffice(‘India’);
Modes of Parameter
2
Employee table
EID EMP_NAME
101 ADITHIYA
102 BAKYA
103 DEEPA
104 SARAVANAN
105 YUVARAJ
1. IN Parameter
This passes the value by IN parameter and display the output directly.
Example
MYSQL> delimiter$$
MYSQL> create procedure empdet (IN id int)
begin
select * from employee where eid=id;
end $$
MYSQL>delimiter;
Output
EID EMP_NAME
102 BAKYA
2. OUT Parameter
This passes the value by IN parameter and stores its results by OUT parameter and
displays the output.
Example
MYSQL> delimiter$$
MYSQL> create procedure empdet (in id int, out name varchar (20))
begin
select emp_name into name from employee where eid =id;
end $$
MYSQL> delimiter ;
Output
EMP_NAME
BAKYA
3
3. IN OUT Parameter
This passes the value and stores its results by a single parameter called IN OUT.
Example
MYSQL> delimiter$$
MYSQL> create procedure empdet(in out rollno int)
begin
select count(*) into rollno from employee where emp_name like 'a%';
end $$
MYSQL> delimiter ;
Output
@rollno
101
Stored Functions
A stored function is a special kind of stored program that returns a single value.
Creating Function
Syntax
MYSQL> delimiter $$
MYSQL> create function functionname(parameters)
returns datatype
[NOT] [deterministic]
begin
Declaration part;
Execution part;
return (value);
end $$
MYSQL> delimiter ;
4
The function has;
Function specification: It begins with CREATE FUNCTION and ends with RETURNS data
type.
Function body: It begins with BEGIN and ends with the END
In function, all parameters are IN as default parameter.
If the function returns the result then it is called deterministic
Otherwise non deterministic.
Calling functions
Used to execute the stored function.
Syntax function_name(Parameter value);
‘User’ table
Username Phonenumber Address
Kumar 9841412545 Chennai
Kalai 6369401526 Trichy
Prabha 9445789642 Tirunelveli
Example to create function: This is used to find the address of a phone no.
MYSQL> delimiter$$
MYSQL> create function findaddress (phno varchar (20))
returns varchar (20)
begin
declare addr varchar (20);
select address into addr from user where phonenumber =phno;
return addr;
end $$
MYSQL> delimiter;
Output Findaddress(9841412545)
Chennai
5
Deleting stored Functions
The statement used to delete a stored function.
Advantages
1. Stored functions that are reusable among SQL statements or stored programs.
2. Stored functions can be used in SQL statements wherever an expression is used.
3. This improves readability and maintainability of the procedural code.
5.2.1 TRIGGERS
Trigger is a statement that is executed automatically by the system as a side effect
of a modification to the database.
Advantages of triggers
Triggers are used to check the changes in the databases
They can be used to record every change to every record in the table.
They are used to ensure the integrity of data.
Triggers can undo an attempt to change data.
They can undo an attempt to change the structure of the database.
Creating Trigger
delimiter$$
create trigger triggername {before/after} (insert/update/delete}
on tablename for each row
begin
trigger body ;
end $$
delimiter ;
Where
CREATE...TRIGGER is a statement. Anyone within{} is must.
Parts of the Trigger:
a) Trigger statement:
The DML statement (INSERT/UPDATE/DELETE) is called the
trigger statement. It fires the trigger body.
b) Trigger body:
Stores the logical part of program;
c) FOR EACH ROW:
The trigger body will be fired once for each row.
6
Types of triggers
Output:
authorid titlename
301 C Programming
302 RDBMS
303 Computer Architecture
7
7. Creating a trigger to update the titlecount of authors table when inserting into titles table
MYSQL>delimiter $$
begin
end $$
MYSQL>delimiter ;
Deleting Triggers
To delete or drop the trigger, DROP TRIGGER statement is used.
5.2.2 CURSORS
Cursor is a temporary work area used by the MYSQL server to execute MYSQL statements and
to store the processed information. The cursor commands are DECLARE, OPEN, FETCH and CLOSE.
They are explained below
1. DECLARE statement
This statement is used to declare the cursor before use.
8
2. OPEN statement
4. CLOSE statement
Finally we can use the CLOSE statement to deactivate the cursor and release the memory associated with it.
When working with MYSQL cursor, we must also declare a NOT FOUND handler to handle
the situation when the cursor could not find any row. Because each time we call the FETCH
statement, the cursor attempts to read the next row in the result set. When the cursor reaches the
end of the result set, it will not be able to get data, and a condition is raised. The handler is used to
handle this condition.
Where finished is a variable to indicate that the cursor reached the end of the result set. The
handler
declaration must appear after variable and cursor declaration inside the stored procedures.
Example program
‘Employee ‘Table
Empno Empname Designation Netsalary
100 Rani Lecturer 50000
101 Kumar Lecturer 45000
102 Deepa Lecturer 40000
103 Muthu Lecturer 45000
9
mysql> delimiter$$
mysql> create procedure cursoremp (in empid int)
begin
declare finished int(1);
declare eno int;
declare ename varchar(25);
declare netsal decimal(6,2);
declare salarycursor cursor for select empno, empname, netsalary from
employee;
Deleting cursor
It is used to delete the cursor completely.
Syntax Drop cursor cursorname;
Example Drop cursor cursoremp;
10
5.3 MYSQL Web
MYSQL distributions include a set of client programs. For example, the client program permits us
to interact with the server to execute SQL statements.
In MySQL our own program can prompt input from the user and reads a value
These methods are easier to use.
Users need not know SQL.
11
2. The DBI API for perl: The figure shows about the perl functions
Explanation
DBI is implemented as a Perl script module.
This module interfaces with other modules at the DBD(Database Driver)level.
This provides access to a specific data base engine.
MYSQL can be used with DBI to create scripts. These scripts can be invoked from the
command line or by web browser.
DBI API is used within the applications written for the perl scripting Language.
DBI works with data bases using perl modules that work in a two-level architecture.
12