Getting Started With
MySQL II
Database Views
2
A database view is a virtual table or logical table which is defined as a SQL
SELECT query with joins.
Most database management systems, including MySQL, allow you to update data
in the underlying tables through the database view with some prerequisites.
Advantages of database view:
• A database view allows you to simplify complex queries: a database view is
defined by an SQL statement that associates with many underlying tables.
• A database view helps limit data access to specific users.
• A database view provides extra security layer.
• A database view enables computed columns.
Database Views
3
Disadvantages of database view:
• Performance: querying data from a database view can be slow especially if the
view is created based on other views.
• Tables dependency: you create a view based on underlying tables of the
database. Whenever you change the structure of those tables that view
associated with, you have to change the view as well.
Database Views – CREATE VIEW
4
Syntax:
CREATE
VIEW [database_name].[view_name]
AS
[SELECT statement]
There are some rules that the SELECT statement must follow:
• The SELECT statement can contain a subquery in WHERE clause but not in
the FROM clause.
• The SELECT statement cannot refer to any variables including local
variables, user variables, and session variables.
Database Views – CREATE OR REPLACE
VIEW
5
You can use CREATE OR REPLACE VIEW statement to either create or replace
an existing view. If a view already exists, MySQL simply modifies the view. In
case the view does not exist, MySQL creates a new view.
Syntax:
CREATE OR REPLACE
VIEW [database_name].[view_name]
AS
[SELECT statement]
Database Views – CREATE VIEW
6
Execute the example below in World database.
Database Views – CREATE OR REPLACE
VIEW
7
Execute the example below in World database.
Stored Procedures
8
Introduction to MySQL Stored Procedures
A stored procedure is a segment of declarative SQL statements stored inside
the database catalog.
A stored procedure can be invoked by triggers, other stored procedures, and
applications such as Java, Python,R, PHP, ERP etc.
Stored Procedures
9
MySQL stored procedures advantages:
• Typically stored procedures help increase the performance of the
applications. Once created, stored procedures are compiled and stored in
the database.
• Stored procedures help reduce the traffic between application and
database server because instead of sending multiple lengthy SQL
statements, the application has to send only name and parameters of the
stored procedure.
• Stored procedures are reusable and transparent to any applications.
• Stored procedures are secure.
Stored Procedures
10
MySQL stored procedures disadvantages
• If you use a lot of stored procedures, the memory usage of every
connection that is using those stored procedures will increase
substantially.
• Constructs of stored procedures make it more difficult to develop stored
procedures that have complicated business logic.
• It is difficult to debug stored procedures. Only a few database
management systems allow you to debug stored procedures.
Unfortunately, MySQL does not provide facilities for debugging stored
procedures.
• It is not easy to develop and maintain stored procedures.
Stored Procedures
11
Steps:
1 Right Click on Stored Procedure – Create Procedure
Stored Procedures
12
Steps:
2 Enter your commands in the editor and SAVE. Give the procedure a name.
Click on Apply.
Stored Procedures
13
Steps:
3 Your procedure can now be called programmatically or in the SQL Editor as
below: Call GetCountryDetails();
The statements in the procedure will get executed.
Triggers
14
A trigger or database trigger is a stored program executed automatically
to respond to a specific event e.g., insert, update or delete occurred in a
table.
A SQL trigger is a special type of stored procedure. It is special because it is
not called directly like a stored procedure. The main difference between a
trigger and a stored procedure is that a trigger is called automatically when a
data modification event is made against a table whereas a stored procedure
must be called explicitly.
Triggers
15
Advantages of using SQL triggers
• SQL triggers provide an alternative way to check the integrity of data.
• SQL triggers can catch errors in business logic in the database layer.
• SQL triggers provide an alternative way to run scheduled tasks. By using
SQL triggers, you don’t have to wait to run the scheduled tasks because
the triggers are invoked automatically before or after a change is made to
the data in the tables.
• SQL triggers are very useful to audit the changes of data in tables.
Triggers
16
Disadvantages of using SQL triggers
• SQL triggers only can provide an extended validation and they cannot
replace all the validations. Some simple validations have to be done in the
application layer. For example, you can validate user’s inputs in the client
side by using JavaScript or in the server side using server-side scripting
languages such as JSP, PHP, ASP.NET, Perl, etc.
• SQL triggers are invoked and executed invisible from the client
applications, therefore, it is difficult to figure out what happens in the
database layer.
• SQL triggers may increase the overhead of the database server.
Triggers
17
Example:
We want to capture the details of people performing any action on a
particular table employee, actions such as anyone executing BACKEND
UPDATE should get captured. For this we need to first create an Audit table
which will store these details as below:
CREATE TABLE employees_audit (
id INT AUTO_INCREMENT PRIMARY KEY,
emp_id INT NOT NULL,
last_name VARCHAR(50) NOT NULL,
first_name VARCHAR(50) NOT NULL,
jobtitle varchar(100),
changedate DATETIME DEFAULT NULL,
action VARCHAR(50) DEFAULT NULL);
Triggers
18
Example:
Next step would be writing the trigger.
DELIMITER $$
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employee
FOR EACH ROW
BEGIN
INSERT INTO employees_audit
SET action = 'update',
emp_id = OLD.emp_id,
last_name = OLD.last_name,
first_name = OLD.first_name,
jobtitle = OLD.jobtitle,
changedate = NOW();
END$$
DELIMITER ;
Triggers
19
Example:
Now we will fire an update on the employee table
update employee set jobtitle = 'programmer' where emp_id = 2;
This action will get captured in employees_audit table and can be viewed
later.
MySQL for Excel
20
• MySQL for Excel enables you to work with a MySQL database from
within Microsoft Excel.
• MySQL data can be imported into Excel, Excel data can be
exported into MySQL as a new table or appended to a current
table, and MySQL for Excel enables you to edit the MySQL data
directly from within Excel.
MySQL for Excel
21
Import MySQL Data into Excel
Data can be imported from MySQL into a Microsoft Excel spreadsheet by
using the Import MySQL Data option after selecting either a table, view, or
procedure to import.
Append Excel Data into MySQL
Data from a Microsoft Excel spreadsheet can be appended to a MySQL
database table by using the Append Excel MySQL Data to Table option.
Export Excel Data into MySQL
Data from a Microsoft Excel spreadsheet can be exported to a new MySQL
database table by using the Export Excel Data to New Table option. Exporting
data looks like so:
MySQL for Excel
22
Example:
Open the excel you want to export/Import data from. Click on MySQL for
Excel
Pre-requisite for doing the same is to install the MySQL Add-on utility
MySQL for Excel
23
Example:
Click on Local Instance MySQL. Enter the password requested and click OK
MySQL for Excel
24
Example:
Select the database in which you want to create a new table or append an
existing table with this excel data
MySQL for Excel
25
Example:
If you want to create a new table, then select the excel sheet and click on Export Excel
Data to New table and then give the name of the table in the column for Name in the
dialogue box. Click on Export Data
MySQL for Excel
26
Example:
After clicking Export Data below screen should appear
MySQL for Excel
27
Example:
Login to backend to check a new table is created and verify rows inserted. Similarly you
can explore more options available in the MySQL for Excel utility
To work with MySQL database in R
28
mydb <- dbConnect(MySQL(), user='user', password='password',
dbname='database_name', host='host')
# Create a database connection object.
install.packages(“RMySQL”)
library(RMySQL)
# Save a results set object to retrieve data from the database
rs = dbSendQuery(mydb, "select * from some_table")
# Access the result in R
data = fetch(rs, n)
Queries can be run using the dbSendQuery().
To access the results in R, fetch() is used.
This saves the results of the query as a data frame object.
n= specifies no. of records to be retrieved. A Value of
-1 in place of n retrieves all pending records.
# Install RMySQL package
THANK YOU!
29

Getting Started with MySQL II

  • 1.
  • 2.
    Database Views 2 A databaseview is a virtual table or logical table which is defined as a SQL SELECT query with joins. Most database management systems, including MySQL, allow you to update data in the underlying tables through the database view with some prerequisites. Advantages of database view: • A database view allows you to simplify complex queries: a database view is defined by an SQL statement that associates with many underlying tables. • A database view helps limit data access to specific users. • A database view provides extra security layer. • A database view enables computed columns.
  • 3.
    Database Views 3 Disadvantages ofdatabase view: • Performance: querying data from a database view can be slow especially if the view is created based on other views. • Tables dependency: you create a view based on underlying tables of the database. Whenever you change the structure of those tables that view associated with, you have to change the view as well.
  • 4.
    Database Views –CREATE VIEW 4 Syntax: CREATE VIEW [database_name].[view_name] AS [SELECT statement] There are some rules that the SELECT statement must follow: • The SELECT statement can contain a subquery in WHERE clause but not in the FROM clause. • The SELECT statement cannot refer to any variables including local variables, user variables, and session variables.
  • 5.
    Database Views –CREATE OR REPLACE VIEW 5 You can use CREATE OR REPLACE VIEW statement to either create or replace an existing view. If a view already exists, MySQL simply modifies the view. In case the view does not exist, MySQL creates a new view. Syntax: CREATE OR REPLACE VIEW [database_name].[view_name] AS [SELECT statement]
  • 6.
    Database Views –CREATE VIEW 6 Execute the example below in World database.
  • 7.
    Database Views –CREATE OR REPLACE VIEW 7 Execute the example below in World database.
  • 8.
    Stored Procedures 8 Introduction toMySQL Stored Procedures A stored procedure is a segment of declarative SQL statements stored inside the database catalog. A stored procedure can be invoked by triggers, other stored procedures, and applications such as Java, Python,R, PHP, ERP etc.
  • 9.
    Stored Procedures 9 MySQL storedprocedures advantages: • Typically stored procedures help increase the performance of the applications. Once created, stored procedures are compiled and stored in the database. • Stored procedures help reduce the traffic between application and database server because instead of sending multiple lengthy SQL statements, the application has to send only name and parameters of the stored procedure. • Stored procedures are reusable and transparent to any applications. • Stored procedures are secure.
  • 10.
    Stored Procedures 10 MySQL storedprocedures disadvantages • If you use a lot of stored procedures, the memory usage of every connection that is using those stored procedures will increase substantially. • Constructs of stored procedures make it more difficult to develop stored procedures that have complicated business logic. • It is difficult to debug stored procedures. Only a few database management systems allow you to debug stored procedures. Unfortunately, MySQL does not provide facilities for debugging stored procedures. • It is not easy to develop and maintain stored procedures.
  • 11.
    Stored Procedures 11 Steps: 1 RightClick on Stored Procedure – Create Procedure
  • 12.
    Stored Procedures 12 Steps: 2 Enteryour commands in the editor and SAVE. Give the procedure a name. Click on Apply.
  • 13.
    Stored Procedures 13 Steps: 3 Yourprocedure can now be called programmatically or in the SQL Editor as below: Call GetCountryDetails(); The statements in the procedure will get executed.
  • 14.
    Triggers 14 A trigger ordatabase trigger is a stored program executed automatically to respond to a specific event e.g., insert, update or delete occurred in a table. A SQL trigger is a special type of stored procedure. It is special because it is not called directly like a stored procedure. The main difference between a trigger and a stored procedure is that a trigger is called automatically when a data modification event is made against a table whereas a stored procedure must be called explicitly.
  • 15.
    Triggers 15 Advantages of usingSQL triggers • SQL triggers provide an alternative way to check the integrity of data. • SQL triggers can catch errors in business logic in the database layer. • SQL triggers provide an alternative way to run scheduled tasks. By using SQL triggers, you don’t have to wait to run the scheduled tasks because the triggers are invoked automatically before or after a change is made to the data in the tables. • SQL triggers are very useful to audit the changes of data in tables.
  • 16.
    Triggers 16 Disadvantages of usingSQL triggers • SQL triggers only can provide an extended validation and they cannot replace all the validations. Some simple validations have to be done in the application layer. For example, you can validate user’s inputs in the client side by using JavaScript or in the server side using server-side scripting languages such as JSP, PHP, ASP.NET, Perl, etc. • SQL triggers are invoked and executed invisible from the client applications, therefore, it is difficult to figure out what happens in the database layer. • SQL triggers may increase the overhead of the database server.
  • 17.
    Triggers 17 Example: We want tocapture the details of people performing any action on a particular table employee, actions such as anyone executing BACKEND UPDATE should get captured. For this we need to first create an Audit table which will store these details as below: CREATE TABLE employees_audit ( id INT AUTO_INCREMENT PRIMARY KEY, emp_id INT NOT NULL, last_name VARCHAR(50) NOT NULL, first_name VARCHAR(50) NOT NULL, jobtitle varchar(100), changedate DATETIME DEFAULT NULL, action VARCHAR(50) DEFAULT NULL);
  • 18.
    Triggers 18 Example: Next step wouldbe writing the trigger. DELIMITER $$ CREATE TRIGGER before_employee_update BEFORE UPDATE ON employee FOR EACH ROW BEGIN INSERT INTO employees_audit SET action = 'update', emp_id = OLD.emp_id, last_name = OLD.last_name, first_name = OLD.first_name, jobtitle = OLD.jobtitle, changedate = NOW(); END$$ DELIMITER ;
  • 19.
    Triggers 19 Example: Now we willfire an update on the employee table update employee set jobtitle = 'programmer' where emp_id = 2; This action will get captured in employees_audit table and can be viewed later.
  • 20.
    MySQL for Excel 20 •MySQL for Excel enables you to work with a MySQL database from within Microsoft Excel. • MySQL data can be imported into Excel, Excel data can be exported into MySQL as a new table or appended to a current table, and MySQL for Excel enables you to edit the MySQL data directly from within Excel.
  • 21.
    MySQL for Excel 21 ImportMySQL Data into Excel Data can be imported from MySQL into a Microsoft Excel spreadsheet by using the Import MySQL Data option after selecting either a table, view, or procedure to import. Append Excel Data into MySQL Data from a Microsoft Excel spreadsheet can be appended to a MySQL database table by using the Append Excel MySQL Data to Table option. Export Excel Data into MySQL Data from a Microsoft Excel spreadsheet can be exported to a new MySQL database table by using the Export Excel Data to New Table option. Exporting data looks like so:
  • 22.
    MySQL for Excel 22 Example: Openthe excel you want to export/Import data from. Click on MySQL for Excel Pre-requisite for doing the same is to install the MySQL Add-on utility
  • 23.
    MySQL for Excel 23 Example: Clickon Local Instance MySQL. Enter the password requested and click OK
  • 24.
    MySQL for Excel 24 Example: Selectthe database in which you want to create a new table or append an existing table with this excel data
  • 25.
    MySQL for Excel 25 Example: Ifyou want to create a new table, then select the excel sheet and click on Export Excel Data to New table and then give the name of the table in the column for Name in the dialogue box. Click on Export Data
  • 26.
    MySQL for Excel 26 Example: Afterclicking Export Data below screen should appear
  • 27.
    MySQL for Excel 27 Example: Loginto backend to check a new table is created and verify rows inserted. Similarly you can explore more options available in the MySQL for Excel utility
  • 28.
    To work withMySQL database in R 28 mydb <- dbConnect(MySQL(), user='user', password='password', dbname='database_name', host='host') # Create a database connection object. install.packages(“RMySQL”) library(RMySQL) # Save a results set object to retrieve data from the database rs = dbSendQuery(mydb, "select * from some_table") # Access the result in R data = fetch(rs, n) Queries can be run using the dbSendQuery(). To access the results in R, fetch() is used. This saves the results of the query as a data frame object. n= specifies no. of records to be retrieved. A Value of -1 in place of n retrieves all pending records. # Install RMySQL package
  • 29.