You are on page 1of 434

Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
3 % e lic
C
MySQL for%Beginners
l bl
c r a
2 0In ansfe
i l l a% on-tr
o bad sStudent
a n Guide
eฺ
B a
ra x) h t Gu i d
n d
l e ja dyฺm den
2 0A oฺua s Stu
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

D61918GC20
Edition 2.0
March 2012
D76212
Author Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Disclaimer
Patricia Garcia
This document contains proprietary information and is protected by copyright and
Technical contr ibutor s other intellectual property laws. You may copy and print this document solely for your
own use in an Oracle training course. The document may not be modified or altered
and Reviewer s in any way. Except where your use constitutes "fair use" under copyright law, you
Kimseong Loh may not use, share, download, upload, copy, print, display, perform, reproduce,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

publish, license, post, transmit, or distribute this document in whole or in part without
Rob Young the express authorization of Oracle.
Philip Olson The information contained in this document is subject to change without notice. If you
Reggie Burnett find any problems in the document, please report them in writing to: Oracle University,
500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not
Todd Farmer warranted to be error-free.
Edwin Desouza
Restricted Rights Notice
Jesper Krogh
If this documentation is delivered to the United States Government or anyone using
Sveta Smirnova
the documentation on behalf of the United States Government, the following notice is
Jeremy Smyth applicable:
Brian Guy to
1n ense
U.S. GOVERNMENT RIGHTS

A
The U.S. Government’s rights to use, modify, reproduce, release, perform, display, or

3% le lic
disclose these training materials are restricted by the terms of the applicable Oracle
Editor s C
license agreement and/or the applicable U.S. Government contract.

l% erab
Trademark Notice
I n c f
Aju Kumar
2 0 n s
a% on-tra
Richard Wallis Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names

i l l
may be trademarks of their respective owners.

Gr aphic Designer o bad s a n eฺ


r a B ha uid
Rajiv Chandrabhanu
d
n yฺm entx ) G
e j a
Publisher s
2 0 Al ฺuad Stud
Giri Venugopal %
e l r r eo this
Ya @co use
Revathi V. Ramamoorthy

d i lla
b o ba
elฺ
(ya
Contents
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Preface

1 Introduction to MySQL
Course Goals 1-2
Course Lesson Map 1-4
Introductions 1-6
Classroom Environment 1-7
MySQL Overview 1-8 to
Acquisitions of the MySQL Company 1-9 A 1n ense
MySQL Is Powering the World! 1-10
C 3% le lic
MySQL Database Server Editions 1-11
n c l% erab
MySQL Tools 1-12
2 0I ansf
MySQL Connectors and APIs 1-13
i l l a% on-tr
MySQL Services 1-15
o bad s a n eฺ
MySQL Community Support 1-16
r a B ha uid
d
n yฺm entx )
Oracle Lifetime Support for MySQL 1-17 G
l e j a
0A oฺuad s Stud
MySQL-Supported Operating Systems 1-18
2
MySQL Websites 1-19
a el% corre e thi
MySQL Curriculum Footprint 1-20
Y @ us
l a
MySQL Certification 1-21
l
b a di
MySQL Online Documentation 1-22

l ฺbo Example Databases 1-23


ya e Summary 1-24
( Practice 1-1 Overview: Access MySQL Information from Company Websites 1-25

2 MySQL Server and Client


Objectives 2-2
MySQL Client/Server Model 2-3
Communication Protocols 2-5
MySQL Connectors 2-7
LAMP Stack 2-8
Installing MySQL 2-9
MySQL Server and Command-Line Client 2-10
Starting the MySQL Command-Line Client 2-11
Startup Command-Line Options 2-12

iii
Keyboard Editing 2-13
tee File 2-15
Quiz 2-16
Summary 2-17
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Practice 2-1 Overview: Install and Start the MySQL Server 2-18
Practice 2-2 Overview: Use the Keyboard Editing and Tee Commands 2-19
Practice 2-3 Overview: Install the world_innodb Database 2-20

3 MySQL Database Basics


Objectives 3-2
RDBMS: Overview 3-3
Spreadsheet Versus Database 3-4
Entities and Relationships 3-5
to
Relationship Categories 3-6
A 1n ense
RDBMS Database Structure 3-7
C 3% le lic
Using SQL with Databases 3-8
n c l% erab
Data Definition Language: SQL Statements 3-9
2 0I ansf
Data Manipulation Language: SQL Statements 3-10
i l l a% on-tr
bad s a n eฺ
MySQL: Benefits 3-11
o
B ha uid
Summary 3-12
d r a x )
Practice 3-1 Overview: Quiz–Database Basics 3-13G
j a n yฺm ent
l e
0A oฺuad s Stud
Practice 3-2 Overview: Identify the Structure of a Table 3-14
2
4 MySQL
a
% rrDesign
elDatabaseo
e
e t hi
Y @4-2
Objectives c us
a
ill Modeling 4-3
d
Database
a
l ฺ b obStructure Diagram (ERD) 4-4
e
(ya
Cardinality Diagram (ERD) 4-5
Cardinality Diagram: Examples 4-6
Keys 4-7
Cardinality ERD: Example 4-8
Normalization 4-9
Advantages of Normalization 4-10
Disadvantages of Normalization 4-11
Eliminating Data Inconsistencies 4-12
Normal Forms 4-14
Normalization Process: Example 4-15
First Normal Form: 1NF 4-16
Second Normal Form: 2NF 4-17
Third Normal Form: 3NF 4-18
Normalized “Furniture Store” Database 4-21

iv
Quiz 4-22
Database Design Considerations 4-23
Database Design Plan 4-24
Database Design Plan Diagram 4-25
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Viewing a Database 4-26


Evaluating a Database Design 4-27
Summary 4-30
Practice 4-1 Overview: Quiz–Database Design 4-31
Practice 4-2 Overview: Evaluate a Database 4-32
Practice 4-3 Overview: Create a Structure Diagram 4-33

5 Table Data Types


Objectives 5-2
to
Data Types as Part of Database Design 5-3
A 1n ense
Data Type Categories 5-4
C 3% le lic
Numeric Data Types 5-5
n c l% erab
Numeric: Integer Data Types 5-6
2 0I ansf
Numeric: Integer Data Types Comparison 5-7
i l l a% on-tr
bad s a n eฺ
Numeric: Floating-Point Data Types 5-8
o
B ha uid
Numeric: Floating-Point Data Types Comparison 5-10
d r a x )
Numeric: Fixed-Point Data Types 5-11 G
j a n yฺm ent
l e
0A oฺuad s Stud
Numeric: Bit Data Types 5-12
2
Temporal Data Types 5-13
el% corre e thi
Temporal Data Types Comparison 5-15
a
Y @ us
Character String Data Types 5-16
l l a
b a di
Character String: Text Class Data Types 5-17

l ฺbo Character String: Text Class Data Types Comparison 5-19

ya e Character String: Integer Class Data Types 5-20


( Character Set and Collation Support 5-21
Binary String Data Types 5-22
Binary String: Data Types Comparison 5-23
Quiz 5-24
Choosing Data Types 5-25
Setting Data Types to NULL 5-26
When to Use NULL 5-27
Summary 5-28
Practice 5-1 Overview: Quiz–Data Types 5-29
Practice 5-2 Overview: Explain the Use of Data Types 5-30

v
6 Database and Table Creation
Objectives 6-2
Creating a Database 6-3
MySQL Naming Conventions 6-4
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Creating a Table 6-5


Showing How a Table Was Created 6-7
Column Options 6-8
Table Options 6-9
Table Indexing 6-10
MySQL Indexing 6-11
Showing the Table Indexes 6-12
Table Constraints 6-13
Quiz 6-14
to
Summary 6-15
A 1n ense
Practice 6-1 Overview: Display Table Creation Information 6-16
C 3% le lic
Practice 6-2 Overview: Create a Database 6-17
n c l% erab
0 I n s f
7 Basic Queries 2
% n-tra
i l l a
Objectives 7-2
b a d a no
SELECT Statement 7-3 B o as i d eฺ
Using SELECT Clauses 7-5
n d ra x) h t Gu
ja dy7-6
Using SELECT witheDISTINCT
l ฺm den
2
SELECT DISTINCT 0A with ฺ a 7-8Stu
uNULL
l % r o
e 7-9 this
SELECT e r
with WHERE
o BY
Ya with
SELECT @ cORDER u se 7-13
d i
SELECT llawith ORDER BY with ASC and DESC 7-15
o a
bSELECT
e l ฺ b with LIMIT 7-17

(ya
SELECT with LIMIT and Skip Count 7-18
SELECT with LIMIT and ORDER BY 7-19
SELECT Usage Tips 7-20
Troubleshooting 7-21
SQL Modes for Syntax Checking 7-23
Common SQL Modes 7-24
Quiz 7-25
MySQL Workbench for SQL Development 7-26
Summary 7-27
Practice 7-1 Overview: Perform Basic Queries 7-28
Practice 7-2 Overview: Perform Basic Queries Using MySQL Workbench 7-29
Practice 7-3 Overview: Perform Basic Queries on the Pets Database 7-30

vi
8 Database and Table Maintenance
Objectives 8-2
DROP DATABASE Statement 8-3
Creating a New Table Using an Existing Table 8-4
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Confirming the Creation of a New Table 8-5


Copying an Existing Table Structure 8-6
Creating a Temporary Table 8-7
DROP TABLE Statement 8-8
Adding a Table Column 8-9
Removing a Table Column 8-11
Modifying a Table Column 8-12
Modifying a Table Column: Row Changes 8-13
Adding Indexes and Constraints 8-14
to
Adding a Column Index 8-15
A 1n ense
Dropping a Column Index 8-17
C 3% le lic
Quiz 8-18
n c l% erab
Summary 8-19
2 0I ansf
Practice 8-1 Overview: Remove a Database 8-20
i l l a% on-tr
bad s a n eฺ
Practice 8-2 Overview: Create a New Table and Remove a Table 8-21
o
B ha uid
Practice 8-3 Overview: Alter Table Columns 8-22
d r a x ) G
Practice 8-4 Overview: Modify Table Indexes and Constraints 8-23
j a n yฺm ent
l e
0A oฺuad s Stud
Practice 8-5 Overview: Further Practice 8-24
2
9 Tablee
a l%Manipulation
Data
o r re
e t hi
Y @9-2
Objectives c us
a
ill of Table Row Data 9-3
d
Manipulation
a
l ฺ b obINSERT Statement 9-4
e
(ya
Using INSERT for Multiple Rows 9-5
NULL condition with INSERT 9-6
REPLACE Statement 9-7
REPLACE Results 9-8
REPLACE Algorithm 9-9
Quiz 9-10
UPDATE Statement 9-11
UPDATE Statement Ordering 9-12
UPDATE with LIMIT 9-13
When UPDATE Has No Effect 9-14
Difference Between UPDATE and REPLACE 9-15
DELETE Statement 9-16
DELETE with ORDER BY and LIMIT 9-17
Summary 9-19

vii
Practice 9-1 Overview: Insert and Replace Table Row Data 9-20
Practice 9-2 Overview: Modify and Delete Table Row Data 9-21
Practice 9-3 Overview: Manipulate Table Row Data in the “Pets” Database 9-22
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

10 Functions
Objectives 10-2
Functions in MySQL Expressions 10-3
Function Tips 10-4
Function Categories 10-5
String Functions 10-6
String Function: Numeric Category Examples 10-7
String Function: String Category Examples (CONCAT, REVERSE,
LEFT, RIGHT) 10-8
to
1n ense
String Function: String Category Examples (LOWER, UPPER, LPAD, RPAD) 10-9
A
String Function: String Category Examples (TRIM) 10-10
C 3% le lic
n c l% erab
String Function: String Category Examples (SUBSTRING) 10-11
0I ansf
String Function: String Category Examples (SUBSTRING_INDEX) 10-12
2
Temporal Functions 10-13
i l l a% on-tr
bad s a n eฺ
Temporal Functions: Date/Time Formats 10-14
o
B ha uid
Temporal Functions: Function Types 10-15
d r a x ) G
Temporal Functions: Extracting Temporal Data Examples 10-16
j a n yฺm ent
l e
0A oฺuad s Stud
Numeric Functions 10-18
2
Numeric Functions: Examples 10-19
el% corre e thi
Numeric Functions: Additional Functions 10-20
a
Y @ us
Control Flow Functions 10-21
l l a
b a di
Control Flow Functions: CASE Functions 10-22

l ฺbo Control Flow Functions: CASE Function Syntax 10-23

ya e Control Flow Functions: CASE Function Examples 10-24


( Quiz 10-25
Aggregate Functions 10-26
Aggregate Function Types 10-27
Aggregate Functions: COUNT Function Examples 10-28
Aggregate Functions: GROUP BY Clause 10-29
Aggregate Functions: GROUP BY Clause and GROUP_CONCAT Function 10-30
Aggregate Functions: GROUP BY and HAVING Clauses 10-31
Aggregate Functions: GROUP BY Clause and WITH ROLLUP Modifier 10-32
Aggregate Functions: Super Aggregate Operation 10-33
Spaces in Function Names 10-34
Summary 10-35
Practice 10-1 Overview: Quiz 10-36
Practice 10-2 Overview: Use Built-In, String, and Temporal Functions 10-37

viii
Practice 10-3 Overview: Use Numeric and Control Flow Functions 10-38
Practice 10-4 Overview: Use Aggregate Functions 10-39

11 Joining Tables
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Objectives 11-2
Combining Multiple Tables 11-3
Joining Tables with SELECT 11-4
Categories of Joins 11-5
Comma-Separated Joins 11-6
INNER JOIN Keywords 11-8
JOIN Keywords 11-9
Outer Joins 11-10
LEFT JOIN Keywords 11-12
to
RIGHT JOIN Keywords 11-13
A 1n ense
Outer Joins: USING and NULL 11-14
C 3% le lic
Table Name Aliases 11-15
n c l% erab
Quiz 11-16
2 0I ansf
Summary 11-17
i l l a% on-tr
bad s a n eฺ
Practice 11-1 Overview: Perform Inner and Outer Joins 11-18
o
B ha uid
Practice 11-2 Overview: Create Queries Requiring Joins 11-19
d r a x ) G
Practice 11-3 Overview: Additional Optional Practice 11-20
j a n yฺm ent
l e
2 0A oฺuad s Stud
12 Table Subqueries
el% 12-2
Objectives
a o r re
e t hi
Y @
Subquery: c u12-3
Overview s
l l a
b a di Subquery: Example 12-4
Basic

l ฺ b o Advantages of Using a Subquery 12-5


e
(ya
Placement of Subqueries 12-6
Subquery Categories 12-7
Non-Correlated Subquery: Example 12-8
Correlated Subquery: Example 12-9
Subquery Result Table Types 12-10
Scalar Subqueries 12-11
Subquery Type/Placement Chart 12-12
Column Designation Subquery 12-13
FROM Subquery 12-14
WHERE Subquery 12-15
WHERE Subquery with Operators 12-16
Subqueries in Comparisons 12-17
WHERE with IN or NOT IN 12-18
WHERE with ALL, ANY, and SOME 12-19

ix
ANY: Example 12-20
ANY: Example Subquery 12-21
WHERE with EXISTS and NOT EXISTS 12-22
Finding Table Mismatches 12-23
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Modifying Tables by Using Subqueries 12-24


Quiz 12-25
Subquery Tips 12-26
Converting Joins to Subqueries 12-27
Converting Subqueries to Joins 12-28
Summary 12-30
Practice 12-1 Overview: Perform Different Types of Queries 12-31
Practice 12-2 Overview: Perform Several Advanced Subqueries 12-32

to
13 Exporting and Importing Data
A 1n ense
Objectives 13-2
C 3% le lic
Exporting Data 13-3
n c l% erab
Exporting with a Query 13-4
2 0I ansf
Exporting with a Query: INTO OUTFILE 13-5
i l l a% on-tr
bad s a n eฺ
Exporting with a Query: CSV Format 13-6
o
B ha uid
Exporting with a MySQL Utility 13-7
d r a
Specifying Databases to Dump 13-8 x ) G
j a n yฺm ent
l e
0A oฺuad s Stud
mysqldump Utility Options 13-9
2
Dumping to a Text File 13-10
el% corre e thi
Text File Contents 13-11
a
Y @
Importing Data 13-12us
l l a
b a di
Importing from a Data File 13-13

l ฺbo Importing with the LOAD DATA INFILE Statement 13-14

ya e Importing with LOAD DATA INFILE: CSV Format 13-15


( Importing with LOAD DATA INFILE: File Control 13-16
Importing with a MySQL Utility 13-17
mysqlimport Utility Options 13-18
mysqlimport Option: Examples 13-19
Summary 13-20
Practice 13-1 Overview: Quiz 13-21
Practice 13-2 Overview: Export Files Using a Query 13-22
Practice 13-3 Overview: Import Files from a Data File 13-23
Practice 13-4 Overview: Back Up Database Files with a Utility 13-24

14 MySQL Graphical User Interface Tools


Objectives 14-2
MySQL GUIs 14-3

x
MySQL Workbench 14-4
MySQL Workbench: Functional Modules 14-5
MySQL Workbench: Primary GUI Window 14-6
MySQL Workbench: SQL Development Window 14-7
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

MySQL Workbench: Data Modeling Module 14-8


MySQL Workbench: Data Modeling Features 14-9
MySQL Workbench: Data Modeling Window 14-10
MySQL Workbench: Data Modeling Panels 14-11
MySQL Workbench: Data Modeling EER Diagram 14-12
MySQL Workbench: Server Administration Window 14-13
MySQL Workbench: Server Administration Module Features 14-14
MySQL Enterprise Monitor 14-15
Enterprise Monitor Features 14-16
to
Enterprise Monitor: Dashboard 14-18
A 1n ense
Enterprise Monitor: Advisors 14-19
C 3% le lic
Summary 14-22
n c l% erab
0I ansf
Practice 14-1 Overview: Create a Data Model Using MySQL Workbench 14-23
2
i l l a% on-tr
Practice 14-2 Overview: Create a Server Instance Using MySQL Workbench 14-24

bad s a n eฺ
Practice 14-3 Overview: View the MySQL Enterprise Monitor Demonstrations 14-25
o
B ha uid
Practice 14-4 Overview: (Optional) Create a Model for the Pets Database Using
MySQL Workbench 14-26 d r a x ) G
j a n yฺm ent
e
Al ฺuad Stud
15 Supplemental0Information
l 2
% 15-2 rreo this
e
Objectives
coanduMySQL
Ya Engines
Storage @ se 15-3
d i
StoragellaEngines Available on the Server 15-4
o a Storage Engine Setting: Using SHOW CREATE TABLE 15-5
bDisplay
b
elฺ Display Storage Engine Setting: Using SHOW TABLE STATUS LIKE 15-6
(ya Set the Storage Engine to InnoDB 15-7
InnoDB Storage Engine 15-8
InnoDB as the Default Storage Engine 15-9
Other Storage Engines 15-10
Quiz 15-11
Creating Views 15-12
CREATE VIEW Examples 15-13
Displaying View Information 15-14
Views: Showing the Table Types 15-15
View Definition Restrictions 15-16
Quiz 15-17
Transactions 15-18
Transactions: ACID 15-19

xi
Transaction Diagram 15-20
Transaction SQL Control Statements 15-21
Starting a Transaction 15-22
Quiz 15-23
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Retrieving Metadata 15-24


Metadata: SHOW Statements 15-25
Metadata: INFORMATION_SCHEMA Database 15-26
Metadata: INFORMATION_SCHEMA Tables 15-27
Metadata: Viewing INFORMATION_SCHEMA 15-29
Metadata: SCHEMATA 15-30
Quiz 15-31
MySQL Performance Schema 15-32
Performance Schema: Implementation 15-33
to
Performance Schema: SHOW Database Tables 15-34
A 1n ense
Quiz 15-36
C 3% le lic
MySQL Enterprise Backup 15-37
n c l% erab
MySQL Enterprise Backup: Preparation 15-38
2 0I ansf
i l l a% on-tr
MySQL Enterprise Backup: Implementation 15-39

bad s a n eฺ
MySQL Enterprise Backup: Running mysqlbackup 15-40
o
B ha uid
MySQL Enterprise Backup: A Few mysqlbackup Options 15-41
d r a x ) G
MySQL Enterprise Backup: Recovering or Restoring a Database 15-42
j a n yฺm ent
l e
0A oฺuad s Stud
Quiz 15-43
2
Summary 15-44
el% corre e thi
Practice 15-1 Overview: Display Storage Engine Information 15-45
a
Y @ us
Practice 15-2 Overview: Display and Create Views 15-46
l l a
b a di
Practice 15-3 Overview: Obtain Metadata 15-47

l ฺbo Practice 15-4 Overview: (Optional) Create a Backup of MySQL Databases 15-48

ya e
( 16 Conclusion
Course Goals 16-2
MySQL Curriculum Path 16-4
MySQL Resources 16-5
We Need Your Evaluation! 16-6
Thank You 16-7
Q&A Session 16-8

xii
Preface
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(
Profile
Before You Begin This Course
Before you begin this course, you should have the following:
• A desire to attain MySQL Associate certification
Prerequisites
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

You should have one of the following prerequisites:


• Basic computer literacy is required.
• It is suggested that you have previous experience with any command-line program,
and knowledge of database concepts.
How This Course Is Organized
MySQL for Beginners is an instructor-led course featuring lecture, demonstrations, quizzes,
and hands-on practice exercises. The practice sessions reinforce the concepts and skills
to
introduced. 1n n se
3 %A e lice
l % C bl
I n c f e ra
20 tran s
%
lla non-
d i
B oba as a ideฺ
n d ra x) h t Gu
l e ja dyฺm den
2 0A oฺua s Stu
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

Preface - 3
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

Preface - 4
Typographic Conventions
Typographic Conventions in Text
The following typographical conventions are used throughout this training guide:
• Computer input and output is printed in this format: Computer input or output.
This is also used for the names of executable programs and file locations.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Keywords from the SQL language appear in this format: SQL KEYWORD. SQL keywords
are not case-sensitive and may be written in any letter case, but the training guide uses
uppercase.
When commands are shown that are meant to be executed from within a particular program, the
prompt shown preceding the command indicates which command to use. For example, sys>
indicates a command that you execute from your shell, and mysql> indicates a statement that you
execute from the mysql client program:
o
shell> mysql -u root -h 127.0.0.1
1 n nse t
mysql> SELECT * FROM world.City;
3 %A e lice
The “sys” is your command interpreter. On Linux, this is typically al% C such
program bl as sh, csh, or
c r a
fe typically run in a
bash. On Windows, the equivalent program is command.com
2 0Inor cmd.exe,
n s
console window. When you enter a command or statement
i l l a % shown
n - tinraan example, do not type the
prompt shown in the example.
b a d a no
Database, table, and column names must often B o be substituted
a s i d eฺstatements. To indicate that such
into
substitution is necessary, this manual
n d ruses x ) h ttbl_name,
a db_name, G u and col_name. For example,
you might see a statement like j a ฺ
le this: ady tude m n
2 0 A ฺu is FROM S db_name.tbl_name;
mysql> %
l SELECT
r e o
col_name
h
This means Y that or to enter
aeif you were
c s e t
a similar statement, you would supply your own database,
a @ u
table, and column
a d ill names for the placeholders db_name, tbl_name, and col_name., perhaps
like this:ob
e l ฺb mysql> SELECT author_name FROM biblio_db.author_list;
(ya In syntax descriptions, square brackets ([ and ]) indicate optional words or clauses. For example,
in the following statement, IF EXISTS is optional:
DROP TABLE [IF EXISTS] tbl_name;
When a syntax element consists of a number of alternatives, the alternatives are separated by
vertical bars (pipe, |).
When one member from a set of choices may be chosen, the alternatives are listed within square
brackets ([ and ]):
TRIM([[BOTH | LEADING | TRAILING] [remstr] FROM] str)
When one member from a set of choices must be chosen, the alternatives are listed within braces
({ and }):
{DESCRIBE | DESC} tbl_name [col_name | wild]
Preface - 5
An ellipsis (...) indicates the omission of a section of a statement, typically to provide a shorter
version of more complex syntax. For example, INSERT ... SELECT is shorthand for the form
of INSERT statement that is followed by a SELECT statement.
An ellipsis can also indicate that the preceding syntax element of a statement may be repeated. In
the following example, multiple reset_option values may be given, with each of those after
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

the first preceded by commas:


RESET reset_option[, reset_option] ...

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

Preface - 6
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Introduction to MySQL

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(
Course Goals

After completing this course, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Describe the features and benefits of MySQL


• Explain the basics of relational databases
• Describe MySQL connectors, and their major features and
differences
• Explain the SQL and MySQL languages
• Describe data/column types with regard to efficient database
design to
A 1n ense
• View a database design structure and content 3%
e l ic
l C
% structurebl
• Create a database design by using an efficient c e r a
• Extract basic database information by 2 In the
0using n s fSELECT
l l a % n-tra
command
a i
d a no
b eฺ
Botypical
• Troubleshoot and identify assyntaxidwarnings
ra x) h t Gu
and errors
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 1 - 2


Course Goals

(continued)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Delete or modify a database and table row data


• Group query data with aggregation
• Connect data from multiple table rows by using JOIN
• Perform nested subqueries
• Use simple functions (String, Date, Numerical)
• Explain MySQL storage engines and transactions, and the
to
features of the common engines
A 1n ense
• Export and import database data
C 3% le lic
• Obtain database metadata n c l% erab
0 I n s f
2
• Monitor server database performance
i l l a% on-tra
o ad interface
• Describe MySQL graphicalbuser a n tools ฺ
• Perform database backupB a s i d e
ra and ) h recovery
nd yฺmx ent G
u
j a
le © 2012,
2 0 A
Copyright
ฺ u tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 1 - 3


Course Lesson Map

Day 1
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

1. Introduction to MySQL
2. MySQL Server and Client
3. Database Basics
4. Database Design
5. Table Data Types
to
Day 2 A 1n ense
3 % e lic
6. Database and Table Creation l C
% rabl
c
7. Basic Queries 2 0In ansfe
8. Database and Table Maintenance i l l a% on-tr
o b ad a n ฺ
9. Table Data Manipulation
r a B has uide
a n d mx) nt G
A lej © 2012,
a d yฺ uditseaffiliates. All rights reserved.
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


Y @ us
l l a
b a di
l ฺ b o
e
(ya

MySQL for Beginners 1 - 4


Course Lesson Map

Day 3
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

9. Table Data Manipulation (continued)


10. Functions
11. Joining Tables
12. Table Subqueries

Day 4 to
13. Exporting/Importing Data A 1n ense
3 % e lic
14. MySQL Graphical User Interface Tools l% C bl
c r a
15. Supplementary Information 2 0In ansfe
16. Conclusion i l l a% on-tr
d n
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
l l a
ob adi
l ฺ b
(y ae

MySQL for Beginners 1 - 5


Introductions

• Name
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Company affiliation
• Title, function, and job responsibilities
• Experience related to topics covered in this course
• Reason for enrolling in this course
• Expectations for this course
to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 1 - 6


Classroom Environment

• Logistics
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Restrooms
– Break rooms and designated smoking areas
– Cafeterias and restaurants in the area
• Emergency evacuation procedures
• Instructor contact information
• Mobile phone usage
to
• Online course attendance confirmation form A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 1 - 7


MySQL Overview

• Relational database management system program suite


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• World's most popular open source database


– Fastest growing with
over 70,000 downloads
per day
• Under active development
since 1995
to
A 1n ense
C 3% le lic
n c l% erab
MySQL is installed on 0I every n s f
2
continent i l l -tra
ain%theonworld.
(Yes, d aAntarctica!)
baeven n ฺ
o
B has uide
r a
d mx) nt G
a n yฺ uditseaffiliates. All rights reserved.
A lej © 2012,
a d
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 1 - 8


Acquisitions of the MySQL Company

• Sun Microsystems acquired MySQL in 2008.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Oracle acquired Sun Microsystems in 2010.


• These acquisitions give MySQL:
– The industry's largest dedicated MySQL engineering and
support staff
– Oracle Lifetime Support services
• All this is combined with strong open-source community
support. to
n
A 1 ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 1 - 9


MySQL Is Powering the World!
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

n e to
Web & Enterprise OEM & ISVs
A1 ens
C 3% le lic
n c l% erab
2 0I ansf
l l a % n-tr
Cloud
a i
d a no
b
o and s eฺcommunity!
An impressive customer B
ra x) h t Gu a partner i d
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y customer
• Strong us base centered in five core areas, including:
@ and partner
- ad
l l a
i 2.0, SaaS, enterprise, telecommunications, and OEM/embedded markets
Web
b
l•ฺboMore than 400 blue-chip customers and a wide range of market leaders
e•
(ya Used by nearly every Web 2.0 and e-commerce company
• Strong in the telecommunications market
• Strong in the enterprise market

MySQL for Beginners 1 - 10


MySQL Database Server Editions

• MySQL Community Edition


– Open source, noncommercial
GPL
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• MySQL Cluster Community Edition


– Open source, noncommercial, cluster

• MySQL Classic Edition


– Embedded database for OEMs, ISVs, VARs
• MySQL Standard Edition
– High-performance, scalable OLTP
applications, MySQL Workbench SE
to
Commercial
• MySQL Enterprise Edition
– Enterprise features: monitor, backup, A 1n ense
Scalability, security, High availability C 3% le lic
– Oracle Product Integrations
n c l% erab
0I Grade n s f
• MySQL Cluster Carrier 2 Edition
tra database
l l a%fault-tolerant
– High availability,
i n -
– MySQL
b a no ฺ
dClusteraManager
–B o Cluster
MySQL
a ide
s Geo-Replication
r a ) h u
j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
Ya Edition
MySQL Classic @ cois well
u e for embedded and read-intensive, non-OLTP
ssuited
applications.d i lla
o a
bStandard
MySQLb and Enterprise Editions are complementary for read-intensive and OLTP
l ฺ
( yaeapplications that require high performance, high availability, and consistent crash recovery.
In addition to the Community edition, OEMs can license or subscribe to all editions, and end
users can subscribe to Standard, Enterprise, and Cluster Carrier Grade editions.
The commercial editions build on each other:
• Standard Edition includes Classic Edition, plus the additional features listed in the slide.
• Enterprise Edition includes Standard Edition, plus additional features listed in the slide.
• Carrier Grade Edition includes Enterprise Edition, plus the additional features listed in
the slide.
You can find more information about product features, as well as licensing and subscription
options, at:
• http://mysql.com/products/
• http://www.mysql.com/about/contact/
• https://shop.oracle.com/
- Select Database from the Product Categories menu, and then select MySQL.

MySQL for Beginners 1 - 11


MySQL Tools

• Graphical and command-line interfaces to your MySQL


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

databases
• MySQL Enterprise Monitor
– Web application that reduces down time, tightens security,
and increases throughput
– Includes MySQL Query Analyzer
• MySQL Enterprise Backup
to
– Online “Hot,” nonblocking backups A 1n ense
3 % e lic
• MySQL Workbench l C
% rabl
c
– Visual database design tool that is used
2 n sfe design,
0In toaefficiently
manage, and document databases
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @iscoavailable
MySQL Workbench u sein both General Public License (GPL) and commercial
d
editions. The i la tools are available only in commercial editions.
lother
More b o ba about these tools are presented later in this course.
details
a e lฺ
( y

MySQL for Beginners 1 - 12


MySQL Connectors and APIs

Connectors APIs
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

ODBC C

JDBC PHP

Net Perl
MXJ Python to
A 1n ense
C Ruby 3% e lic
l % C bl
I n cTcl fera
C++ 2 0 ans
i l l a% on-tr
OpenOffice
o bad s a nEiffel e ฺ Wrapper
r B
a x) ha Guid
a d
n yฺm ent
e j
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @provide
MySQL connectors co uconnectivity
se to the MySQL server for client programs. APIs
l l a
b a di access to the MySQL protocol and MySQL resources. Both the connectors
provide low-level
and the
l ฺ b o APIs enable you to connect and execute MySQL statements from another language

yae
or environment.
( The following are particularly important connectors:
• Connector/J (JDBC): A JDBC Type 4 driver that provides connectivity for client
applications developed in the Java programming language. The Type 4 designation
means that the driver is pure-Java implementation of the MySQL protocol and does not
rely on the MySQL client libraries.
• Connector/NET (Net): Enables developers to easily create .NET applications that
require secure, high-performance data connectivity with MySQL. Connector/Net is a fully
managed ADO.NET driver written in 100% pure C#.
• Connector/PHP: PHP is a server-side, HTML-embedded scripting language that can be
used to create dynamic web pages. PHP provides two different MySQL API extensions:
mysql and mysqli. MySQL Connector/PHP is a version of the mysql and mysqli
extensions for PHP optimized for the Windows operating system.
MySQL Connector/MXJ is available, but is not fully developed or supported at this time.

MySQL for Beginners 1 - 13


Third-party connectors that MySQL supports:
• PHP: mysqli, ext/mysqli, PDO_MYSQLND, PHP_MYSQLND
• Perl: DBD::mysql
• Python: MySQLdb
• Ruby: DBD::MySQL, ruby-mysql
• C++ Wrapper: For MySQL C API (MySQL++)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

The embedded MySQL server library (libmysqld) is also supported. libmysqld makes it
possible to run a full-featured MySQL server inside a client application. The main benefits are
increased speed and simpler management for embedded applications.
You can download connectors and their documentation from the following page:
http://mysql.com/products/connector/.
For more information about connectors, see the MySQL Reference Manual at
http://dev.mysql.com/doc/refman/5.5/en/connectors-apis.html.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 1 - 14


MySQL Services

MySQL training
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Comprehensive set of MySQL training courses

MySQL certification

• High-quality certification for MySQL developers and database


administrators

MySQL consulting to
A 1n ense
• Full range of consulting services from startup to optimization
C 3% le lic
n c l% erab
Oracle Lifetime Support 2 0I ansf
i l l a% on-tr
• Offerings to save you time anda d athatn you achieve the
ensure
breliability,
highest levels of performance,
B o a s eฺ
and uptime
i d
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 1 - 15


MySQL Community Support

• Mailing lists
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Forums
• Community articles
• PlanetMySQL blogs
• MySQL Forge
• Twitter
to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
• Yalists@
Mailing co use
(http://lists.mysql.com/)
• d
Forums i la
l(http://forums.mysql.com)

l ฺboba
Community articles (http://dev.mysql.com/tech-resources/articles)
ya e • PlanetMySQL blogs (http://planet.mysql.com/)
(
• MySQL Forge (http://forge.mysql.com)
• Twitter (http://twitter.com/mysql_community)

MySQL for Beginners 1 - 16


Oracle Lifetime Support for MySQL

• 24 × 7 support
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Unlimited support incidents


• Knowledge Base
• Maintenance releases, bug fixes, patches, and updates
• MySQL Consultative Support

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya My
You can access @ co uSupport
Oracle se at https://support.oracle.com.
d i lla
b o ba
a e lฺ
( y

MySQL for Beginners 1 - 17


MySQL-Supported Operating Systems

• MySQL provides control and flexibility for users.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• It supports more than 20 platforms, including:


– Windows (multiple)
– Linux (multiple)
– Solaris
– Mac OS

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
a
Ysupported
A full list of @ cooperating
u sesystems is available at
d i lla
http://www.mysql.com/support/supportedplatforms/database.html.
b o ba
a e lฺ
( y

MySQL for Beginners 1 - 18


MySQL Websites

• http://dev.mysql.com includes:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Developer Zone (articles, forums, Forge, PlanetMySQL, and


more)
– Downloads (GA and development release)
– Documentation
• http://www.mysql.com includes:
– Downloads (GA)
– Services to
– Consulting A 1n ense
C 3% le lic
– Resources
n c l% erab
– White papers 2 0I ansf
– Webinars i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 1 - 19


MySQL Curriculum Footprint
Database developers Database administrators
MySQL and PHP MySQL for Beginners Introductory
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

ILT/LVC ILT/LVC

Intermediate
MySQL Performance
Tuning Bootcamp

MySQL for Database


MySQL MySQL for Developers
Administrators
Bootcamp ILT/LVC
o
n nse t
ILT/LVC
1
3 %AAdvanced
l i ce
l % C ble
I n c f e ra
20 trMySQL s
an Cluster MySQL High
MySQL Advanced MySQL Developer
l a
l non%
MySQL Performance
-
Stored Procedures Techniques
d i
Tuning Availability

oba ILT/LVC
ILT
ILT/LVC ILT/LVC
B s a e ฺ ILT

d r a x) ha Guid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
Ya @co use
Course types:
d i lla Training (ILT): Delivered in a classroom with an instructor and students
• Instructor-Led
b o ba at the same location and time
present
a e l•ฺ Live Virtual Class (LVC): Delivered using video and audio through a web-based
( y delivery system (WebEx) in which geographically distributed instructor and students
participate, interact, and collaborate in a virtual class environment
For full details about the MySQL curriculum, go to http://www.oracle.com/education.

MySQL for Beginners 1 - 20


MySQL Certification

The Oracle Certification Program validates various levels of


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

MySQL expertise:
• Introductory: Certified Associate
– Oracle Certified Associate: MySQL
• Intermediate: Certified Professional
– Oracle Certified Professional: MySQL Database
Administrator
– Oracle Certified Professional: MySQL Developer to
A 1n ense
• Advanced: Certified Expert 3% le lic
– Oracle Certified Expert: MySQL Cluster c
C
l% erab
Database
Administrator
n
0I ansf
2
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
For complete @ co about
Ya information u sethese and other offerings of the Oracle Certification Program,
d i lla
go to http://education.oracle.com/certification.
b o ba
a e lฺ
( y

MySQL for Beginners 1 - 21


MySQL Online Documentation

• MySQL Reference Manual


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Topic guides
• Expert guides
• MySQL help tables
• Example databases
• Meta documentation
• Community-contributed documentation to
• Printed books A 1n ense
• Additional resources C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
The MySQL @ co uissavailable
Yadocumentation e at http://dev.mysql.com/doc.
l l a
b a di
l ฺ b o
( yae

MySQL for Beginners 1 - 22


Example Databases

• MySQL provides several example/test databases:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– world_innodb
– world
– employee
– menagerie
– sakila
• Available for download from our website
• The world_innodb database is used for demonstration to
A 1n ense
and exercises in this course. 3% lic C ble
c l % ra
I n s f e
% 20 tran
d i lla non-
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
For more Y information s
@ about uexample database installation, see the MySQL Reference Manual
l l a
b a di
at http://dev.mysql.com/doc/index-other.html.

l ฺ b o
( yae

MySQL for Beginners 1 - 23


Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Describe the course goals


• Explain the origin and status of the MySQL product
• List the available MySQL products and professional
services
• List the currently supported operating systems
• Describe how to access MySQL information and services
to
on Oracle and MySQL websites
A 1n ense
• List all the available MySQL courses C 3% le lic
• Describe the Oracle Certification Program n c l%
for e r
MySQL
f ab
2 0I ans
• Obtain MySQL online documentation
i l l a% oand
n -tr example
d an
databases oba B has uideฺ
r a
d mx) nt G
a n yฺ uditseaffiliates. All rights reserved.
A lej © 2012,
a d
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 1 - 24


Practice 1-1 Overview:
Access MySQL Information
from Company Websites
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

This practice covers reviewing the MySQL and Oracle websites


that contain information about MySQL products and services.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 1 - 25


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

MySQL Server and Client

to
A 1n ense
Connecting to the Database
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(
Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Explain the MySQL client/server model


• Describe the communication protocols used to interact with
the MySQL server
• Explain how MySQL works with connectors
• Identify the components of a LAMP stack, and their roles
• Install the MySQL server
n nse to
• Start the MySQL server and the mysql client A1 % ice
• Install the world_innodb example databaseC3 ble l
n c l% era
• Use command-line editing methods 0I n s f
2 tra
• Use a text file to log your mysql i l l a%client n -
session
b a d a no
B o as i d eฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
l l a
b a di
l ฺ b o
e
(ya

MySQL for Beginners 2 - 2


MySQL Client/Server Model

MySQL client/server architecture


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Database
PHP

mysqld TCP/IP
MySQL Server Process
Linux
TCP/IP Socket
n nse to
(localhost) TCP/IP
A 1
mysql PHP 3 ice
% e lODBC
l % C bl
Client
Process
Client
Process
I n c f e ra
20 tran s
%
lla non-
a d i Windows

B ob as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
The MySQL Y database@ system ususes a client/server architecture. The server is the central
l l a
program that
b a dimanages database contents, and the client programs connect to the server to
retrieve
l ฺ b o or modify data. To access the data in a database, a MySQL server must be running.

yae
The MySQL server, named mysqld, listens on a particular port for incoming connection
( requests; the default port for MySQL is 3306. You can change this port number to a different
available port, if desired. You can also return it to the default port (3306), if it has been
changed.
The client (in MySQL) is any application that sends a request to the database via the server.
A client is used to communicate with the MySQL server any time a command statement is
sent, whether that is a PHP script or one of the standard MySQL clients. The client connects,
does what it needs to do, and then disconnects. The server can handle multiple client
connections at once.

MySQL for Beginners 2 - 3


Connection Methods
• On Windows, local connections can use a shared pipe or shared memory. However, most
local connections use TCP/IP.
• UNIX/Linux local connections can use a UNIX socket file.
• Remote connections must be made via TCP/IP. However, TCP/IP can also be used for a
local connection.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

The "d" in "mysqld" is for daemon; a program or process that sits idly in the background until it
is invoked to perform its task.
Note: Any information in this course that does not apply to all operating systems is identified as
platform specific. Information that works for Linux generally applies for all UNIX-like operating
systems.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 2 - 4


Communication Protocols

Protocol Types of Connections Supported Operating


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Systems
TCP/IP Local, remote All

UNIX socket file Local only UNIX only

Shared memory Local only Windows only

Named pipes Local only Windows only

o
1 n nse t
• Protocols are implemented in the client libraries% A ice
and
C 3 l e l
drivers. l% erab
n c
• The speed of a connection protocol2varies 0I awith n sf the local
settings. i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
• TCP/IP @ co uControl
Ya(Transmission se Protocol/Internet Protocol): TCP/IP is the suite of
d i lla protocols used to connect hosts on the Internet. For the Linux operating
communication
b o ba TCP/IP is built-in and is used by the Internet, making it the de facto standard for
system,
elฺ transmitting data over networks. This is the best MySQL connection type for Windows.
(ya • UNIX socket file: This is a form of interprocess communication used to form one end of
a bidirectional communication link between processes on the same machine. A socket
requires a physical file on the local system. This is the best MySQL connection type for
Linux.
• Shared memory: This is an efficient means of passing data between programs. One
program creates a memory portion that other processes (if permitted) can access. This
Windows explicit “passive” mode works only within a single (Windows) machine. Shared
memory is disabled by default. To enable shared-memory connections, you must start
the server with the --shared-memory option.

MySQL for Beginners 2 - 5


• Named pipes: The design of named pipes is biased toward client/server communication,
and they work much like sockets. Other than read and write operations, Windows named
pipes also support an explicit “passive” mode for server applications. This protocol works
only within a single (Windows) machine. Named pipes are disabled by default. To enable
named-pipe connections, the server must be started with the --enable-named-pipe
option.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 2 - 6


MySQL Connectors

• Application programming interfaces (APIs)


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Most are compatible with industry standards ODBC and


JDBC
• Available for multiple operating systems
• Officially MySQL-supported connectors:
– Connector/ODBC
– Connector/J
– Connector/NET to
A 1n ense
– Connector/MXJ
C 3% le lic
– Connector/C/C++
n c l% erab
– OpenOffice 2 0I ansf
l l a % n-tr
• Embedded MySQL server library:
a i
d alibmysqld no ฺ
b
oand aAPIs
• Multiple PHP extensions
r a B
) h s supported
u ide
j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
MySQL works co application
Ya with@several u se programming interfaces also known as “database
d i
drivers”. These llaAPIs and drivers act as bridges to the MySQL server for client programs that
o ba using a particular protocol. The drivers comprise the family of MySQL
communicate
b
a e lฺ
connectors. They are available as separate packages.
( y The mysqlnd connector is not compatible with JDBC and ODBC.
The MySQL connectors are available for Windows, Linux/UNIX, and Mac OS X. To use a
connector, you must install it on the client host. It is not necessary for the server to be running
on the same machine or for the server to be running the same operating system as the client.
Therefore, MySQL connectors are very useful for providing MySQL connectivity in
heterogeneous environments. For example, people who use Windows machines can run
client applications that access MySQL databases located on a Linux server host.
Most of them are based on the C client library and provide a binding for some other language.
The MySQL C client library is the standard client/server protocol implementation from MySQL
(which is considered to be the reference implementation).
The embedded MySQL server library makes it possible to run a full-featured MySQL server
inside a client application. The main benefits are increased speed and more simple
management for embedded applications.

MySQL for Beginners 2 - 7


LAMP Stack

• MySQL is the database component in the LAMP stack,


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

which has become the preferred stack for web


applications:
– Linux: Operating system
– Apache: Web server
– MySQL: Relational Database Management System
– PHP/Perl/Python: Programming languages
• The LAMP stack offers many degrees of freedom. n to
A 1 ense
• You can go from LAMP to WAMP (Windows). 3% lic
l % C ble
I n c f e ra
20 tran s
%
lla non-
d i
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Though the Y originators
@ of these us open source programs did not design them all to work
specificallyd l l a
i each other, the combination has become popular because of its low
with
o b
acquisition a cost and the ubiquity of its components. When used in combination, they represent
l ฺ b
yae
a solution stack of technologies that support application servers.
( This technology allows the user of a web browser to execute a program on the web server,
and to thereby receive dynamic as well as static content.
The LAMP stack offers many degrees of freedom, enabling you to:
• Go from LAMP to WAMP (Windows operating system)
• Put the MySQL server process on a separate computer
• Replicate the MySQL server process on several computers
• Run several MySQL server processes on one server

MySQL for Beginners 2 - 8


Installing MySQL

• You can download MySQL products from:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Community: http://dev.mysql.com/downloads
– Enterprise: https://edelivery.oracle.com/
• The Windows operating system is used for this course.
• The MySQL installer for Windows is recommended:
– http://dev.mysql.com/downloads/installer/
– Installs several MySQL products to
A 1n ense
• Example databases for testing MySQL features: 3% le lic
– The world_innodb database is used forcexamples
C
l% eraand b
practices in this course. n
0I ans f
2
– This and other sample databases i l l a%areonavailable-tr (free) online.
a d n
B ob as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @all licensable
You can download us Oracle products from the Oracle Software Delivery Cloud
l l a
b a di
website at https://edelivery.oracle.com/.

l ฺ o installer for Windows installs the following MySQL products:


ThebMySQL

( yae • MySQL Server


• All of our supported connectors
• Workbench and sample models
• Sample databases
• Documentation
For more information about MySQL installation, see the MySQL Reference Manual:
http://dev.mysql.com/doc/refman/5.5/en/installing.html.

MySQL for Beginners 2 - 9


MySQL Server and Command-Line Client

• The server starts automatically after standard installation


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

on the Windows platform.


• Connection to the server is made using the mysql
command-line client.
• The command-line client is primarily used to:
– Send queries
– Receive query results
to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Use the mysql @ co usclient
Ya command-line e for many purposes:
• Create d i lla
databases.
b o ba syntax.
Check
elฺ

(ya • Ease program development.
• Create tables.
• Show database structure.
• Optimize queries.
• Alter table descriptions.
• Test SELECTs.
• Perform backup and restore.
• Create indexes.
• Do bulk updates.
• Grant access rights.

MySQL for Beginners 2 - 10


Starting the MySQL Command-Line Client

Start the mysql client with the following command:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

shell> mysql -u root -p


Enter password: <password>
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.5.16 MySQL Community Server (GPL)
...
Type 'help;' or '\h' for help. Type '\c' to clear the e
n to
current input statement. A1 ens
C 3% le lic
mysql>
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya the@
After invoking co client,
mysql u setake note of the following:
d illa id and the server version
• Theaconnection
•ฺbo
b
The help command
l
( yaeAt this point, the only available account is the root account (and possibly an anonymous
account).

MySQL for Beginners 2 - 11


Startup Command-Line Options

• Get a full list of options by using –-help:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

shell> mysql --help

• Some primary options:


– -h: Host name or IP address
– -u: Username
– -p: Password
– <database>: Database name
to
– <: Input script
A 1n ense
– >: Output file name
C 3% le lic
– -b: Beeps
n c l% erab
• Syntax example: 2 0I ansf
i l l a% on-tr
shell> mysql -h 192.145.66.10
o b ad a–un wld ฺ -pmypass
world_innodb B
r a ) h as uide
< sqlcommands.sql

j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
Descriptions co options:
Yaof the@primary u se
• -h a d illa
<hostname> or <IP>: Can be used to specify the host machine where the MySQL
b b
oserver resides. This can usually be omitted if the client and the server are on the same
l ฺ
( yae host.
• -u<username>: Specifies a username other than the default (usually the OS
username). No space is necessary after the option, but it is allowed.
• -p<password>: Specifies user password (enter -p only when prompted for it, then the
password you enter is not displayed on the screen). No space is allowed after the
option.
• <database>: (Optional) Sets the name of the default database for the current session
• < <input_script>: Connects to the MySQL server and execute the SQL statements
in this file
• > <filename>: Saves the output sent by the MySQL server to this file
• -b: Disables the beeps the client makes for errors
The example in the slide shows how to execute the mysql client, connect to the host IP
192.145.66.10 as the user wld, and execute the SQL statements found in the
sqlcommands.sql file in the world_innodb database.

MySQL for Beginners 2 - 12


Keyboard Editing

mysql client command-line editing methods:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Keyboard directional arrows


• Command history preserved during session
• Interrupt a query
• Full readline capabilities under Linux
• Close quotes
• Copy and paste into window o
1 n nse t
3 %A e lice
l % C bl
I n c f e ra
20 tran s
%
lla non-
d i
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y methods:
Some editing @ us
l l a
• Theafour
b di keyboard arrows:
l ฺ b o - Right and left arrows (←, →) move the cursor one step forward and backward.
( yae - Up and down arrows (↑, ↓) let you cycle your command history in the mysql client.
• Command history is preserved between sessions.
- History clears in Windows if the command prompt window is closed
- Persistent in Linux
• Cancel a query partway through entry with \c.
• The mysql client has full readline capabilities under Linux
- Ctrl-A: Moves to the beginning of the line (Anfang)
- Ctrl-E: Moves to the end of the line (Ende)
- Ctrl-K: Kills from the cursor onward
- Ctrl-R: Searches in reverse through your history
Note: MySQL commercial versions use libedit, not readline. However, libedit is fully readline
compatible. Libedit is a replacement or alternative to the GNU readline command-line editing
functionality.

MySQL for Beginners 2 - 13


• Close the quotes (otherwise, the prompt does not let you continue):
- '>
- ">
• Copy from the DOS window.
- Right-click and select Mark. Click the first character to copy it.
- Press and hold the Shift key and click the last character to copy it.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

- Press Enter to place the selection in paste buffer.


• Paste into DOS window
- Place the cursor at the prompt.
- Right-click and select Paste.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 2 - 14


tee File

• The tee file is a text file that logs all mysql client
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

statements and their output.


• Everything you see displayed on the screen is appended
into a given file.
• You can enable this feature interactively within the mysql
client with the tee command:
mysql> tee session_tee_log.txt
to
• The tee file can be disabled with the notee command. A 1n ense
3 % e lic
• Executing tee again re-enables logging. l% C bl
c
n using r
fethea
• View the text file from the file location 2 0Iby n s
command-line text editor or d lla%nonExplorer.
Windows
i -tra
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
When writingY to an@existing utee s file (re-enabling), the new statement information will be
l l a
appended to
b a dithe current file content.
l ฺ b o
( yae

MySQL for Beginners 2 - 15


Quiz

The MySQL command-line client execution permits many


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

options. What command do you use to list and define those


options?
a. mysql -u root -p -h
b. mysql --help
c. Use the down-arrow key to step through all the commands
shown after the mysql client is invoked.
to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 2 - 16


Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Explain the MySQL client/server model


• Describe the communication protocols used to interact with
the MySQL server
• Explain how MySQL works with connectors
• Identify the components of a LAMP stack, and their roles
• Install the MySQL server
n nse to
• Start the MySQL server and the mysql client A1 % ice
• Install the world_innodb example databaseC3 ble l
n c l% era
• Use command-line editing methods 0I n s f
2 tra
• Use a text file to log your mysql i l l a%client n -
session
b a d a no
B o as i d eฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
l l a
b a di
l ฺ b o
e
(ya

MySQL for Beginners 2 - 17


Practice 2-1 Overview:
Install and Start the MySQL Server
This practice covers the following topics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Installing the current MySQL Server version by using the


MySQL Installer for Windows
• Starting the mysql client from the command-line prompt

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 2 - 18


Practice 2-2 Overview:
Use the Keyboard Editing and Tee Commands
This practice covers the following topics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Using the keyboard editing methods


• Creating and viewing a tee file

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 2 - 19


Practice 2-3 Overview:
Install the world_innodb Database
This practice covers installing the world_innodb database.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 2 - 20


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

MySQL Database Basics

to
A 1n ense
Relational Database
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(
Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Define a relational database (and RDBMS)


• Describe the structure of an RDBMS database
• Identify the differences between databases and
spreadsheets
• Explain the use of SQL and MySQL with relational
databases
to
• Define and use data definition language (DDL)
A 1n ense
• Define and use data manipulation language C 3% le lic
(DML)
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 3 - 2


RDBMS: Overview

• A relational database management system (RDBMS):


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Manages data according to the relational model


– Organizes and stores data in the form of tables
– Example: A bank database has tables for currency data,
customer information, account information, and so on.
• A database is a collection of data placed in tables.
– Synonymous with “schema”
• The relational model to
A 1n ense
– Data logically organized as tables and relations3%
e l ic
– An improvement over the hierarchical database l C
% model, bl which
c r a
has the following problems: 2 0In ansfe
l
Requires additional steps to icoordinatel a% onthe -tr data and programs
bad s and

a nperform
— Difficult to develop applications
B o a i d eฺ required operations
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y model,
In the relational us
@ the fundamental structure to organize data is the “relation,” which is
l l a
where it gets
b a diits name. For most purposes, the term “table” is interchangeable with the more
abstract
l ฺ b o term “relation.” The term “table” is used in the remainder of this course.

( yae“Database” is MySQL terminology. Other RDBMSs use the term “schema.”


For example, a database for a bank might contain a table to store currency data, a table to
store customer data, and a table for its accounts. These tables are obviously related: a
customer can have one or more accounts, and an account can express its balance in a
particular currency. However, the existence of these relationships is not a defining
characteristic of a relational database. The only reason for a DBMS to be called relational is
that it stores its data in tables, regardless of whether or not these tables are related to one
another.
Continuing with the bank example, a hierarchical representation would require a list of
customers and, within each customer entry, a list of bank accounts, which contain a currency.
To list all used currencies, you must first examine all the customers and then, for each
customer, you must look at all accounts. This shows a case for using the relational model
over the hierarchical model, which requires many additional steps to coordinate the data and
programs that work with a database. The hierarchical model makes it incredibly time
consuming to develop applications and to perform many required operations.

MySQL for Beginners 3 - 3


Spreadsheet Versus Database

• Spreadsheets are flexible and provide more user interface


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

features:
– Allow any data to be entered into a cell
– Convert data into graphs
– Format directly into printable reports with header and footer
• Databases are much more powerful than spreadsheets
due to data query and manipulation capabilities:
to
– Retrieve all records that match certain criteria
A 1n ense
– Cross-reference records between tables
C 3% le lic
– Update records in bulk
n c l% erab
– 2 0I ansf
Perform complex aggregate calculations
% l l r
a on-t
i
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 3 - 4


Entities and Relationships

• Entities: Things in the real world that you store information


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

about in a database.
– Tables typically store data representing one type of entity.
– Example:
— A bank database has a customer table specifically for
customer information.
— The customer table can contain entities/columns such as the
customer name, account number, and contact information.
to
• Relationships: Links between entities that have 1n
A e n se
something to do with each other. % e lic
– Example:
C3 l % rabl
c fe customer
The bank customer name has a relationship 2 0In atonsthe
a% on-tr

l
account number and contactilinformation.
bad s abetween
There can also be relationships
o
n ฺseparate tables (for
ide

example, customer r a Bto accounts).


h a u
nd yฺmx ent G )
j a
le © 2012,
2 0 A
Copyright
ฺ u tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
You cannot Yaliterally@ co things
store u sein a database, nor any relationships they might have. What
d
you can store i linlaa database is data. Storing information about things such as customers, bank
o
accounts
b baand currencies in our database, means that you store data in your database that
lฺ
erepresents these real-world things.
(ya In relational databases, one table is typically used to store data that represents entities of one
particular kind. As in the bank example, the customers table is used to store items of data,
each of which represents exactly one entity of the "customer" kind.

MySQL for Beginners 3 - 5


Relationship Categories

Relationship categories and examples:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

one-to-one Relationship between one car and


one engine

many-to-one
Relationship between many animals
and one zoo
to
Relationship between one 1n ense
bank
A
one-to-many
customer and many accounts C 3% le lic
n c l% erab
2 0I ansf
Relationship
i l l a % between n - tr many students
many-to-many
b a d a no
ando as courses
many eฺ
B
ra x) h t Gu i d
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
RelationshipsY can@ us according to how many entities can possibly be involved at
be categorized
l l a
either end of
b a dithe relationship.
In the
l ฺ b oslide example of a one-to-one relationship, a car has one engine, and the engine can
( yaebelong to only one car. There is a one-to-one relationship between the car and the engine.
Often these types of relationships are put in the same table, but not always.
In the slide example of a one-to-many relationship, an individual customer of a bank can
have more than one account. Note that this allows for customers to have zero, one, or more
bank accounts. The word many refers to the maximum number of possible bank accounts for
each customer. Alternatively, a bank account is tied to a single customer only. That is why this
is a one-to-many relationship.
There is a many-to-many relationship between students and courses. A student can attend
more than one course and a course can be attended by many students.

MySQL for Beginners 3 - 6


RDBMS Database Structure

• Two-dimensional tables, columns, and rows:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– An ordered set of columns (1 or more)


– An unordered set of rows (0 or more)
• Each table row has exactly one value for each column.
Data Storage

Database1 Database2 world_innodb Database4 Database5 to


A 1n ense
C 3% leRowlic
Code Name
n c l% erab
Continent
ABW Aruba 0I Norths
n f
America
Country AFG
2
% n-trAsia
Afghanistan a
i l l a
AFG d Afghanistan
b a a no ฺ Africa
B o as e
idColumn
Tables r a ) h u
j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
Row-Column @ co use
Ya Relationship
• Rows d i llaa collection of values that describe an entity (such as a bank account).
are
b o ba are a collection of similar data among rows (such as customer surnames).
Columns
a e lฺ Each column has a name and a data type.

( y
• The intersection of row and column contains individual data items called values. Values
are always atomic, that is, each position in a table may contain only one datum (piece of
data). If you have ever used a spreadsheet, you have used a table of data.
It is common to present data in a simple two-dimensional table form. The relational model
stipulates that a relation must have unique tuples—no two entities can be identical or you
would not be able to distinguish one from the other. There must be some combination of
columns (possibly, all columns) called a key, whose values uniquely identify each tuple. Most
RDBMSs are less strict. Virtually all of them allow a table to contain duplicate rows, and allow
a table to exist without a key.
Note: In SQL, tables are not required to have primary keys. In other words, the requirement of
the relational model is not enforced in SQL. However, it is enforced as soon as a primary key
is added to the table. A detailed discussion of primary keys, and how to create them, is
provided later in the course.

MySQL for Beginners 3 - 7


Using SQL with Databases

• Structured Query Language


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Standardized language
• Based on the English language (phrases)
• Categories of phrase types:
– DDL: Data definition language
– DML: Data manipulation language
• The “core” of the relational database
to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @with
SQL in conjunction co the ufeatures
se of MySQL provides an easy, efficient way for users to
i lladatabases. A user must be able to add, delete, modify, and retrieve the data
manipulatedtheir
o ba To make this possible, MySQL makes use of:
in a database.
b
a e l•ฺ The SQL language
( y • A powerful server
• Flexible program connections
SQL is a standardized language for communicating with relational databases. The majority of
database vendors have add-ons and extensions to the syntax, but most SQL dialects provide
a reasonably adequate subset of the features defined in the standard. The language is
designed to mimic the English language, and is most commonly used in phrases rather than
individual words. The categories of these phrases are discussed in the next two sections.

MySQL for Beginners 3 - 8


Data Definition Language: SQL Statements

• Create and delete database:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

CREATE DATABASE
DROP DATABASE
– DATABASE is synonymous with SCHEMA.
• Create and delete database table:
CREATE TABLE
DROP TABLE o
1 n nse t
• Modify databases and tables:
3 %A e lice
ALTER DATABASE l % C bl
I n c f e ra
ALTER TABLE 20 tran s
%
lla non-
d i
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
The DDL Y @
SQL statements usused to define database and table data. The statements shown
are
in the slided l l a
i followed by options to specify data operations.
are
o b a
Forbexample, to create a bank database with a table for customer information, you can enter
l ฺ
( yaethe following statements:
CREATE DATABASE mybank
CREATE TABLE customers
Because SQL is phrase based, the order of words is important. For example, CREATE
mybank DATABASE and DATABASE mybank CREATE are not correct SQL statements. Only
CREATE DATABASE mybank is correct.
In the CREATE DATABASE and DROP DATABASE statements, SCHEMA is considered
synonymous with DATABASE (such as CREATE SCHEMA).

MySQL for Beginners 3 - 9


Data Manipulation Language: SQL Statements

• Retrieve data:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

SELECT ... FROM


• Add new data:
INSERT INTO
• Modify data:
UPDATE
to
• Remove data:
A 1n ense
DELETE ... FROM
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
The DMLY
a
@ co are
SQL statements u e to manipulate database and table data. The statements
sused
d
shown in the i lla are followed by options to specify data operations (such as table name).
slide
o ba to select all the data from the customer table, enter the following statement:
Forbexample,
a e lฺ SELECT * FROM customers
( y
Note: Using DDL and DML statements is covered in detail later in the course.

MySQL for Beginners 3 - 10


MySQL: Benefits

The following are some of the benefits of MySQL:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Supports SQL “dialect,” which is a powerful extension of


the standard SQL language
• Runs on many different operating systems
• Is flexible and secure authorization system
• Supports very large databases
• Is very customizable
to
• Is built for speed A 1n ense
• Is free or inexpensive C 3% le lic
n c l% erab
• Includes tools and commercial features
2 0I ansf
• Is available as open source andi l l aas n - tr
% commercial licenses
d n o
ba
Bo as a deฺ
• Provides exceptional support
r a x) h Gui
a d
n yฺm ent
e j
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 3 - 11


Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Define a relational database (and RDBMS)


• Describe the structure of an RDBMS database
• Identify the differences between databases and
spreadsheets
• Explain the use of SQL and MySQL with relational
databases
to
• Define and use data definition language
A 1n ense
• Define and use data manipulation language C3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 3 - 12


Practice 3-1 Overview:
Quiz–Database Basics
This practice covers the following topics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Answering questions about database basics


• Answering questions about MySQL-specific SQL and
RDBMS applications

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 3 - 13


Practice 3-2 Overview:
Identify the Structure of a Table
This practice covers identifying the relational database
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

structure of a given table example.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 3 - 14


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

MySQL Database Design

to
A 1n ense
Table Design
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(
Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Explain database modeling


• Explain how to use keys to identify a row
• Explain how to use foreign keys to achieve referential
integrity
• Define and perform normalization
• Prepare a design plan for a new database
to
• View a database structure A 1n ense
% ic
• Evaluate a database design C3 ble l l% era
n c
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 4 - 2


Database Modeling

Database modeling is the process of specifying the database


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

table structure, based on the specific type and use of data.


• Before building a database, some database structure
modeling is highly recommended.
• To effectively design a database, you must know the
questions to be asked of the database.
• The entity-relationship model (ERM) is the most common
model for RDBMSs. n e to
1
A icen s
– Top-down method %
C 3 le l
– Used to produce an entity-relationship diagram
n c l% e(ERD)
f r ab
2 0I ans
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @cmodel o issused e to depict a relational database using a top-down method.
An entity-relationship u
lla with an overall “black box” view, then adds details as the process is
This methodd istarts
a product of this modeling process is a diagram called an entity-relationship
o
refined.
b bThe
a e lฺ (ERD). There are multiple types of ERDs used at different stages of modeling and for
diagram
( y different reasons.
Note: The information provided here for database modeling is intended to give a high-level,
conceptual view. This is a very deep topic that could take several days to cover on its own.

MySQL for Beginners 4 - 3


Structure Diagram (ERD)

• Visualize the content and relationships of a database.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Organize data into groups of similar entities (to be placed


in tables).
• Example of a high-level diagram of the world database:

contains CountryLanguage
to
Continent contains Country A 1n ense
C 3% le lic
n c l% erab
contains
2 0I ansf City
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 4 - 4


Cardinality Diagram (ERD)

• Indicate the type of relationship between table entities.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Use lines and specific symbols (notation) to indicate table


relationships.
• Symbols are used to indicate very specific states:
Zero or one

Exactly one (one and only one)


to
Zero or many A 1n ense
C 3% le lic
One or many
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
There areY
a
@
many types coof ERDu e
ssymbols (notation). The type of notation shown in the slide is
l l a
called “crow's
b a di foot” notation, and is one of the most commonly used.
To b beoprecise, the zero or many symbol can also mean zero or one or many.
l ฺ
( yae

MySQL for Beginners 4 - 5


Cardinality Diagram: Examples

• One-to-one: One car must have only one engine:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Car Engine

• One-to-one (or many): An individual customer of a bank


can have more than one account:
Customer Account

• Zero (or many)-to-one (or many): Zero or many students


to
can take one or many courses: 1n nse A ice
3 % e l
Students C
l% erab l
Courses
n c
• Zero (or one)-to-zero (or many): Zero 2 0I oraone n sf person can
rent zero or many DVDs: dilla non-
% tr
ba s a
oRenter eฺ
r a B h a u i d DVD
nd yฺmx ent G )
j a
le © 2012,
2 0 A
Copyright
ฺ u tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Yathe other
To complete @ coside ofusthee cardinality for each relationship:
d i
• One-to-one:
lla One engine can be installed only in one car at a time.
b o ba
One-to-one (or many): One or many accounts must be assigned to one bank customer.
elฺ

(ya • One (or many)-to-zero (or many): One or many courses can be taken by zero or many
students.
• Zero (or one)-to-zero (or many): Zero or many DVDs can be rented by zero or one
renter at a time.

MySQL for Beginners 4 - 6


Keys

• Candidate key:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– It is a column that can uniquely identify a row.


– You can have multiple candidate keys per table.
• Primary key:
– A primary key is a chosen candidate key that best identifies
one unique row.
– It ensures that duplicate values do not occur.
– It cannot contain NULL.
to
– It can decrease lookup time for large tables. A 1n ense
– You can have only one primary key per tableC3
% e lic
c l % rabl
• Foreign key:
2 0In ansfe
– A foreign key is a column thatllmatches
i a% on-atrprimary key in
another table to cross-reference
o bad s atables. n ฺ
e tables.
– It creates referential r a Bintegrity h abetween u idtwo
nd yฺmx ent G )
j a
le © 2012,
2 0 A
Copyright
ฺ u tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
o data.
Ya @tocidentify se This keeps data records (table rows) in a database
Use key attributes
a u
organized. dill
o ba for using foreign keys is primarily for referential integrity:
Thebpurpose
a e l•ฺ Referential integrity is a property of data which, when satisfied, requires every value of
( y
one attribute (column) of a relation (table) to exist as a value of another attribute in a
different (or the same) relation (table).
• To maintain referential integrity in a relational database, any column in a table that is
declared a foreign key can contain only values from a parent table's primary key (or a
candidate key). For instance, deleting a row that contains a value referred to by a
foreign key in another table would break referential integrity.

MySQL for Beginners 4 - 7


Cardinality ERD: Example

The world_innodb database ERD, showing key designations:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Country
CountryLanguage
Code CHAR (3)
CountryCode CHAR (3)
Name CHAR(52)
Language CHAR (3)
Continent ENUM (…)
IsOfficial ENUM (‘T’,’F’)
Region CHAR (26)
Percentage FLOAT
SurfaceArea FLOAT
IndepYear SMALLINT(6)

Population INT (11)

o
n nse t
LifeExpectancy FLOAT

1
%A e lice
GNP FLOAT
GNPO Id FLOAT City
3
C bl
LocalName CHAR(45) ID INT (11)
c l % ra
GovernmentForm CHAR (60) I
0 an
Name CHAR(35) n s f e
• %2
HeadOfState CHAR(60)

i l l a on-tr
CountryCode CHAR (3)

bad s a n eฺ
Capital INT (11) District CHAR(20)
Code2 CHAR (2)
o
B ha
Population INT (11)

d r a x ) G uid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
A primaryY
a becaosinglesvalue e (such as ID in the City table) or a combination value (as
key can @ u
lla + Language in the CountryLanguage table).
i
in CountryCode
d
o ba
Thebworld_innodb ERD demonstrates the foreign key relationship between the Country and
l ฺ
( yaeCountryLanguage tables, indicated by the reference to the primary key (Code) in the
Country table, by the CountryCode column in the CountryLanguage table. There is also a
foreign key relationship between the Country and City tables, where the primary key (Code)
in the Country table is referenced by the CountryCode column in the City table.
The world_innodb ERD also shows the relationship between the one Code in the Country
table and the many CountryCodes (per language) in the CountryLanguage table. It also
shows the relationship between the one Code in the Country table and the many
CountryCodes (per city) in the City table.
The double bar notation on the Country table side means “one and only one.” The bar and
crow’s foot combination on the referencing table sides (CountryLanguage and City) means
“one or many.” For the Country-to-CountryLanguage relationship, there can be only one
code per country, but there can be one language (or many languages) per country code. For
the Country-to-City relationship, there can be only one code per country, but there can be
one city (or many cities) per country code.
Note: There are hands-on practices for ERDs later in the course.

MySQL for Beginners 4 - 8


Normalization

Normalization is the process of refining a relational database


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

design to ensure that each independent piece of information is


in only one place.
• Eliminates redundant data
• Eliminates modifications that make the data inconsistent
• “Decomposes” database into a set of smaller tables
• Removes multivalued attributes and repeating groups
to
• Facilitates good database design 1n nse
3 %A e lice
l % C bl
I n c f e ra
20 tran s
%
lla non-
d i
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y is a@techniqueuthat
Normalization s is widely used as a guide in designing relational databases.
l l a
i database makes it possible to access data more flexibly, and eliminates the
Normalizing
b a dyour
l ฺ b o
possibility that inappropriate modifications render the data inconsistent.
eThis process removes undesirable multivalued attributes and repeating groups within rows,
(ya and data redundancy within columns. Repeating groups and multivalued attributes are
essentially tables within tables. Like the organization of hierarchical databases, this would
effectively make it impossible to access the inner table without first accessing the outer table.
This would lead to the hierarchical database problems described in the previous chapter, and
defeat the purpose of using an RDBMS.
Although this course focuses on the use of SQL (to create and use databases), all the
well-written SQL code in the world cannot fix a badly designed database. It is very important
to spend the necessary time and effort on proper database modeling and normalization before
building your database.
Note: The information provided here about normalization is intended to give only a high-level,
conceptual view of table structure and its importance. This is a very deep topic that could take
several days to cover on its own.

MySQL for Beginners 4 - 9


Advantages of Normalization

• ERDs:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Enables you to develop diagrams effortlessly when tables,


columns, and relationships are predetermined
• Updates:
– Avoid anomalies such as insertion, deletion, and modification
problems, which cause inconsistencies with updates
• Compact:
– Modifies a single object property easily to
A 1n ense
• Data access:
C 3% le lic
– Enables you to access all logically required
n c l%dataerab
0 I n s f
• Joins: 2
% n-tra
i l l a
– Identify the join columns ad
b a no ฺ
– Minimize the amount B o dataahaving
of s itodebe searched
r a ) h u
j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
Ya @co use
d i lla
b o ba
elฺ
(ya

MySQL for Beginners 4 - 10


Disadvantages of Normalization

Despite the numerous advantages of normalization, there are


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

some disadvantages to be considered:


• Several tables:
– Must be accessed for user reports and other user data
• Maintenance:
– Can be in some conflict with the business processes. For
example, you may have to duplicate information or create
summary tables to gain more speed, due to the maintenance
n e to
costs of keeping multiple copies of data. A1 ens % e lic
C 3
• Resource usage:
c l % rabl
– Can be an expensive process in time0Iand n resources
n s fe
2
% thenrequired tra data
– Takes many join statements ito l l aget -
b a d a no
B o as i d eฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
i l l a
b o bad
l ฺ
(y ae

MySQL for Beginners 4 - 11


Eliminating Data Inconsistencies

Eliminating insertion, deletion, and modification anomalies is a


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

key advantage to normalization.


• Poorly designed table structures result in duplicate data,
redundant data, and difficulties in using the data.
• To avoid anomalies, ensure that each table column meets
the following criteria:
– Represents a characteristic of the table subject
o
– Contains only a single value
1 n nse t
– Is not deconstructed into smaller components 3%
A ice
C l e l
– Does not contain a calculated or concatenated
n c l% value
f e r ab
2 I
0structure n s
– Is unique within the entire database
a% on-t r a
i l l
– Multitable columns (in relationship)
o bad s a nareeidentical ฺ
B
ra x) h t Gu a i d
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
A central Y @
idea in normalizationusis the use of the correct columns in each table to remove data
l l a
b a di The best way to detect columns that can lead to these anomalies is to ensure
inconsistencies.

l ฺ b o
that each column you design meets the following criteria:

( yae • Represents a characteristic of the table subject: Design tables to address a subject
of the complete database. The columns within those tables must represent the subject
of the table they are in. For example, a table representing a dinner menu would not
include shoe sizes of guests.
• Contains only a single value: If a column contains more than one value (multivalued
columns), the data contained is more difficult to work with and the potential for data
redundancy is high.
• Is not deconstructed into smaller components: In a column that contains multiple
potential separate data elements (multipart column), deconstruct the column into
smaller, separate columns. An example of this would be an address column that can be
broken down to Street_Number, Street_Direction (N, E, W, S, and so on), Street_Name,
Street Identifier (Drive, Court, Lane, and so on), rather than being one column that
contains all those elements.

MySQL for Beginners 4 - 12


• Does not contain a calculated or concatenated value: Columns must not have to
depend on their value being derived from other column data. If using calculated or
concatenated columns, you have to put in place unnecessary business processes to
ensure that associated column modifications are passed to these columns.
• Is unique within the entire database structure: Ensuring that a column in one table
does not have a redundant or duplicate column in another table eliminates the anomalies
associated with modifying or deleting identical data in more than one place.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Has identical multitable columns (in relationship): When a column is used in more
than one table to create relationships between the tables, it is crucial that they are
identical, including column type.
Note: The term “column” in this context is also sometimes referred to as “field.”

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 4 - 13


Normal Forms

• Many successive levels (called normal forms) of


normalization guarantee consistency.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Each consecutive normal form depends on the previous.


• The first three levels are the most common (from 1NF to
2NF to 3NF):
Third Normal Form (3NF)

Second Normal Form (2NF) o


1 n nse t
the 3 %Asolely
Dependent
primary
e l
key and
on e
i c
First Normal
l C no other b
%(supporting) l
non-key
Form (1NF)
Every non-key
n c f r a
e valuecolumn
(supporting) column
0 I s
No repeating groups
value is dependent 2
a
on the primarylkey. % - t r an
within rows
a d il non
B ob as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Each normal Y form@ depends u onsthe previous normal form and it is best practice to work through
l l a
b a di
each one individually (in sequence starting with the first normal form). There are numerous
normal
l ฺ b o forms. However, the first three levels usually provide adequate normalization, and are

yae
the most common:
( • First normal form (1NF): A table in the first normal form contains no complex
(nonsimple) column types, such as repeating groups within rows. If a table is not in 1NF,
it is not normalized.
• Second normal form (2NF): A table is in second normal form if it is in 1NF and every
non-key (supporting) column value is dependent on the primary key value. In addition,
the latter constraint means that a non-key value must depend on every column in a
composite primary key.
• Third normal form (3NF): A table is in third normal form if it is in 2NF and every
non-key (supporting) value depends directly on the primary key and not on some other
non-key column.

MySQL for Beginners 4 - 14


Normalization Process: Example

The normalization process is demonstrated by using a very


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

simple example:
• Furniture store
– You want to turn your inventory spreadsheet into a database,
so you can:
— Execute intelligent searches
— Make modifications
— Prepare for future growth of your business
n e to
• Original inventory spreadsheet 1
A icen s
%
3 le l
Inventory
C
sID sLoc sPostal pID1 pName1 pQty1 pID2cl%
n pID
f e r ab pQty2
pName2
1 Holtsville 00501 1 bed 15
2 0I2 an2 s chair 4
2 Waukesha 53146 1 bed
l l %
a on-
4 3 t r 3 table 6
3 Waukesha 53146 2 chair
i
ad a8 n 4 ฺ 4 sofa 4
o b
4 Ketchikan 99950
r
2 B chair
a ) h as 24 uid4e 4 sofa 10

j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
Yayou @ o sestore, and you want to use MySQL to turn your inventory
ownca furniture
Imagine that
i l l a a database.u Your original “Inventory” spreadsheet is shown in the slide. This
spreadsheet
o b
spreadsheetad is the basis for the next several slides, which demonstrate the normalization
into

e l ฺb
process.
( ya

MySQL for Beginners 4 - 15


First Normal Form: 1NF
Inventory
sID sLoc sPostal pID1 pName pQty1 pID2 pName2 pQty2
1 Holtsville 00501 1 bed 15 2 chair 4
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

2 Waukesha 53146 1 bed 4 3 table 6


3 Waukesha 53146 2 chair 8 4 sofa 4
4 Ketchikan 99950 2 chair 24 4 sofa 10

1NF

PK Inventory_1NF PK
sID sLoc sPostal pID* pName pQty
1 Holtsville 00501 1 bed 15
to
1n ense
1 Holtsville 00501 2 chair 4
2 Waukesha 53146 1 bed 4 A ic
6 3% l
2 Waukesha 53146 3 table
C
%8 rabl e
3 Waukesha 53146 2 chair
c l
3 Waukesha 53146 4
2 0sofaIn an4sfe
2 % chair-tr
4 Ketchikan 99950
99950 d i l l a o n 24
4 Ketchikan
b a 4
a n ฺ 10
sofa

B o appearainsa first normal


* This column would not usually eform; however,
idnatural
d r a
it is here to demonstrate a ) h
connection
x G u
to the second form.
n ฺm den
ja© 2012,dOracle t
l e y
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @to 1NF must
The transformation us never result in loss of data. It is primarily a matter of
l l a
organization
b a diof data.
In the
l ฺ b ofurniture store spreadsheet in the slide, notice that pID1 and pID2 are both in the same
( yaerow, yielding duplicate information. This causes a problem if you try to remove part of pID1
from Holtsville (with a DELETE statement). It removes the whole row, including the
information about pID2 (so that removing the “bed” also removes the “chair”).
To keep that from happening, you take the "fat" spreadsheet (with its nine columns and
duplicate values), and turn it into a "skinny" table (with six columns that have only one type of
column per row). In the Inventory_1NF table, you do not lose the “chair” if you remove the
“bed.” The goal is to have all data without repeating any groups (duplicating column data) in a
row.
Note that the Inventory_1NF table has a composite primary key made up of the sID column
and the pID column. At this stage, there is no single column that can be used as a primary
key to ensure that there are no repeating groups.
The redundancy that still exists after this first level of normalization allows for inconsistencies
and data integrity issues during updates and deletes. Therefore, you need to put this table
through the second normal form.

MySQL for Beginners 4 - 16


Second Normal Form: 2NF
PK Inventory_1NF PK
sID sLoc sPostal pID* pName pQty
1 Holtsville 00501 1 bed 15
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

1 Holtsville 00501 2 chair 4


2 Waukesha 53146 1 bed 4
2 Waukesha 53146 3 table 6
3 Waukesha 53146 2 chair 8
3 Waukesha 53146 4 sofa 4
4 Ketchikan 99950 2 chair 24
4 Ketchikan 99950 4 sofa 10

sLoc and pName


2NF PK PK Part_1NF
depends to
sPostal do not
depend on pID.
1NF sID pID pName
A 1n ense
pQty
only on pID.
1 1 bed
3 % e lic 15

Supplier_2NF
1 2
l C
% rabl
chair 4
2 1 c bed 4
0In ansfe
PK sID sLoc sPostal
2 3 table 6
1 Holtsville 00501 2
2 Waukesha 53146
i l
3
l a% on-tr 2 chair 8

3 Waukesha 53146
o b ad a n ฺ
3
4
4
2
sofa
chair
4
24
4 Ketchikan
r B has uide
99950
a 4 4 sofa 10

a n d mx) nt G
A lej © 2012,
a d yฺ uditseaffiliates. All rights reserved.
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


A table atY this level us has been normalized to the first normal form (1NF), plus
@of normalization
l l a
every non-key
b a di (supporting) value depends on the primary key value. In addition, the latter
l ฺ b o
constraint means that a non-key value must depend on every column in a composite primary

yae
key. The Inventory_1NF table does not meet these criteria; therefore, it requires further
( normalization.
The single table has been split into two tables, Supplier_2NF and Part_1NF, which address
the supplier and part categories, respectively:
• Supplier_2NF: Has one primary key (sID) with two supporting columns (sLoc and
sPostal) that depend on the primary key, making it a table that is in second normal form
• Part_1NF: Has a composite primary key (made up of sID and pID) but the supporting
column (pName) is not dependent on both of the composite keys (dependent only on
pID), which means that this table is still in first normal form

MySQL for Beginners 4 - 17


Third Normal Form: 3NF
PK PK Part_3NF
sID pID pQty
Part_1NF
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

PK PK
3NF 1 1 15
sID pID pName pQty
1 2 4
1 1 bed 15 2 1 4

1 2 chair 4 2 3 6
3 2 8
2 1 bed 4
3 4 4
2 3 table 6 4 2 24
3 2 chair 8 4 4 10

3 4 sofa 4
n e to
4 2 chair 24 PK PartName_3NF 1
A icen s
3NF %
3 le l
pID
C pName
ab
4 4 sofa 10
1c
n l% bed e r
0I 2 anschair f
2
i l l a% on3-tr table
o bad s a n e4 ฺ
r a B ha u id sofa

nd yฺmx ent G )
j a
le © 2012,
2 0 A
Copyright
ฺ u tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
A table atY
a o se has been normalized so that every non-key (supporting)
ofcnormalization
i l l asolely on theuprimary key and not on some other non-key (supporting) value.
this level @
o ad
value depends
b
The Supplier_2NF and Part_1NF tables do not meet these criteria; therefore, they require
l ฺ b
yae
further normalization. They are not yet in third normal form due to the following anomalies with
( the current tables:
• Update problem: The Part_1NF table has a problem with updates. If you change the
pName to “armchair,” where sID is 1 and pID is 2, then you have inconsistent data in
the pName column. The other “chair” values are no longer matching with this one; one
is “armchair” and the others are still “chair.” Notice in the next illustration that it is
impossible to do this when it is in 3NF.
• Insertion problem: The Part_1NF has a problem with inserts. Assume that the
manufacturer now has a new “Loveseat” for sale in the future. You want to add a
“Loveseat” (pName) to the parts with a pID of 5. However, if you do this, you end up
with an empty value for pQty and sID. This creates inconsistency because you have
empty values, and it does not represent future possibilities. You now have three different
suppliers, so the sID and pQty need to have multiple rows.

MySQL for Beginners 4 - 18


In the case of the Part_1NF table, when you attempt to normalize it in the second normal form,
it is clear that it is truly in third normal form. Because of the lack of complexity in the initial table
(Part_1NF), the second normal form was essentially passed over and the two resulting tables
(Part_3NF and PartName_3NF) met all the criteria of the third normal form. Now, if you change
“chair” to “armchair,” they are changed everywhere consistently.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 4 - 19


Third Normal Form: 3NF
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

PK Supplier_3NF
sLoc
sID sPostal
depends on
1 00501
sPostal.
2 53146
Supplier_2NF 3NF 3 53146
PK sID sLoc sPostal 4 99950
1 Holtsville 00501
2 Waukesha 53146
3 Waukesha 53146
PK n e to
4 Ketchikan 99950 3NF
SupplierPostal_3NF
1
A icen s
sPostal sLoc
%
3 le l
00501 C
l% erab
Holtsville
53146 c Waukesha
n
0I anKetchikan sf
2 99950

i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Because Y
a
@ co dependency
of the transitive u se in the Supplier_2NF table (sLoc depends on both sID
i a table could not be considered to be in third normal form. By normalizing that
llthe
d
and sPostal),
batwo separate 3NF tables (SupplierPostal_3NF and Supplier_3NF), updates in the
tableointo
e b
lฺ are less problematic.
future
( y a
To make it more practical, add an extra column to the Supplier_3NF table for supplier name
(sName), because two suppliers are in the same postal zone. This is easier to understand,
because most people think in terms of names and not numbers. However, if you want the
most efficient table, you would not use sName.

MySQL for Beginners 4 - 20


Normalized “Furniture Store” Database
Inventory
sID sLoc sPostal pID1 pName1 pQty1 pID2 pName2 pQty2
1 Holtsville 00501 1 bed 15 2 chair 4
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

2 Waukesha 53146 1 bed 4 3 table 6


3 Waukesha 53146 2 chair 8 4 sofa 4
4 Ketchikan 99950 2 chair 24 4 sofa 10

PK PK Part_3NF PK Supplier_3NF PK SupplierPostal_3NF


PK PartName_3NF
sID pID pQty sID sPostal sPostal sLoc
pID pName
1 1 15 1 00501 00501 Holtsville

1 2 4
1 bed 2 53146 53146 Waukesha
to
2 1 4 2 chair 3 53146
A 1nKetchikan
99950
e n se
2 3 6 3 table
4 99950
C 3% le lic
3 2 8 4 sofa
n c l% erab
3 4 4
2 0I ansf
4 2 24
i l l a% on-tr
4 4 10
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
a
The entireYview (ER
o sofethe normalization that was completed on the original
cdiagram)
l l a @ u
a d i
Inventory spreadsheet is shown in the slide.
One b of b
o the positive consequences of normalizing a database is that the relationship between
l ฺ
( yaetwo tables can result in a One-to-Many relationship. This relationship ensures an efficient
approach to updates, deletes, and alterations to existing data. The database now consists of
four tables, which have been sufficiently normalized.

MySQL for Beginners 4 - 21


Quiz

The first three normalization forms are cumulative and build on


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

each other, starting with the first normal form (or 1NF).
a. True
b. False

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 4 - 22


Database Design Considerations

• Organize new database data by means of normalization.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Can also use to evaluate and improve an existing database


– Normalize only to the point where it is useful.
• Put “pen to paper” and document the process, even if you
do not use normalization.
• Eliminate repeating groups.
• Ensure that each column contains only one value.
to
• Use candidate keys. A 1n ense
• Give columns sensible names. C 3% le lic
n c l% erab
• Create new tables to better organize nsf
20(ifI needed).
i l l a% on-tra
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya columns,
For all non-key @ co determine
u se if they depend on any combination of columns that is not
i
a candidatedkey.lla If so, you found a functional dependency and you must create a separate
tableo for a columns.
bthose
b
eAnlฺ appropriate saying for database design is “Normalize until it hurts…De-normalize until it
(ya works!” Ultimately, the business case guides the normalization process. You do not normalize
merely to normalize; you normalize to support reliable data maintenance. If you can show that
the business case is not improved by additional normalizing, do not perform additional
normalization, even if an additional level can be implemented.

MySQL for Beginners 4 - 23


Database Design Plan

To start the design process, ask these questions about your


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

database:
• What is the primary purpose of this database?
• What entities need to be stored, retrieved, and/or
modified?
• How do those entities relate to each other?

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 4 - 24


Database Design Plan Diagram
Database
Design Plan
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

No Primary No
Store? Retrieve?
Purpose

Yes Yes
No
Modify?

Yes

List List List


Entities Entities Entities

to
Build Database Model
A 1n ense
3% le lic
(establish relationships
and data types)
C
l% erab
n c
Normalization
2 0I ansf
Process
i l l a% on-tr
o bad s a n eฺ
Database

r a B ha Creation
uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
DatabaseY
a plancosteps: se
Design@
l l a u
i
ad the questions in the diagram in the slide.
• Answer
o b
•ฺb Start a structure diagram to visually represent your database design during the
e l
( ya construction of your plan.
• Make a list (or diagram) of the primary columns (that might eventually become tables).
• Make a list (or diagram) of the attributes that belong to each primary entity (that might
eventually become columns). Keep in mind that you need a unique identifier, which may
be an additional column.
• Determine the data types (and parameters) needed for each column. Depending on the
type of operations desired, you select a specific storage engine. Then, depending on the
storage engine, you choose fixed versus variable size data types as follows:
- For MyISAM, you use fixed data types.
- For InnoDB, you use variable.
- Use bit data type when flags are needed.
Note: Data types are covered in detail in the lesson titled “Table Data Types.”
• Normalize to the third normal form (or higher).
Additional adjustments can be made after the creation of a database, if necessary.

MySQL for Beginners 4 - 25


Viewing a Database

From within the mysql client, issue the following SQL


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

statements:
• SHOW DATABASES
• USE <database_name>
• SHOW TABLES
• DESCRIBE <table_name>
• SELECT * FROM <table_name> to
n
A 1 ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 4 - 26


Evaluating a Database Design

1. Connect to the database server:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

shell> mysql -uroot -p


Enter password: <password>

2. Display all databases/schemas:


mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql | to
| performance_schema |
A 1n ense
| test |
C 3% le lic
| world_innodb |
n c l% erab
+--------------------+
2 0I ansf
3. Change the default database/schema:
i l l a% on-tr
mysql> USE world_innodb
o bad s a n eฺ
Database changed B
d r a x) ha Guid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
Ya @co use
d i lla
b o ba
elฺ
(ya

MySQL for Beginners 4 - 27


Evaluating a Database Design

4. Display all tables in the database/schema:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SHOW TABLES;


+------------------------+
| Tables_in_world_innodb |
+------------------------+
| city |
| country |
| countrylanguage |
+------------------------+

5. Display all the columns in the specified table: to


A 1n ense
mysql> DESCRIBE City;
+-------------+----------+------+-----+---------+----------------+
C 3% le lic
| Field | Type | Null | Key | Default | Extral%
n c f e r a| b
| PRI | NULL 20
I
+-------------+----------+------+-----+---------+----------------+
n s |
| ID | int(11) | NO
a
| auto_increment
a% o|| n-t r
|ill
| Name | char(35) | NO | | |
| CountryCode | char(3) | NO
| District | char(20) | NO
|
| a |
d
b | s0 a | eฺ n |
|
|
| Population | int(11) | NO o|
a B h a u i d |

a n dr mx) nt G
+-------------+----------+------+-----+---------+----------------+

A lej © 2012,
a d yฺ uditseaffiliates. All rights reserved.
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


DESCRIBE Ydisplays us values for each column:
@the following
l l a
• Field:
b a di Indicates the column name
•ฺbo
Type: Indicates the column data type
e l
( ya • Null: Contains YES if NULL values can be stored in the column, NO if not
• Key: Indicates whether the column is indexed:
- PRI: Primary key index, or one of the columns in a multiple-column PRIMARY KEY
- MUL: First column of a nonunique index in which multiple occurrences of a given
value are permitted within the column
• Default: Indicates the default value that is assigned to the column
• Extra: Contains any additional information that is available about a given column. The
value is auto_increment if the column was created with the AUTO_INCREMENT
keyword and empty otherwise.
For more information about the DESCRIBE statement, see the MySQL Reference Manual:
http://dev.mysql.com/doc/refman/5.5/en/show-columns.html.

MySQL for Beginners 4 - 28


Evaluating a Database Design

6. Display all the data in the specified table:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT * FROM City;


+------+----------------+-------------+---------------+-----------+
| ID | Name | CountryCode | District | Population|
+------+----------------+-------------+---------------+-----------+
| 1 | Kabul | AFG | Kabol | 1780000 |
| 2 | Qandahar | AFG | Qandahar | 237500 |
| 3 | Herat | AFG | Herat | 186800 |
| 4 | Mazar-e-Sharif | AFG | Balkh | 127800 |
| 5 | Amsterdam | NLD | Noord-Holland | 731200 |
| 6 | Rotterdam | NLD | Zuid-Holland | 593321 |
... to
| 4079 | Rafah | PSE | Rafah | 92020 |
A 1n ense
+------+----------------+-------------+---------------+-----------+
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya 5 and o se and CountryLanguage tables. Note the differences in
6cfor theuCountry
Repeat steps
la @
lcontent.
d
structure and i
b o ba
a e lฺ
( y

MySQL for Beginners 4 - 29


Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Explain database modeling


• Explain how to use keys to identify a row
• Explain how to use foreign keys to achieve referential
integrity
• Define and perform normalization
• Prepare a design plan for a new database
to
• View a database structure A 1n ense
% ic
• Evaluate a database design C3 ble l l% era
n c
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 4 - 30


Practice 4-1 Overview:
Quiz–Database Design
This practice includes questions about database design.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 4 - 31


Practice 4-2 Overview:
Evaluate a Database
This practice covers evaluating the world_innodb database.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 4 - 32


Practice 4-3 Overview:
Create a Structure Diagram
This practice covers creating a complete structure diagram for
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

the world_innodb database, including all its tables and


columns.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 4 - 33


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Table Data Types

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(
Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Explain the use of data types in database design


• List the four MySQL data type categories
• Choose the correct data types for columns
• Describe the special considerations for using data types
• Explain the usage of NULL
to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 5 - 2


Data Types as Part of Database Design

The design of an efficient database structure includes the


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

assignment of data types:


• Use the database design questions to determine the
columns and data types required.
• Assign column data types according to column purpose:
– For example, from the Inventory database, the
PartName_3NF table and the pName column
to
values are all character data types, whereas the
A 1n ense
lic
pID column values are all numeric data types. 3% PartName_3NF
PK
C ble
• Follow the ABCs of data types: c l % a
rpID
I n s f e pName

– Appropriate % 20 tran 1 bed

– Brief d i lla non- 2 chair

– Complete o ba s a e ฺ
3 table

a B h a u i d 4 sofa

a n dr mx) nt G
A lej © 2012,
a d yฺ uditseaffiliates. All rights reserved.
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


ChoosingY a data @ us a matter of obtaining a model that is closest to your
type is primarily
l l a
b a di and is most capable of representing your data. When you have decided how
business reality,
to best
l ฺ b o represent your data, you can determine the best mapping between how you want it to

yae
be and the capabilities of the database. If you have a clear understanding of the possible
( mappings, then consider implementation efficiency.
• Appropriate: Represent the data needs in the type most fitting the column it represents.
• Brief: Choose the data type that uses the least amount of storage space. This saves
resources and increases performance.
• Complete: Choose the data type that allocates enough room to store the largest
possible value for a particular item.
Within each category, there are numerous specific data types that use varying amounts of
memory and disk space, which have varying effects on performance. Choosing the best data
type for the column has a small effect on performance in an individual record, but as the
database grows, these small effects can lead to larger effects. Take this into account early in
the design process, before they become performance issues.

MySQL for Beginners 5 - 3


Data Type Categories

• Numeric: Numeric values


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Temporal: Time and dates


• Character: Text strings
• Binary: Binary data strings

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
For more Y
a o data
cabout setypes, see the MySQL Reference Manual:
@
information
lla u
d i
http://dev.mysql.com/doc/refman/5.5/en/data-types.html.
b o ba
a e lฺ
( y

MySQL for Beginners 5 - 4


Numeric Data Types

• Factors to consider with numeric data types:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Range of values that the data type represents


– Amount of space that column values require
– Column precision and scale (floating-point and fixed-point)
• Classes of numeric data types:
– Integer: Whole numbers
– Floating-point: Fractional numbers
– Fixed-point: Exact-value numbers to
A 1n ense
– BIT: BIT-field values
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
For storing
a
Ynumeric @ co MySQL
data, u se provides the following numeric data type classes:
i a
llIntegers
• Integer:
b d
a places. do not have a fractional part. That is, a single integer value has no
l ฺb o
decimal
e
ya • Floating-point: Floating-point represents approximate-value numbers that have an
( integer part, a fractional part, or both. This data type class represents values in the
native binary floating-point format (IEEE 754) used by the server host's CPU. This is a
very efficient type for storage and computation, but values are subject to rounding error.
• Fixed-point: Fixed-point has an integer part, a fractional part, or both.
• BIT: BIT column specifications take a width indicating the number of bits per value, from
1 to 64 bits.
Precision and scale are terms that apply to floating-point and fixed-point values, which can
have both an integer part and a fractional part.
• Precision: The number of significant digits
• Scale: The number of digits to the right of the decimal point

MySQL for Beginners 5 - 5


Numeric: Integer Data Types

• Data types:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– TINYINT: Very small integer data type


– SMALLINT: Small integer data type
– MEDIUMINT: Medium-sized integer data type
– INT, INTEGER: Normal (average) size integer data type
– BIGINT: Large integer data type
• Example:
to
1n ense
– world_innodb database, City table, Population column:
A
Population INT(11)
C 3% le lic
% rab
ncl 10500000
– Largest value output (uses 8; 11 allowed): fe 0I ans
2
• Attributes: i l l a% on-tr
– UNSIGNED allows only positive
o bad s numbers.a n ฺ
e zeros.
– ZEROFILL replaces
r a Bpadding h aspaces u idwith
nd yฺmx ent G )
j a
le © 2012,
2 0 A
Copyright
ฺ u tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Yatypes@arecoassigned
Integer data u seusing the following syntax:
lla
INTdi[(<M>)]
•ฺbo
ba
M indicates the maximum display width for integer types. The maximum legal display
a e l width is 255. Display width is unrelated to the range of values a type can contain. The
( y display width depends on the data size.
• M is required only when used with the ZEROFILL attribute.
All integer types can have an optional (nonstandard) attribute UNSIGNED. You can use
unsigned values when you want to allow only nonnegative numbers in a column and you
need a larger upper numeric range for the column. For example, if an INT column is
UNSIGNED, the size of the column's range is the same, but its endpoints shift from -
2147483648 and 2147483647 up to 0 and 4294967295.
When you use an integer data type in conjunction with the optional extension attribute
ZEROFILL, the default padding of spaces is replaced with zeros. For example, when you
declare a column as INT(5) ZEROFILL, a value of 4 is retrieved as 00004. If you specify
ZEROFILL for a numeric column, MySQL automatically adds the UNSIGNED attribute to the
column.

MySQL for Beginners 5 - 6


Numeric: Integer Data Types Comparison

Storage
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Type Signed Range Unsigned Range


Required

TINYINT 1 byte –128 to 127 0 to 255

SMALLINT 2 bytes –32,768 to 32,767 0 to 65,535

MEDIUMINT 3 bytes –8,388,608 to 8,388,607 0 to 16,777,215


to
INT 4 bytes
–2,147,683,648 to
A 1n ense
0 to 4,294,967,295
2,147,483,647
C 3% le lic
–9,223,372,036,854,775,808 n0cto l% erab
n s f
0I 18,446,744,073,709,
BIGINT 8 bytes to 2 ra
l l a% on-t551,615
9,223,372,036,854,775,807
i
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Yadata @
The integer cocomparison
types u se chart in the slide lists the data types and their respective
d i
attributes, suchllaas the storage required, signed range, and unsigned range.
b o ba
a e lฺ
( y

MySQL for Beginners 5 - 7


Numeric: Floating-Point Data Types

• Used for approximate-value numbers: integer, fractional, or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

both
• Data types:
– FLOAT: Very small numeric data type
– DOUBLE: Small numeric data type
• Can declare with precision and scale
• Example: to
– world_innodb database, Country table, GNP column: A 1n ense
GNP FLOAT(10,2) C 3% le lic
n c l% erab
– Largest value output (uses 7; 10 allowed; 0I a2 ntosright f of
2
decimal): 8510700.00
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
YaDOUBLE o typesserepresent values in the native binary floating-point format
cdata
FLOAT and @ u
lla by the server
(IEEE 754)dused
a i host's CPU. This is a very efficient type for storage and
b o b
computation, but values are subject to rounding error.
l ฺ
( yaeYou can declare the floating-point columns with a precision and scale to indicate the total
number of digits (from 1 to 255) and the number of decimal places to the right of the decimal
point (from 0 to 30).
The FLOAT data type is assigned using the following syntax:
• FLOAT(M,D)
• M is the maximum number of decimal digits that can be stored and D is the number of
digits following the decimal point. A single precision floating point value is accurate to
approximately seven decimal places. In simplest terms, if M is less than or equal to 25,
the storage taken up is 4 bytes. If M is greater than 25, the storage taken up is 8 bytes.
The default value is NULL (if column can be NULL) or zero (0) if NOT NULL.

MySQL for Beginners 5 - 8


The DOUBLE data type is assigned using the following syntax:
• DOUBLE(M,D)
• M is the maximum number of decimal digits and D is the number of digits following the
decimal point. A double precision floating point value is accurate to approximately 15
decimal places. The default value is NULL (if column can be NULL) or zero (0) if NOT
NULL.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

The floating point assigned width does not affect how the numbers are actually stored; it affects
only how the number is displayed.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 5 - 9


Numeric: Floating-Point Data Types Comparison
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Storage
Type Signed Range Unsigned Range
Required

-3.402823466E+38 to
0 and 1.175494351E-38
-1.175494351E-38 to
FLOAT 4 bytes to
1.175494351E-38 to
3.402823466E+38
3.402823466E+38

-1.7976931348623157E+308 0
to
to
-2.2250738585072014E-308
and
A 1n ense
DOUBLE 8 bytes and
2.2250738585072014E-
308 C 3% le lic
2.2250738585072014E-308 to n c l% erab
to
2 0I ansf
1.7976931348623157E
1.7976931348623157E+308
i l l a% on-tr
+308

o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @
The floating-point cotypesucomparison
data se chart in the slide lists the data types and their
respective d i l l a
attributes, such as the storage required, signed range, and unsigned range.
o b a
l ฺ b
( yae

MySQL for Beginners 5 - 10


Numeric: Fixed-Point Data Types

• Used for exact-value numbers: integer, fractional, or both


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Data types:
– DECIMAL (also NUMERIC):
— Fixed-decimal, binary storage format
— Preserve exact precision

• Example:
– To represent currency values, such as dollars and cents:
e to
cost DECIMAL(10,2) 1n ens
– Example value output: 3 %A e lic
l % C bl
650.88
I n c f e ra
20 tran s
%
lla non-
d i
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
All valuesY in a DECIMAL
@ column us have the same number of decimal places. DECIMAL values
l l a
b
efficientlya diFLOATas orgiven,
are stored exactly
as
when it is possible. DECIMAL values are not processed quite as
values (which use the processor's native binary format), but
l ฺ b o DOUBLE
eDECIMAL values are not subject to rounding error, so they are more accurate. In other words,
(ya there is an accuracy versus speed tradeoff in choosing which type to use. For example, the
DECIMAL data type is a popular choice for financial applications involving currency
calculations, because accuracy is most important.
Integer data types are assigned using the following syntax:
• DECIMAL(M,D)
• M is the number of significant digits that can be stored and D is the number of digits
following the decimal point (from 1 to 255). A double precision floating point integer is
accurate to approximately 15 decimal places (from 0 to 30). The default value is NULL
(if column can be NULL) or zero (0) if NOT NULL.

MySQL for Beginners 5 - 11


Numeric: Bit Data Types

• Data type:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– BIT
• Bit-field values:
– Column Width (M) is number of bits per value
– 1 to 64 bits
• Example:
– Storing 4 and 20 bits: to
bit_col1 BIT(4) A 1n ense
bit_col2 BIT(20) C 3% le lic
n c l% erab
• Can assign values using Numeric expressions 2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya column,
For a BIT(n) @ cothe range
u se of values is 0 to 2 n – 1, and the storage requirement is
approximately i a
llINT((n+7)/8) bytes per value.
b a d
Assign
l ฺ b o BIT column values using numeric expressions. To write literal bit values in binary
( yaeformat, use the literal value notation b'val', where val indicates a value consisting of the
binary digits 0 and 1. For example, b'1111' equals 15 and b'1000000' equals 64.
Note: A rule of thumb for storage size is that n=8 takes 1 byte.

MySQL for Beginners 5 - 12


Temporal Data Types

• TIME:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– HH:MM:SS as in 12:59:02
• YEAR:
– Two (YY) or Four digit (YYYY) as in 2012
• DATE:
– YYYY-MM-DD as in 2012-01-04
• DATETIME:
– YYYY-MM-DD HH:MM:SS as in 2012-01-04 12:59:021n e to

ens
%A e lic
TIMESTAMP: 3
C bl
– Current date and time as in 2012-01-04 l %
c12:59:02 ra
I n s f e
– DEFAULT CURRENT_TIMESTAMP % 20 tran
d i lla non-
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Date and Y time data @types areusreferred to as temporal data types. MySQL provides data types
l l a
b
YYYY,oMM,
di HH, MM,
for storing different
aDD, kinds of temporal information. In the following descriptions, the terms
and SS stand for a year, month, day of month, hour, minute, and
l ฺ b
esecond value, respectively.
(ya TIME
• This data type can express time of day or a duration, and has a range of '-838:59:59' to
'838:59:59'. MySQL displays TIME values in HH:MM:SS format.
• TIME columns can be assigned using either strings or numbers. The storage used is 3
bytes.
YEAR
• The YEAR data type is assigned using the following syntax: YEAR [(2|4)].
• The default is the four-digit format, where the permitted values are 1901 to 2155, and
0000. MySQL retrieves YEAR values in YYYY format.
• In the two-digit format, the permitted values are 70 to 69, representing years from 1970
to 2069.

MySQL for Beginners 5 - 13


DATE
• The supported range is '1000-01-01' to '9999-12-31' and the storage used is 3 bytes. DATE
columns can be assigned using either strings or numbers. For example, the date January
9, 1998 can be represented as '1998-01-09'.
DATETIME
• This data type allows a date and time combination. The supported range is '1000-01-01
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

00:00:00' to '9999-12-31 23:59:59' and the storage used is 8 bytes. DATETIME columns
can be assigned using either strings or numbers.
TIMESTAMP
• This data type can be used to express datetime values ranging from '1970-01-01 00:00:00'
to partway through the year 2037. The storage used is 4 bytes with a display width fixed at
19 characters. To obtain the value as a number, add +0 to the timestamp column.
TIMESTAMP values are converted from the current time zone to UTC for storage, and
converted back from UTC to the current time zone for retrieval. (This occurs only for the
TIMESTAMP data type, and not for other types such as DATETIME.)
to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 5 - 14


Temporal Data Types Comparison
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Type Storage Required Range

DATE 3 bytes '1000-01-01' to '9999-12-31'

TIME 3 bytes '-838:59:59' to '838:59:59'

'1000-01-01 00:00:00' to
DATETIME 8 bytes
o
n nse t
9999-12-31 23:59:59'
1
TIMESTAMP 4 bytes '1970-01-01 00:00:00' to mid-year 3 %A2037 l i ce
l % C ble
I n c f e ra
1901 to 21552(for 0 YEAR(4)), a s
n 1970 to
YEAR 1 bytes %
llaYEAR(2))
2069 (for n- t r
d i n o
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
The temporalY data@types comparison
us chart in the slide lists the data types and their respective
l l a
b a di as the storage required and range.
attributes, such

l ฺ b o
( yae

MySQL for Beginners 5 - 15


Character String Data Types

A character string data type:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Represents a sequence of alphanumeric characters that


belong to a given character set
• Stores text or binary data
• Is implemented in nearly every programming language
• Supports character sets and collation
• Belongs to one of the following classes
to
– Text: True, unstructured character string data typesA1n
e n se
% ic
– Integer: Structured string types C3 le l l% erab
n c
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
a
CharacterYstring data
o differ
ctypes se in several ways:
@ u
a in a fixed or variable length format
llstored
• If data d i
is
b o
If
bthea maximum length that can be stored
elฺ

(ya • If the type supports unstructured string values
For storing character string data, MySQL provides the following numeric data type storage
classes:
• Text: Represents true character string data types. You can use this type for storing
unstructured, freely formatted character strings (provided that their length fits the defined
amount of space).
• Integer: Represents structured string types. These are called “structured” because the
values you can store in columns of these types must be constructed from a list of values
that you supply, thereby defining the data type.

MySQL for Beginners 5 - 16


Character String: Text Class Data Types

• Data types:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– CHAR: Fixed-length (static) string


– VARCHAR: Variable-length (dynamic) string
– TINYTEXT: Variable-length string
– TEXT: Variable-length string
– MEDIUMTEXT: Variable-length string
– LONGTEXT: Variable-length string
o
• Example: 1 n nse t
– world_innodb database, CountryLanguage table, 3 %A e lice
l % C bl
Language column:
I n c f e ra
Language CHAR(30) 20 tran s
%
lla30 allowed): n-
– Largest value output (uses d i
25; n o
Southern Slavic B oba as a ideฺ
Languages
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
CHAR: Y @ us
l l a
b a di
• Fixed-length: Stores the string using a fixed number of bytes
o
•ฺb It is always right-padded with spaces to the specified length when stored.
l
e
ya • The syntax for assigning a column to the CHAR data type is CHAR(<M>), where M stands
( for the maximum number of characters the CHAR value allows. If you give CHAR a
length of 10, but the text entered is only 3 characters long, 10 characters are always
stored. If you set the value of CHAR greater than the allowed maximum of 255, the
CREATE TABLE or ALTER TABLE statement in which this is done fails with an error.
Trailing spaces are removed when CHAR fields are retrieved.
VARCHAR:
• Variable-length: Stores the string value and string length together
• Unlike the CHAR data type, the VARCHAR data type can be used to store strings with
trailing spaces.

MySQL for Beginners 5 - 17


• The syntax for assigning a column to the VARCHAR data type is VARCHAR(<M>),
where M stands for the maximum number of characters the VARCHAR value allows. The
actual maximum length of a VARCHAR in MySQL is determined by the maximum row size
and the character set used. The amount of storage space that a VARCHAR uses depends
on the characters set as well as the number of characters in the string. In the event that a
VARCHAR is assigned with a max length of 10, but only 3 characters are entered, then 3
characters would be stored and only 1 byte would be used for length. VARCHAR retains
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

the trailing spaces when retrieved.


LONGTEXT:
• The maximum effective (permitted) length of LONGTEXT columns depends on the
configured maximum packet size in the client/server protocol and available storage.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 5 - 18


Character String: Text Class Data Types
Comparison
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Type Description Maximum Length

CHAR M characters 255 characters

VARCHAR L characters plus 1 or 2 bytes 65,535 characters


(subject to limitations)
TINYTEXT L + 1 bytes, where L < 28 255 bytes

o
TEXT
L + 2 bytes, where L < 216 65,535 bytes 1 n nse t
3 %A e lice
MEDIUMTEXT L + 3 bytes, where L < 2 16,777,215l%
C bl
ra
24
bytes
I n c f e
20 tran bytes s
LONGTEXT L + 4 bytes, where L < 2 a%
ll non-
32
4,294,967,295
d i
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y string
The character us comparison chart in the slide lists the data types and their
@ data types
l l a
respective
b a diattributes, such as the description and maximum length.
l ฺ o table in the slide, M represents the declared column length in characters for nonbinary
Inbthe
e string types and in bytes for binary string types. L represents the actual length in bytes of a
(ya given string value.

MySQL for Beginners 5 - 19


Character String: Integer Class Data Types

• Data types:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– ENUM: List of enumerated string values


– SET: List of zero or more string values
• ENUM example:
– world_innodb database, Country table, Continent column:
Continent ENUM('Asia', 'Europe', 'North America',
'Africa', 'Oceana', 'Antarctica', 'South America')
– Largest value output: to
A 1n ense
3% le lic
North America, Asia, Africa, Europe, South America,
Oceania, Antarctica C
l% erab
n c
• SET example:
2 0I ansf
– Allergy database, Symptomillcolumn: a% on-tr
Symptom SET('sneezing', o bad 'runny
s a n nose',
eฺ 'stuffy head',
'red eyes') a B a i d
n d r x ) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
ENUM: Y @ us
l l a
• An ENUM
b a di data type definition entails a list of strings assigned to a column during table
l ฺ b ocreation. A value for a particular ENUM data type must be one of the values specified in
( yae that list. An ENUM column can have a maximum of 65,535 distinct values. ENUM values
are represented internally as integers.
SET:
• A set can be thought of as any unordered list or collection of distinct things considered
as a whole. A single value of a SET data type is actually a list of values, and not a
single, atomic value chosen from a list of permitted values during table creation. A SET
column can have a maximum of 64 members. SET values are represented internally as
integers.
• Like the ENUM data type, the definition of a SET data type comprises a list of predefined
values. The difference with the ENUM data type is that a value for a particular SET data
type can be a list of any of these values.

MySQL for Beginners 5 - 20


Character Set and Collation Support

• Character set: A named encoded character repertoire


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– A character string belongs to a specific character set.


• Collation: A named collating sequence
– Defines character sort order
– Governs character and character string comparison
• Column definitions for string data types can specify a
character set or collation of the column. to
1 n nse
• Character set and collation example: A
% e lice
3
C bl
CREATE TABLE t c l % ra
I n s f e
( c1 VARCHAR(20) CHARACTER SET
% 20 tran utf8,
c2 TEXT CHARACTER SET llatin1
i l a non); -
d
oba as a ideฺ
COLLATE latin1_general_cs
B
ra x) h t Gu
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
CharacterYstrings@ us characteristics:
have the following
i l l a
• Every
b a dcharacter is associated with a particular symbol, depending on the character set.
o
•ฺb The positions in the character set dictate an implicit sorting order (binary).
l
e
ya • MySQL supports a number of alternative sorting orders called collations.
(
• Character string operations (such as comparison) are also affected by the collation.
• Characters with the same sorting position are effectively equal to one another.
In MySQL, there are some noteworthy issues affecting strings that must be addressed:
• Column definitions for many string data types can include a CHARACTER SET attribute
to specify the character set. (CHARSET is a synonym for CHARACTER SET.)
• The COLLATE attribute specifies a collation for the character set. As in the slide
example, the table definition creates a column named c1 that has a character set of
utf8 with the default collation for that character set, and a column named c2 that has a
character set of latin1 and a case-sensitive collation.
Note: The CHARACTER SET attribute applies to the CHAR and VARCHAR data types, the TEXT
data types, and ENUM and SET data types.

MySQL for Beginners 5 - 21


Binary String Data Types

• Similar to character string, but store a sequence of bytes,


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

instead of characters
• Can store binary values that represent data, such as:
– Compiled computer programs and applications
– Video and audio files
• Data types:
– BINARY: Fixed-length (static) binary byte strings to
– 1n ense
VARBINARY: Variable-length (dynamic) binary byteAstrings
– TINYBLOB: Variable-length binary byte strings C 3% le lic
n c l% erab
– 0I ansf
BLOB: Variable-length binary byte strings
2
– MEDIUMBLOB: Variable-lengthla
i l % nbyte
binary - tr strings
o
– badbinary
LONGBLOB: Variable-length a nbyte strings
o as ฺ
r a B
) h u ide
j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
Binary data Yatypes@ o thesestring data type due to their similarities in storage. Instead of
fallcunder u
i
characters,dbinarylla data types store bytes of data (binary digits [bits] grouped in eights
o
[octets]).
b ba
eIt lisฺ important that you understand that the textual representation of a binary string has usually
(ya nothing to do with the real meaning of the binary string. This is an important difference with
respect to character strings, for which textual representation usually corresponds exactly with
their meaning. Therefore, binary strings do not have an associated character set or collation.
Binary data types are suitable for storing images, sound, and PDF documents.
A BLOB is a collection of binary data stored as a single value in a database management
system. BLOBs are typically images, audio, or other multimedia objects, although sometimes
binary code is stored as a BLOB.

MySQL for Beginners 5 - 22


Binary String: Data Types Comparison
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Type Description Maximum Length

BINARY M bytes 255 characters

VARBINARY L bytes plus 1 or 2 bytes 65,535 characters

TINYBLOB L + 1 bytes 255 bytes

to
1n ense
BLOB
L + 2 bytes 65,535 bytes
A
% e lic
C 3
MEDIUMBLOB L + 3 bytes 16,777,215l%
c bytes
r a bl
2 0 In nsfe
LONGBLOB L + 4 bytes
i l l a%4,294,967,295
n - tra bytes
b a d a no
B o as i d eฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y string@data types
The binary uscomparison chart in the slide lists the data types and their
l l a
respective
b a diattributes, such as description and maximum length.
l ฺ o table in the slide, M represents the maximum length of a column and L represents the
Inbthe
e actual length of a given value, which may be 0 to M.
(ya

MySQL for Beginners 5 - 23


Quiz

Identify the best data type for the PartName_3NF table column
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

pID in the Inventory database example.


a. INT
b. CHAR
c. TINYINT
d. BLOB

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 5 - 24


Choosing Data Types

When designing the database, consider the following:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Use appropriate data type: For example, use a numeric


data type for a number (rather than a character string).
• Use appropriate integer length: For example, assign the
data type with the appropriate maximum size.
• Use appropriate character length: For example,
estimate the potential maximum size for variable length to
n e
strings. A1 ens
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Data storage @ co is aumajor
Yaand retrieval se issue in the tuning of the MySQL server and ensuring that
la
data integritydisilmaintained. As listed in the slide, the following issues must be taken into
account: o b a
l ฺ b
( yae • Use appropriate data type: An example of this is storing numbers as strings. “09” and
“9” are the same number but different strings and can lead not only to compromised
data, but to additional processes to convert the string to a numeric value before
performing calculations. Determine the data types (and parameters) needed for each
column. Depending on the storage engines you are using, use fixed versus variable size
data types.
• Use appropriate length: Consider the maximum size of the column before setting the
data type. For a person’s age, a TINYINT UNSIGNED data type (0 to 255) is
appropriate. Using an integer UNSIGNED data type (0 to 4,294,967,295) here would be
a waste of storage and affect performance over the lifetime of the database.
• Use appropriate character length: For columns that have the potential for holding
varying length of strings, take into account the minimum and maximum number of
characters allowed when selecting a data type. For example, a VARCHAR(64) is an
acceptable length for a person’s last name column.

MySQL for Beginners 5 - 25


Setting Data Types to NULL

NULL is a SQL keyword used to define data types that can:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Allow missing values


• Be an empty query result
• Be assessed during database design
• Have two categories:
Type Description
There is a value, but the precise value is to
Unknown
unknown at this time. A 1n ense
Not applicable If a value is specified, it would not be C 3% le lic
accurately representative. cl%
n f e r ab
2 0I ans
• Have several meanings, such as a% ovalue,”
“no -tr “unknown
i l l n
value,” “missing value,” “out
o badof srange,”a n “not ฺ applicable,”
and so on
r a B ha
) u ide
j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
Ya @ccan o evaluate
se to the null value. The null attribute is special because it
In SQL, expressions u
a that a value cannot be computed or is not known. The use of NULL can
llfact
representsd i
the
usually
b o bbeaassessed during database design, while assigning data types.
a e lฺ
( y

MySQL for Beginners 5 - 26


When to Use NULL

• During database design, in cases where column


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

information is not available, determine whether NULL


values can be allowed.
• NULL values can be changed in an existing table.
• Example from world_innodb:
– Country table contains countries with no value for this
column:
'LifeExpectancy' float(3,1) DEFAULT NULL to
– Allows undefined values without an error A 1n ense
C 3% le lic
• Use NOT NULL if a column does not allowl%
n c f e abensure
nulls,rto
integrity of the data. 2 0I ans
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
When to Y
a
Use NULL @ co use
d i
In the beginning
llastages of database design, when you are making a list of the data to be
o
included,
b bait becomes clear that some data may not be available for all columns. Examine
a e lฺ
these cases and determine whether or not to allow null values. Also, you can change this for
( y an existing table if a problem is detected due to occurrences of null values in the column.
In the example in the slide, the column has been set to DEFAULT NULL to allow undefined
values without an error. DEFAULT NULL is equivalent to NULL.
When Not to Use NULL
There are some cases when null values in a column are not recommended. The most
common case is when it is a primary key. Another example is any column that must have a
value for the database design to make sense. Use NOT NULL to minimize the processes that
have to be put into place to test for nulls or work with nulls.

MySQL for Beginners 5 - 27


Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Explain the use of data types in database design


• List the four MySQL data type categories
• Choose the correct data types for columns
• Describe the special considerations for using data types
• Explain the usage of NULL
to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 5 - 28


Practice 5-1 Overview:
Quiz–Data Types
This practice includes questions about MySQL-supported data
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

types.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 5 - 29


Practice 5-2 Overview:
Explain the Use of Data Types
This practice covers explaining the use of data types in a
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

world_innodb database table.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 5 - 30


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Database and Table Creation

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(
Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Use the CREATE DATABASE statement


• Use the CREATE TABLE statement to add tables to a
database
• Use the SHOW CREATE TABLE statement
• Describe and set column and table options
• Describe and use table indexing
n e to
• Use the SHOW INDEX statement A1 ens
• Describe table constraints C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
b o ba
l ฺ
(y ae

MySQL for Beginners 6 - 2


Creating a Database

• General syntax for creating a database:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

CREATE DATABASE <database_name> [<options>]

• CREATE SCHEMA is a synonym for CREATE DATABASE.


• Example:
CREATE DATABASE mydatabase
– The response looks like this: to
Query OK, 0 rows affected (0.00 sec) A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
a
Ydatabase o isscomplete,
cdesign e
When your
l l a @ u create the actual database by using the MySQL

b a di
statement CREATE DATABASE. It is important for you to name the database according to its

l ฺ b o
purpose. After the database is created, you can add the tables.

( yaeYou can add the IF NOT EXISTS option statement. An error occurs if the database exists
and you did not specify IF NOT EXISTS.
For more information about creating a database, see the MySQL Reference Manual at
http://dev.mysql.com/doc/refman/5.5/en/create-database.html.

MySQL for Beginners 6 - 3


MySQL Naming Conventions

• Database and table names are generally not


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

case-sensitive, but this depends on the file system.


• You cannot use certain characters, including ASCII(0),
ASCII(255), /, \, and .
• Names cannot have more than 64 characters.
• You can use reserved words and special characters in
quotation marks. o
1 n nse t
3 %A e lice
l % C bl
I n c f e ra
20 tran s
%
lla non-
d i
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
MySQL inYgeneral s
@does not uconsider names (databases and tables) to be case-sensitive.
l l a
i treat them as case-sensitive if the file system on which the database resides
However, itddoes
o
is itself b a
case-sensitive.
l ฺ b
( yaeTable names can be (or contain) reserved words as long as the name is quoted (such as a
table named 'my_table' or '$'), but this practice is discouraged.

MySQL for Beginners 6 - 4


Creating a Table

• General syntax for creating a table:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

CREATE TABLE <table_name> (


<column name> <column type> [<column options>]
,…,
[, <primary key definition>])

• Example:
CREATE TABLE CountryLanguage (
CountryCode CHAR(3) NOT NULL, n nse to
A 1
Language CHAR(30) NOT NULL,
3 % e lice
IsOfficial ENUM(‘True’,‘False’) NOT l % C bl
NULL DEFAULT
c r a
‘False’,
2 0 In nsfe
Percentage FLOAT(3,1) NOT % NULL, tra
d i
PRIMARY KEY(CountryCode, l l a
n o n-
Language)
); oba s a B ha eฺ
d r a x ) G uid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
Ya @structure
After the database co uissdesigned
e and the database has been created, you can add the
l l a
b a di You must use accurate assignment of data types and options, then you can
individual tables.
add the
l ฺ b o tables from the design plan to the database. Table and column options are covered

yae
later in this lesson.
( Creating tables is a complex topic due to the process of choosing how to create the table and
the syntax, which consists of many elements. The statement syntax shown in the slide
includes the column and table options.
A line-by-line description of the CREATE TABLE example:
1. Creates a table called CountryLanguage
"(" is the beginning of the table structure definition that ends with ")".
2. The column named CountryCode is assigned the data type of CHAR and maximum
length of 3 characters that cannot accept NULL. The comma at the end of the line
indicates that you are continuing to define columns, or set a primary key.
3. The column named Language is assigned the CHAR data type and a length of 30, also
with no NULLs.

MySQL for Beginners 6 - 5


4. The column named IsOffical is assigned the ENUM data type (with the value 'True' or
'False'). The addition of NOT NULL means that each row must contain one of the
specified values (as indicated in single quotation marks). If the field is not provided, it is set
to 'False' by the phrase DEFAULT 'False'.
5. The column named Percentage is assigned the FLOAT data type. It contains three digits,
including one to the right of the decimal point. This column cannot accept NULL.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

6. Defines the PRIMARY KEY, the type of key, and to what columns it applies. In this case, a
combination of both CountryCode and Language columns define a unique identifier for
each row.
7. ")" is the closing of the table structure definition. “;” means execute this statement (using
the MySQL command-line client) and create the CountryLanguage table.
Note: You can also use the CREATE TABLE statement to create temporary tables.
Temporary tables are covered in detail later in the course.
For more information about creating a table, see the MySQL Reference Manual at
http://dev.mysql.com/doc/refman/5.5/en/create-table.html. to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 6 - 6


Showing How a Table Was Created

• View the exact statement used to create a table.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example:
mysql> SHOW CREATE TABLE City\G
******************* 1. row ********************
Table: City
Create Table: CREATE TABLE `City` (
`ID` int(11) NOT NULL auto_increment,
`Name` char(35) NOT NULL default '', to
`CountryCode` char(3) NOT NULL default A 1n ense
'',
3%
'', le l
ic
`District` char(20) NOT NULL default C
n c f ab
l% er'0',
0I ans
`Population` int(11) NOT NULL default
PRIMARY KEY (`ID`) 2
% n-tr
i l l a
a
) ENGINE=InnoDB DEFAULT
b a no ฺ
d CHARSET=latin1
Bo sec) s
1 row in set (0.00
r de
a x) ha Gui
a d
n yฺm ent
e j
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
a
The SHOWYCREATE
o statement
cTABLE se produces a statement that can create a table with the
@ u
llaas the table specified. This can help you to understand the structure of a
d i
same properties
bacan also use it as a basis for the syntax to create a new table. For example, to
table.oYou
b
a e lฺ the CREATE TABLE statement used to create the City table, execute the statement
show
( y shown in the example in the slide.

MySQL for Beginners 6 - 7


Column Options

• Each table must have at least one column.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• You can add options to the CREATE TABLE statement,


such as:
– NULL – DEFAULT
– NOT NULL – AUTO_INCREMENT
• Example:
CREATE TABLE CountryLanguage ( to
CountryCode CHAR(3) NOT NULL, A 1n ense
Language CHAR(30) NOT NULL, C 3% le lic
n c l%DEFAULT
f e r ab 'F',
20I trans
IsOfficial ENUM('T', 'F') NOT NULL
Percentage FLOAT(3,1) NOT %
n-
NULL,
d i llaLanguage)
n o
oba as a ideฺ
PRIMARY KEY(CountryCode,
); B
ra x) h t Gu
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y TABLE
The CREATE s
@ columnuoptions modify how MySQL handles the associated column.
l l a
Some common
b a di column options:
• bo
NULL: Is the default option that allows storing of NULL values
l ฺ
( yae • NOT NULL
- Disallows NULL
- Saves response time and, in some cases, disk space
- Is a necessity for a PRIMARY KEY
- NULL and NOT NULL are mutually exclusive.
• DEFAULT <value>: If no value is supplied by the user, this specified value is stored.
• AUTO_INCREMENT
- A "running number" option for indexed columns
- Used for INTEGER data type columns only
- Using NULL, or not specifying a value for the column, causes an automatic insert
of the next available number in sequence
- Must be indexed
- Only one permitted per table
Note: Indexes are covered later in this lesson.

MySQL for Beginners 6 - 8


Table Options

• You can add options to the CREATE TABLE statement,


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

such as:
– ENGINE
– COMMENT
– DEFAULT CHARACTER SET
• Example:
CREATE TABLE CountryLanguage (
to
CountryCode CHAR(3) NOT NULL,
A 1n ense
Language CHAR(30) NOT NULL,
C 3% le lic
IsOfficial ENUM('T', 'F') NOT NULL
n c l%DEFAULT
f e r ab 'F',
Percentage FLOAT(3,1) NOT NULL, 2 0I ans
l l % n-tr
aLanguage)
PRIMARY KEY(CountryCode,
a i
d a no
o b
)ENGINE = InnoDB COMMENT ฺ
s 'ListseLanguage Spoken'
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya TABLE o options
ctable se modify how MySQL handles the entire table. Some
The CREATE
a @
lloptions: u
d
common table i
• bo ba = <storage_engine_name>: Indicates the storage engine to be used for
ENGINE
a e lฺ the table
( y • COMMENT: Up to 60 characters of free form text
• DEFAULT CHARACTER SET <character set>: Specifies the default character set
for the table

MySQL for Beginners 6 - 9


Table Indexing

• Original table data is not put in any specific order or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

location.
– Server must scan all data to find relevant rows.
• Indexes assist in finding rows quickly and easily.
– Only contain column information for locating rows
• Indexes are assigned when creating a table, or you can
add them later. to
1 n nse
• Composite indexes are created on multiple columns. A
% e lice
3
C bl
• “Key” is normally a synonym for “index.” c l % ra
I n s f e
% 20 tran
d i lla non-
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
When youYinsert a s the database server does not attempt to put the data in
@row into autable,
l l a
any particular
b a di location within the table. Instead, the server simply places the data in any
l ฺ b o
available location within the table. Tables can be very large, and as a table gets bigger,

yae
retrievals from it become slower. This is due to the fact that the location of the data is
( unknown, so the server must look at all the data to find the relevant rows.
An index (or key) in MySQL serves to assist in finding rows quickly, like an index at the back
of a technical manual. Database indexes are used to locate rows in a table. Instead of
containing all of the row data, an index contains only the columns used to locate the rows. It
also contains information describing where the rows are physically located. Usually, you
create all the indexes you need when you are creating tables.
You can create indexes on single columns or multiple columns (composite indexes). For
example, the phone number for an individual in a phone book can be used as a single column
index, whereas the last name and first name can be used to create a composite index.

MySQL for Beginners 6 - 10


MySQL Indexing

• Commonly used indexes:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– PRIMARY KEY: Only one allowed


– UNIQUE: Multiple allowed
• Indexes are optional and must be created by the user.
• Example:
CREATE TABLE CountryLanguage (
CountryCode CHAR(3) NOT NULL, to
Language CHAR(30) NOT NULL, A 1n ense
C
IsOfficial ENUM('T', 'F') NOT NULL DEFAULT e lic
3% l'F',
Percentage FLOAT(3,1) NOT NULL,ncl% fera
b
2 0I ans
l l a % n-tr
PRIMARY KEY(CountryCode, Language)
); d i no
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y are@
The following us used indexes:
the commonly
l l a
• PRIMARY
b a di KEY
l ฺ b o - Only one PRIMARY KEY is allowed per table.
e
(ya - It uniquely identifies a single row in the table.
- No NULL values are permitted.
-No duplicate values are permitted.
-If a duplicate value is INSERTed or UPDATEd, MySQL returns an error and the
attempted operation is not performed.
• UNIQUE
- The same rules as the PRIMARY KEY, with two exceptions:
Can have values stored as NULL
Can have multiple UNIQUE indexes in a table
- Each non-NULL value uniquely identifies a single row in a table.
For more information about how MySQL uses indexes, see the MySQL Reference
Manual at http://dev.mysql.com/doc/refman/5.5/en/mysql-indexes.html.

MySQL for Beginners 6 - 11


Showing the Table Indexes

• General syntax for displaying table indexes:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

SHOW INDEX FROM <table_name>


• Example:
mysql> SHOW INDEX FROM Country\G
******************** 1. row ********************
Table: Country
Non_unique: 0
Key_name: PRIMARY
to
Seq_in_index:
Column_name:
1
Code A 1n ense
Collation: A
C 3% le lic
Cardinality: 239
n c l% erab
Sub_part: NULL
2 0I ansf
Packed: NULL
i l l a% on-tr
bad s a n eฺ
Null:
Index_type: BTREE o
B ha
d r a x ) G uid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
a
The resultYof the SHOW@ coINDEX u e
sstatement example in the slide shows that there is a PRIMARY
l l a
index on the
b a diCode column of the Country table, and an index type of BTREE table. The
column shows the number of distinct values that exist in the table: 239 in this
l ฺ b o
Cardinality

yae
case.
( Note: Most indexes are stored in B-trees. Exceptions are indexes on spatial data types use
R-trees, and MEMORY tables also support hash indexes.
For more information about the SHOW INDEX statement, see the MySQL Reference Manual
at http://dev.mysql.com/doc/refman/5.5/en/show-index.html.

MySQL for Beginners 6 - 12


Table Constraints

• A constraint is a restriction placed on one or more column


values of a table to actively enforce integrity rules.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Constraints are implemented using indexes.


• Types of constraints:
– PRIMARY KEY
– FOREIGN KEY
– UNIQUE
n e to
• MySQL generates indexes to enforce the above A 1 en s
%
3 le l i c
constraints. C
n c l %
f e r ab
2 0I ans
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm x ) G
t All rights reserved.
l e ©a2012, Oracle
j e n
0A oฺuad s Stud
Copyright and/or its affiliates.

2
a el% corre e thi
Y is a restriction
A constraint @ us on one or more column values of a table to actively enforce
placed
l l a
b a di
integrity rules.

l ฺ b o are implemented using the following indexes:


Constraints

( yae • PRIMARY KEY: Defines the columns that guarantee uniqueness within a table
• FOREIGN KEY: Restricts the columns to contain only values that match those in another
table’s PRIMARY KEY or UNIQUE columns
• UNIQUE: The same as PRIMARY KEY except that the columns are allowed to be null-
able, and there may be multiple UNIQUE constraints in one table
For example, if the MySQL server allowed you to modify the world_innodb database by
changing the CountryCode value in the CountryLanguage table without changing the
corresponding CountryCode value in the City table, then you end up with rows that no
longer point to valid country records (known as orphaned rows). With constraints in place
(FOREIGN KEY, in this case), the server raises an error if an attempt is made to modify or
delete data that is referenced by other tables, or it propagates the changes to other tables for
you.
Note: Only the InnoDB storage engine supports FOREIGN KEY constraints. Other storage
engines ignore these constraints in table definitions.

MySQL for Beginners 6 - 13


Quiz

Which of the following SQL statements do you use to create a


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

database after completing a database design process?


a. SHOW CREATE DATABASE
b. CREATE TABLE
c. CREATE DATABASE

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 6 - 14


Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Use the CREATE DATABASE statement


• Use the CREATE TABLE statement to add tables to a
database
• Use the SHOW CREATE TABLE statement
• Describe and set column and table options
• Describe and use table indexing
n e to
• Use the SHOW INDEX statement A1 ens
• Describe table constraints C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
b o ba
l ฺ
(y ae

MySQL for Beginners 6 - 15


Practice 6-1 Overview:
Display Table Creation Information
This practice covers the following topics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Showing the creation SQL statement syntax used to create


the Country table from the world_innodb database
• Using the output from a SHOW TABLE CREATION
statement to create a new table
• Showing the indexes used in table creation

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 6 - 16


Practice 6-2 Overview:
Create a Database
This practice covers using your knowledge of database design
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

and creation to create the Pets database and its tables.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 6 - 17


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Basic Queries

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(
Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Retrieve database data by using the SELECT statement


• Use the SELECT statement clauses: FROM, DISTINCT,
WHERE, ORDER BY, LIMIT
• Troubleshoot problems using warning and error messages
• Describe and use SQL Modes to change interpretation of
SQL syntax
to
• 1n nse
Use the MySQL Workbench GUI tool to submit queries
3 %A e lice
l % C bl
I n c f e ra
20 tran s
%
lla non-
d i
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 7 - 2


SELECT Statement

• SELECT is the most commonly used DML command for


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

queries:
– Retrieves rows from tables in a database
– Returns rows as a “result set” in the form of a table
• General syntax:
SELECT [<clause options>] <column list>
o
[FROM <table_name>] [<other_clauses>]
1 n nse t
• column_list is a list of column names that make 3 %Aup l i
thece
l % C ble
result set.
I n c f e ra
0 an
2comma s
– Separate the items in the list with
i l l a on-tr separator (,).
% a

o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
In MySQL,
a
YSELECT @ cothe most
is u secommonly used data manipulation language (DML) statement.
The SELECT d i lla
statement forms a description of the data that is to be retrieved from the
o
database. b aIt does not specify exactly how the data is to be retrieved. The result returned by
l ฺ b
yae
the database server in response to a SELECT statement takes the form of a table, which is a
( collection of rows.
An expression that does not contain any column name is allowed in <column_list>.
For more information about the SELECT statement, see the MySQL Reference Manual at
http://dev.mysql.com/doc/refman/5.5/en/select.html.

MySQL for Beginners 7 - 3


SELECT Statement

A world_innodb database SELECT example:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT Name, Continent FROM Country;


+----------------------------------+---------------+
| Name | Continent |
+----------------------------------+---------------+
| Aruba | North America |
| Afghanistan | Asia |
| Angola | Africa |
| Anguilla | North America |
| Albania | Europe | to
...
A 1n ense
| Yemen | Asia |
C 3% le lic
| Yugoslavia | Europe |
n c l% erab
0I ansf
| South Africa | Africa |
| Zambia | Africa 2 |
| Zimbabwe i l l a% on-tr
| Africa |
bad s a n eฺ
+----------------------------------+---------------+
o
B ha
239 rows in set (0.02 sec)
r a uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya in the
The example @ co shows
slide u sea typical multiple-column query, which retrieves all the rows
i
in the NamedandllaContinent columns from the Country table. Queries can be performed on
o ba or all columns, on one or more tables.
one, multiple,
b
a e lฺ example, you can retrieve all the column data from the Country table, using (*):
For
( y
mysql> SELECT * FROM Country;
Note: The word “query” is most commonly used to describe a SELECT statement.

MySQL for Beginners 7 - 4


Using SELECT Clauses

Optional clauses can be used alone (or in combination) to


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

generate specific query results.


• Types of clauses:
– DISTINCT: Eliminates duplicate rows from the result set
– FROM: Specifies what tables to retrieve data from
– WHERE: Filters for specific rows
– ORDER BY: Sorts rows by specified order
– LIMIT: Limits the maximum number of rows in the result set to
A 1n ense
• Syntax example (with the order of the clauses 3fixed): % e lic
SELECT DISTINCT <values_to_return>l% C bl
c r a
FROM <table_name>
2 0In ansfe
WHERE <condition>
i l l a% on-tr
ORDER BY <how_to_sort>
o bad s a n eฺ
LIMIT <row_count>;
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
The syntaxYaexample @ cinothe slide
u seshows the correct order and usage of each of the listed
d i lla This statement performs the following:
optional clauses.
• o
b ba
Specifically selecting DISTINCT rows
l ฺ
( yae • FROM a named table
• WHERE some condition defines which rows to return
• Given a specific sorting order (ORDER BY)
• LIMITing the number of rows to be retrieved to some number
The order of the clauses is fixed. Therefore, if you do not keep them in their proper order, you
get a syntax error. No result set is returned.

MySQL for Beginners 7 - 5


Using SELECT with DISTINCT

• Removes duplicate rows, so every result set row is unique


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example of difference between SELECT without and with


DISTINCT:
mysql> SELECT Continent mysql> SELECT DISTINCT Continent
-> FROM Country; -> FROM Country;
+---------------+ +---------------+
| Continent | | Continent |
+---------------+ +---------------+
| Asia | | Asia |
to
1n ense
| Europe | | Europe |
| North America | compared to | North America | A
| Europe | | Africa |
C 3% le lic
| Africa | | Oceania |
n c l% erab
| Oceania | | South America |
2 0I ansf
a% on-tr
| Europe | | Antarctica |
i l l
bad s a n eฺ
| Africa | +---------------+
7 rows in set (0.00 sec)
...
o
B ha
239 rows in set (0.01 sec)
d r a x ) G uid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
An example co ubetween
Yaof the@difference se SELECT without and with DISTINCT for multiple
columns: dill
a
b o
mysql>ba SELECT Continent, Region FROM Country;
e ฺ
l+---------------+---------------------------+
( y a | Continent | Region |
+---------------+---------------------------+
| North America | Caribbean |
| Asia | Southern and Central Asia |
| Africa | Central Africa |
| North America | Caribbean |
...
| Oceania | Polynesia |
| Oceania | Polynesia |
...
| Africa | Eastern Africa |
| Africa | Eastern Africa |
+---------------+---------------------------+
239 rows in set (0.00 sec)

MySQL for Beginners 7 - 6


... compared to ...

mysql> SELECT DISTINCT Continent, Region FROM Country;


+---------------+---------------------------+
| Continent | Region |
+---------------+---------------------------+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| North America | Caribbean |


| Asia | Southern and Central Asia |
| Africa | Central Africa |
| Europe | Southern Europe |
| Asia | Middle East |
| South America | South America |
| Oceania | Polynesia |
| Antarctica | Antarctica |
| Oceania | Australia and New Zealand |
to
1n ense
| Europe | Western Europe |
| Africa | Eastern Africa | A
| Africa | Western Africa |
C 3% le lic
| Europe | Eastern Europe |
n c l% erab
| North America | Central America |
2 0I ansf
| North America | North America |
i l l a% on-tr
bad s a n eฺ
| Asia | Southeast Asia |
| Africa | Southern Africa o
B ha |
| Asia | Eastern Asia
d r a x )|
G uid
| Europe j a n yฺm ent
| Nordic Countries |
l e
| Africa
0A oฺuad s Stud
| Northern Africa
2
|

el% corre e thi


| Europe | Baltic Countries |
| Oceania a
Y @ | Melanesia |
| Oceania
l a us
| Micronesia
l |
| Europe
b a di | British Islands |

l ฺbo
| Oceania | Micronesia/Caribbean |
ya e+---------------+---------------------------+
( 25 rows in set (0.00 sec)

MySQL for Beginners 7 - 7


SELECT DISTINCT with NULL

• Treats NULL as the same value


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example of difference between DISTINCT without and


with NULL:
mysql> SELECT i, j mysql> SELECT DISTINCT i, j
-> FROM t; -> FROM t;
+-------------+ +-------------+
| i | j | | i | j |
+-------------+ +-------------+
compared to
| 1 | 2 | | 1 | 2 |
to
| 1 | NULL | | 1 | NULL |
A 1n ense
3% le lic
| 1 | NULL | +-------------+
+-------------+ C
l% erab
n c
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
As shownY
a co with
in the example,
@ u e
sDISTINCT, the NULL values in the second column are the
l l a
same, so the
b a disecond and third rows are identical. Adding DISTINCT to the query eliminates
one of
l ฺ b o as a duplicate.
them

( yae

MySQL for Beginners 7 - 8


SELECT with WHERE

Expressions in a WHERE clause can use the following types of


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

operators:
• Arithmetic: +, -, *, /, DIV, %
• Comparison: <, <=, =, <=>, <> or !=, >=, >,
BETWEEN
• Logical: AND, OR, XOR, NOT
• Additional options: IN, IS NULL, LIKE, () to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
YaOperators
Arithmetic @ co use
d i lla
Perform mathematical operations on column value expressions:
o b a
•ฺb + Addition
l
e
ya • - Subtraction
(
• * Multiplication
• / Division
• DIV Integer division
• % Modulo (remainder after division)

MySQL for Beginners 7 - 9


Comparison Operators
Compare column value expressions
• + Addition
• < Less than
• <= Less than or equal to
• = Equal to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• <=> Equal to (works even for NULL values)


• <> or != Not equal to
• >= Greater than or equal to
• > Greater than
• BETWEEN <value1> AND <value2> Indicate a range of values (inclusive)
Logical Operators
Combine Boolean expressions
o
• AND: Logical AND
1 n nse t
• OR: Logical OR
3 %A e lice
• XOR: Logical exclusive-OR
l % C bl
• NOT: Logical negation I n c f e ra
20 tran s
Additional options in a WHERE condition: %
a on-
• IN is equivalent to a list of comparisonsawithd illOR, n moreฺ readable and efficient.
o b s abut
• You can use IS NULL to check whether
r a ) ide(such as ... <column_name>
B ha avalue isunull
IS NULL).
j a nd yฺmx ent G
• The LIKE operator A le be used
can
tud matching (such as WHERE <value> LIKE
ad forSpattern
'<pattern>'). 2 0 ฺ u
o his
e l % r r e t (<expression>) to group parts of an expression.
Ya also@use
• You can coparentheses
s e
u to almost all types of value expressions such as literals,
• Operators
i l l acan be applied
o b ad function calls, and so on.
columns,
l•ฺb You can also combine several criteria with logical operators.
ya e
(

MySQL for Beginners 7 - 10


SELECT with WHERE

Example of WHERE with IN:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT ID, Name, District FROM City


-> WHERE Name IN ('New York', 'Rochester',
'Syracuse');
+------+-----------+----------+
| ID | Name | District |
+------+-----------+----------+
| 3793 | New York | New York |
| 3871 | Rochester | New York | to
| 3935 | Syracuse | New York | A 1n ense
+------+-----------+----------+
C 3% le lic
3 rows in set (0.00 sec)
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
The example Ya in the @ co demonstrates
slide u se the use of the IN expression in a WHERE condition to
l l a
i specified city names, along with their corresponding ID and District from
find a list ofdthe
the Cityo b a
table.
l ฺ b
( yae

MySQL for Beginners 7 - 11


SELECT with WHERE

Example of WHERE with AND and OR:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT Name, Continent FROM Country


-> WHERE GovernmentForm = 'Republic'
-> AND (Continent='North America'
-> OR Continent='Europe');
+---------------------+---------------+
| Name | Continent |
+---------------------+---------------+
| Albania | Europe | to
| Bulgaria | Europe | A 1n ense
| Costa Rica | North America |
C 3% le lic
...
n c l% erab
| Trinidad and Tobago | North America |
2 0I ansf
| Ukraine | Europe |
i l l a% on-tr
bad s a n eฺ
+---------------------+---------------+
35 rows in set (0.00 sec) o
B ha
d r a x ) G uid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
The exampleYa in the @ co uses
slide u e (with an OR expression) in a WHERE condition to list all
sAND
i lla America and Europe whose government is a Republic from the
countries indNorth
Country
b o batable.
a e lฺ
( y

MySQL for Beginners 7 - 12


SELECT with ORDER BY

• Returns output rows in a specific order


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example of ORDER BY:


mysql> SELECT Name FROM Country ORDER BY Name;
+----------------------------------------------+
| Name |
+----------------------------------------------+
| Afghanistan |
| Albania |
| Algeria |
to
| American Samoa |
A 1n ense
| Andorra |
C 3% le lic
| Angola |
n c l% erab
0I ansf
| Anguilla |
| Antarctica | 2
| Antigua and Barbuda i l l a% on-tr
|
| Argentina
o bad s a n eฺ |
...
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
o sthee rows in the SELECT statement to the client in no particular
a servercreturns
Ythe
By default,
l l @ u
a issue a query,
order. When
a d i
you the server is free to return the rows in any convenient order.
b o
This orderb can be affected by factors such as the order in which the rows are actually stored
l ฺ
yae
in the table, or which indexes are used to process the query. If you require output rows to be
( returned in a specific order, include an ORDER BY clause that indicates how to sort the
results.
The example in the slide sorts the names of the countries in alphabetical order by Name, from
the Country table.
In another example, this SELECT...ORDER BY statement adds onto the example in the
previous slide by ordering the results by country Name.

MySQL for Beginners 7 - 13


mysql> SELECT Name, Continent FROM Country
-> WHERE GovernmentForm = 'Republic'
-> AND (Continent='North America' OR Continent='Europe')
-> ORDER BY Name;
+---------------------+---------------+
| Name | Continent |
+---------------------+---------------+
| Albania | Europe |
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| Belarus | Europe |
| Bulgaria | Europe |
| Costa Rica | North America |
| Croatia | Europe |
| Czech Republic | Europe |
...
| Romania | Europe |
| San Marino | Europe |
| Slovakia | Europe |
| Slovenia | Europe |
to
| Trinidad and Tobago | North America |
A 1n ense
3% le lic
| Ukraine | Europe |
+---------------------+---------------+
C
l% erab
35 rows in set (0.00 sec)
n c
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 7 - 14


SELECT with ORDER BY with ASC and DESC

• Specify order with ASC and DESC


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– ASC: Ascending order (default)


– DESC: Descending order
• Example of ORDER BY with DESC:
mysql> SELECT Name FROM Country
-> ORDER BY Name DESC;
+----------------------+
| Name |
to
+----------------------+
A 1n ense
| Zimbabwe |
C 3% le lic
| Zambia |
n c l% erab
0I ansf
| Yugoslavia |
| Yemen | 2
| Western Sahara | i l l a% on-tr
| Wallis and Futuna |
o bad s a n eฺ
...
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ascending
a is the
Yorder @ codefault
u e order in an ORDER BY clause. You can specify explicitly
ssort
whether to d i
sortllaa column in ascending or descending order by using the ASC or DESC
o
keywords
b baafter the column names. Ascending means that the lowest value comes first.
a e lฺ
The statement in the example in the slide sorts the names of the countries in the Country
( y table in descending alphabetical order, with the highest value first.
Note: Functions, other mathematical operations, and any value expression can also be used
with ORDER BY.

MySQL for Beginners 7 - 15


SELECT with ORDER BY with ASC and DESC

• You can sort multiple columns simultaneously.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example of ORDER BY with both ASC and DESC:


mysql> SELECT Name, Continent FROM Country
-> ORDER BY Continent DESC, Name ASC;
+------------------+---------------+
| Name | Continent |
+------------------+---------------+
| Argentina | South America |
o
n nse t
| Bolivia | South America |
| Brazil | South America | 1
| Chile | South America |
3 %A e lice
...
l % C bl
| Uzbekistan | Asia |
I n c f e ra
| Vietnam | Asia | 20 tran s
| Yemen | Asia | %
lla non-
d i
oba as a ideฺ
+------------------+---------------+
239 rows in set (0.00 sec) B
ra x) h t Gu
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
The example Y in the usthe Continent names in the Country table in descending
@slide sorts
alphabetical l l a
i and the country Names in ascending order for the same Continent value.
b a
The Continent
dorder, column is of ENUM data type; therefore, it is ordered by number of placement
l ฺ b o
yae
in the list, and not alphabetically.
(

MySQL for Beginners 7 - 16


SELECT with LIMIT

• Specifies the number of rows to output in result set


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example of LIMIT:
mysql> SELECT Name FROM Country LIMIT 8;
+----------------------+
| Name |
+----------------------+
| Aruba |
| Afghanistan |
| Angola | to
| Anguilla | A 1n ense
| Albania |
C 3% le lic
| Andorra |
n c l% erab
| Netherlands Antilles |
2 0I ansf
| United Arab Emirates |la%
i l n - tr
a d a no
+----------------------+
b
Bo sec) ฺ
8 rows in set (0.00 as ide
ra x) h t Gu
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y returns
When a query @ manyurows, s but you want to see only a few of them, add a LIMIT
l l a
clause. This
b a disi a MySQL-exclusive option that enables you to limit the output of a query to the
l ฺ b o the result set.
first rows of

( yaeYou can use the LIMIT clause with either one or two arguments:
• ... LIMIT <row_count>
• ... LIMIT <skip_count>, <row_count>
You must represent each argument as an integer constant. You cannot use expressions, user
variables, and so forth.
When followed by a single integer <row_count>, LIMIT returns the first <row_count>
rows from the beginning of the result set.
As shown in the example in the slide, to select just the first 8 rows of the Name column from
the Country table, use LIMIT 8.

MySQL for Beginners 7 - 17


SELECT with LIMIT and Skip Count

• Specifies how many rows to skip before starting result set


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example of skipped LIMIT:


mysql> SELECT Name, Population FROM Country
-> LIMIT 20,8;
+------------------------+------------+
| Name | Population |
+------------------------+------------+
| Burkina Faso | 11937000 |
| Bangladesh | 129155000 |
to
| Bulgaria | 8190900 |
A 1n ense
| Bahrain | 617000 |
C 3% le lic
| Bahamas | 307000 |
n c l% erab
0I ansf
| Bosnia and Herzegovina | 3972000 |
2
a% on-tr
| Belarus | 10236000 |
| Belize | i
241000 |l l
bad s a n eฺ
+------------------------+------------+
o
8 rows in set (0.00
r a B sec)ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya by@
When followed cointegers,
two u se<skip_count> and <row_count>, LIMIT skips the first
d
<skip_count> i llarows from the beginning of the result set, and then returns the next
o ba rows.
<row_count>
b
a e lฺ
As shown in the example in the slide, to select the next 8 rows that come after the first 20
( y rows of the Name and Population columns, use LIMIT 20,8.

MySQL for Beginners 7 - 18


SELECT with LIMIT and ORDER BY

• Returns a specific number of rows in a specific order


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example:
mysql> SELECT Name FROM Country
-> ORDER BY Name LIMIT 8;
+----------------+
| Name |
+----------------+
| Afghanistan |
o
n nse t
| Albania |
| Algeria | 1
| American Samoa |
3 %A e lice
| Andorra |
l % C bl
| Angola | I n c f e ra
| Anguilla | 20 tran s
%
lla non-
| Antarctica |
d i
+----------------+
B oba as a ideฺ
n d ra x) h t Gu
8 rows in set (0.00 sec)

l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Use LIMIT Y in conjunction
@ usthe ORDER BY clause to put the rows in a particular order.
with
l l a
When you use
b a di them together, MySQL applies ORDER BY first and then LIMIT. One common
use for
l ฺ b o is to find the row containing the smallest or largest value in a particular column.
this

( yaeThe example in the slide combines the previous LIMIT example with ORDER BY to return the
first 8 rows of the Name column, in alphabetical order.

MySQL for Beginners 7 - 19


SELECT Usage Tips

• Treat table and database names as case-sensitive.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Use \c to abort a SQL statement, when issuing


statements using the command-line client.
• Use \G in place of ; to return results with each column in a
row, instead of as a table. Example:
mysql> SELECT Name, Continent FROM Country\G
*********************** 1. row ***********************
Name: Afghanistan to
Continent: Asia
A 1n ense
*********************** 2. row ***********************
C 3% le lic
l% erab
Name: Angola
Continent: Africa
n c
...
2 0I ansf
• Use * (all) cautiously, because i l l ait%
can n -
waste
tr resources and
b a d a no
give unpredictable results B o dueasto changes i d eฺ in columns.
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Use \G atYthe end@ us when the output is too wide for the screen.
of a statement
l l a
You can use
b a dithe clauses covered in this lesson with other statement types besides SELECT.
Some
l ฺ b oof them are covered later in the course.
( yaeUsing * (meaning all columns) can waste resources (time, disk space, and so on) and result
in potential maintenance problems. For example, if a table structure is changed, all SELECT
* queries on the table give different results.

MySQL for Beginners 7 - 20


Troubleshooting

• MySQL provides many resources for detecting errors and


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

warnings.
– Help to avoid future errors and warnings
• You can determine the cause and effect of a problem by
using an error or a warning message.
– Error message example:

error code
mysql> SELECT Name FROM City LIMIT;
SQLSTATE n e to
ERROR 1064 (42000): You have an error in % A1SQLicens
your
syntax; check the manual that corresponds C e l
3 to lyour
c % ratob use
lsyntax
MySQL server version for the right
I n
0error n s fe
near '' at line 1 2
% n-tra message
i l l a
The <row_count> valueais

b d missinga nofromฺthe above statement,
causing the error. Bo as uide
r a ) h
j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
There areY
a
@ co uofsethese messages:
three components
d i lla
• A MySQL-specific code
o b a
•ฺb A SQLSTATE error code. A SQLSTATE error code is defined by standard SQL and
l
ya e ODBC.
( • A text message that describes the problem
In the example in the slide, the message indicates that there is a syntax error in your
statement. It recommends that you check the manual.
The information string for multiple-row statements is a summary rather than a complete listing
of diagnostics.
There is a shortcut to look up any topic from the MySQL Reference Manual. Simply enter the
MySQL website URL followed by the keyword for which you want to search:
http://dev.mysql.com/<keyword >.

MySQL for Beginners 7 - 21


Troubleshooting

• Use the following statements for viewing warnings and


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

errors:
– SHOW WARNINGS: Displays any error, warning, and
messages that resulted from the last statement
– SHOW ERRORS: Displays only errors
• Refer the error code definitions in the MySQL Reference
Manual.
to
• For a shortcut to MySQL Reference Manual, use A1n
e n se
% ic
http://dev.mysql.com/<keyword>. C3 le l l% erab
n c fwarning,
• After you understand the cause of the
2 0Ierror nor
s
make any needed changes and
i l l % the
arun n - tra statement
SQL
again. b a d a no
B o as i d eฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Many MySQLY statements
@ generateus warnings and errors that might not be output for the user
l l a
b a di
to view automatically. Use the following statements to turn on error and warning output:
• bo SHOW WARNINGS: Shows nothing if the last statement that used a table did not generate
l ฺ
e any messages. It works only for the previous statement executed from the same
(ya connection. After you run another statement, even though the new statement does not
cause any errors or warnings, the earlier statement warnings will disappear. Warnings
do not show by default, therefore, you must turn it on if you want to see warnings.
• SHOW ERRORS: The list of messages is reset for each new statement that uses a table.
You can also find out what an error code means by using the perror utility, which prints a
description for a system error code or for a storage engine (table handler) error code:
shell> perror [options] errorcode
The MySQL Reference Manual can also be used to find the various error code definitions,
along with information about other types of common problems:
• Problems and common errors: http://dev.mysql.com/doc/refman/5.5/en/problems.html.
• Error codes/messages: http://dev.mysql.com/doc/refman/5.5/en/error-handling.html.

MySQL for Beginners 7 - 22


SQL Modes for Syntax Checking

You can customize the MySQL server’s operating mode for


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

each application, using SQL modes.


• SQL modes control server operations, such as:
– Which SQL syntax MySQL supports
– What kind of data validation checks it performs
• Customize server operating mode at run time:
SET [SESSION|GLOBAL] sql_mode='mode_value' to
A 1n ense
• View current global or session SQL mode value:
C 3% le lic
SELECT @@global.sql_mode
n c l% erab
0 I n s f
2
SELECT @@session.sql_mode %
i l l a on-tra
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
SQL mode
a
Ysettings @ comake
can u siteeasier to use MySQL in different environments and to use
d i
MySQL togetherllawith other database servers.
o
Youbcan
a the default SQL mode by starting mysqld with the --sql-mode =
bset
a e lฺ
‘mode_value’ option.
( y
Setting the GLOBAL variable requires the SUPER privilege and affects the operation of all
clients that connect from that time on. Setting the SESSION variable affects only the current
client. Any client can change its own session sql_mode value at any time.
For more information about SQL modes, see the MySQL Reference Manual:
http://dev.mysql.com/doc/refman/5.5/en/server-sql-mode.html.

MySQL for Beginners 7 - 23


Common SQL Modes

• ANSI: Change syntax and behavior to conform to standard


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

SQL.
• STRICT_TRANS_TABLES and STRICT_ALL_TABLES
enable “strict mode”:
– Transactional tables: Abort a statement if a value could not
be inserted as given.
– Nontransactional tables: Abort a statement if the value
occurs in a single-row statement or the first row of a multiple-
n nse to
row statement. A1 % i ce
• TRADITIONAL: Make MySQL behave like a C 3 le l
"traditional"
l % a b
SQL database system. 0 I nc sfer
% 2 tran
d i l non-
l a
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @mode can
The TRADITIONAL usbe described as "give an error instead of a warning," when
attempting d l l a
toi insert an incorrect value into a column.
Note: b a
oSTRICT_TRANS_TABLES affects nontransactional tables as well as transactional
l ฺ b
etables.
(ya

MySQL for Beginners 7 - 24


Quiz

Using SELECT with the DISTINCT clause returns a result set in


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

alphabetical order.
a. True
b. False

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 7 - 25


MySQL Workbench for SQL Development

• A GUI tool that includes the SQL Development module:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Used to query and analyze data on a MySQL server


• Download from the MySQL website
• Available for Windows, Linux, and Mac OS:
– Community and commercial versions

o
1 n nse t
3 %A e lice
l % C bl
I n c f e ra
20 tran s
%
lla non-
d i
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @providesuextensive
MySQL Workbench s facilities for working directly with SQL code. MySQL
i l
Workbenchdincludes l a the SQL Editor facility. Use SQL Editor to enter SQL statements directly.
You can o b a
enter statements, which can be saved to a file for later use. At any point, you can
l ฺ b
yae
also execute the statements that you have entered.
(

MySQL for Beginners 7 - 26


Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Retrieve database data using the SELECT statement


• Use the SELECT statement clauses: FROM, DISTINCT,
WHERE, ORDER BY, LIMIT
• Troubleshoot problems using warning and error messages
• Describe and use SQL modes to change interpretation of
SQL syntax
to
• 1n nse
Use the MySQL Workbench GUI tool to submit queries
3 %A e lice
l % C bl
I n c f e ra
20 tran s
%
lla non-
d i
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 7 - 27


Practice 7-1 Overview:
Perform Basic Queries
This practice covers performing basic queries on the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

world_innodb database tables by using the SELECT statement


from the command line.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 7 - 28


Practice 7-2 Overview:
Perform Basic Queries Using MySQL Workbench
This practice covers performing basic queries on the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

world_innodb database tables by using the SELECT statement


within the MySQL Workbench tool.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 7 - 29


Practice 7-3 Overview:
Perform Basic Queries on the Pets Database
This practice covers performing basic queries on the Pets
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

database tables by using the SELECT statement.


Note: You can use both the command line and the MySQL
Workbench tool.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 7 - 30


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Database and Table Maintenance

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(
Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Use the DROP DATABASE statement to delete a database


• Discuss the issues related to dropping a database
• Add a new table to a database by using SELECT
• Delete an entire table
• Add and remove columns of a table
• Modify table columns to
• Add and remove indexes and constraints A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 8 - 2


DROP DATABASE Statement

• Removes a database when it is no longer needed


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– The database can be empty or contain tables and data.


• Returns a row count, which is the number of tables deleted
• Must be used with extreme caution, because it does not
have the “undo” feature
• Examples:
to
DROP DATABASE my_database
A 1n ense
– Returns an error if the database does not exist C 3% le lic
n c l% erab
DROP DATABASE IF EXISTS my_database
2 0I ansf
l l a% does n - r
tnot
– Returns a warning if the database
a d i n o exist
B ob as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Use DROPYDATABASE @ whenuyou s are sure that the database is no longer needed.
l l a
di the DROP privilege for each database.
You mustahave
b
l ฺ
DROP b oDATABASE does not require the database to be empty. Before dropping the database,
( yaeMySQL removes any objects that it contains, such as tables, stored routines, and triggers.
A successful DROP DATABASE returns a row count that indicates the number of tables
dropped. (This actually is the number of .frm files removed, which amounts to the same
thing.) You can check your current databases to make sure that the database is removed by
using the SHOW DATABASES statement.
A database is represented by a directory under the data directory. The server deletes only
files and directories that it can identify as having been created by itself (such as .frm files). It
does not delete other files and directories. If you have put nontable files in that directory,
those files are not deleted by the DROP DATABASE statement. This results in a failure to
remove the database directory. In that case, the database continues to be listed by SHOW
DATABASES. To correct this problem, you can manually remove the database directory and
any files that it contains.
Any warning generated by DROP DATABASE can be displayed with the SHOW WARNINGS
statement.

MySQL for Beginners 8 - 3


Creating a New Table Using an Existing Table

• Create a table from the result of a SELECT statement on


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

an existing table (or tables).


– Use the SELECT statement with CREATE TABLE.
• View the original table using SHOW CREATE TABLE.
new table name
• Example:
mysql> CREATE TABLE EU_Countries
-> SELECT Name, Population * 1.5
to
-> AS NewPopulation
A 1n ense
-> FROM Country column alias 3%
e l ic
l C
% rabl
c fe
0Insec)
-> WHERE Continent = 'Europe';
2 n s
Query OK, 46 rows affected (0.42
Records: 46 Duplicates: i0 l l % n-tra0
aWarnings:
b a d a no
– The AS keyword is used B o to create
a s a new
i d eฺcolumn name.
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
A new tableY can be s values from one or more existing tables. This saves the
@createduusing
l l a
b a di a new table from scratch, when the data needed already exists. It is good
time in creating
practice
l ฺ b o familiarize yourself with an existing table before replicating it for a new table. You
to

yae
can use the SHOW CREATE TABLE statement, which is explicitly for reviewing the statement
( used for building a table.
You can also use multiple tables with joins, subqueries, or unions in the SELECT statement, or
even a SELECT statement without any table.
In the example in the slide, the AS keyword is used to create a new column name, based on a
calculation for a new population number that is used in the new table. Also, the query is
restricted to the countries where the continent is Europe.
Note: The tables created with CREATE TABLE...SELECT are based solely on the output of
the SELECT. Therefore, no table options are copied, including indexes and constraints. Also,
the newly created tables do not always end up with the data types you expect; particularly if
the column is created based on an expression.
For more information about using CREATE TABLE with SELECT, see the MySQL Reference
Manual at: http://dev.mysql.com/doc/refman/5.5/en/create-table-select.html.

MySQL for Beginners 8 - 4


Confirming the Creation of a New Table
• Show the new table: • Confirm the structure of the new
table:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SHOW TABLES;


+------------------------+
| Tables_in_world_innodb | mysql> DESCRIBE EU_Countries;
+---------------+---------------+------+-----+---------+-------+
+------------------------+ | Field | Type | Null | Key | Default | Extra |
| city | +---------------+---------------+------+-----+---------+-------+
... | Name | char(52) | NO | | | |
| NewPopulation | decimal(12,1) | NO | | 0.0 | |
| eu_countries | +---------------+---------------+------+-----+---------+-------+
+------------------------+

• Select data from the new table:


to
1n ense
mysql> SELECT * FROM EU_Countries;
+-------------------------------+---------------+
A
| Name | NewPopulation |
C 3% le lic
l% erab
+-------------------------------+---------------+
| Albania | 5101800.0 |
n c
| Andorra | 117000.0 |
2 0I ansf
| Austria | 12137700.0 |
i l l a% on-tr
bad s a n eฺ
...
| Yugoslavia |
o
15960000.0 |
B ha
+-------------------------------+---------------+
d r a x ) G uid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
Ya in@ o seSHOW TABLES, DESCRIBE, and SELECT statements confirm
thecslide, the
In the example u
a new EU_Countries
llthe
a i
the creationdof table and its contents.
b o b
l ฺ
( yae

MySQL for Beginners 8 - 5


Copying an Existing Table Structure

• Use CREATE TABLE with the LIKE keyword to create a


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

table with the same structure as another table:


– Indexes
– Column options
– No row data
• Example:
mysql> CREATE TABLE NewCity
to
-> LIKE City;
A 1n ense
Query OK, 0 rows affected (0.05 sec)
C 3% le lic
– The new table is empty; no row data isIncopied. cl% ferab
2 0 ans
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 8 - 6


Creating a Temporary Table
• Use CREATE TEMPORARY TABLE for a table that is:
– Kept only until the client disconnects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Visible only to the client that created it


– Not conflicting with other clients using same data
– Overriding an existing table until the temporary table is
dropped
• A great way to create a summary of specific table data.
• Example:
to
A
mysql> CREATE TEMPORARY TABLE EU_CountriesTemp1n ense
-> SELECT Name, Population * 1.5 3%
e l ic
l C
% rabl
-> AS NewPopulation c
-> FROM Country 2 0In ansfe
-> WHERE Continentlla
i =% n - tr
'Europe';
b a
Query OK, 46 rows affected no ฺ sec)
d a (0.42
Bo as0 Warnings:
Records: 46 Duplicates: ide
ra x) h t Gu
0
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
A temporary Y table@ us name as an existing permanent table causes the temporary
with the same
l l a
b a di the existing permanent table, until the temporary table (or the connection) is
table to override
dropped.
l ฺ b o This is true only within the same connection that created the temporary table.

( yaeIn the example in the slide, view the structure of the temporary table to confirm proper
creation:
mysql> DESC EU_CountriesTemp;
+---------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+---------------+------+-----+---------+-------+
| Name | char(52) | NO | | | |
| NewPopulation | decimal(12,1) | NO | | 0.0 | |
+---------------+---------------+------+-----+---------+-------+
2 rows in set (0.08 sec)
The LIKE keyword can also be used with CREATE TEMPORARY TABLE to create a
temporary table with the same structure as an existing table.

MySQL for Beginners 8 - 7


DROP TABLE Statement

• Removes one or more tables


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– The table can be empty or containing data.


• Must be used with extreme caution, because it does not
have the “undo” feature
• Examples:
DROP TABLE table1, table2, table3

– Returns an error if the table does not exist


to
DROP TABLE IF EXISTS table1 A 1n ense
C 3% le lic
– Returns a warning if the table does not exist
n c l% erab
DROP TEMPORARY TABLE table1_temp 2 0I ansf
i l l a% on-tr
– Removes only a temporary
o badtable a n ฺ
r a B has uide
a n d mx) nt G
A lej © 2012,
a d yฺ uditseaffiliates. All rights reserved.
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


Use DROPYTABLE @when youuares sure that the tables are no longer needed. All table data and
l l a
b a di are removed, so be careful with this statement!
the table definition

l ฺ o have the DROP privilege for each table.


Youbmust

( yaeUse IF EXISTS to prevent an error from occurring for tables that do not exist. A NOTE is
generated for each non-existent table when using IF EXISTS.
Using DROP TABLE with the TEMPORARY keyword has the following effects:
• Drops only TEMPORARY tables
• Does not end an ongoing transaction (Transactions are covered later in the course.)
• Does not check access rights (A TEMPORARY table is visible only to the client that
created it, so no check is necessary.)
Using TEMPORARY is a good way to ensure that you do not accidentally drop a permanent
table.

MySQL for Beginners 8 - 8


Adding a Table Column

• Use the ALTER TABLE statement with ADD COLUMN.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example:
mysql> ALTER TABLE EU_Countries
-> ADD COLUMN ID INT NOT NULL;
Query OK, 46 rows affected (0.11 sec)
Records: 46 Duplicates: 0 Warnings: 0

– Changes the structure as follows:


mysql> DESC EU_Countries; to
+---------------+---------------+------+-----+---------+-------+
A 1n ense
3% le lic
| Field | Type | Null | Key | Default | Extra |
+---------------+---------------+------+-----+---------+-------+
C
l% erab
| Name | char(52) | NO | | |
n c|
| NewPopulation | decimal(12,1) | NO
| ID | int(11) | NO
|
|
| 0.0
2
| NULL 0I ansf
|
|
|
|

l l a% on-tr
+---------------+---------------+------+-----+---------+-------+
i
bad s a n eฺ
3 rows in set (0.00 sec)
o
B column.
– ID is added as thealast
d r x ) ha Guid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
To add a Y
a
new column
@ co(or remove
u se a column), use the ALTER TABLE statement with the
i
appropriatedclausella that specifies the column’s definition. A column definition uses the same
syntax
b o bforaALTER TABLE as for CREATE TABLE. You can use ALTER TABLE to:
a e l•ฺ Add or remove a column
( y • Add or remove an index
• Change the specification of a current column
Column names within a table must be unique, so you cannot add a column with the same
name as one that already exists in the table. Also, column names are not case-sensitive, so if
the table already contains a column named ID, you cannot add a new column using any of
these names: ID, id, Id, or iD. They are all considered to be the same.

MySQL for Beginners 8 - 9


Adding a Table Column
• Adding a column to a table populates the rows with NULL,
the default value as specified, or the data type implicit
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

default.
• In a query, the column appears as empty or zero:
mysql> SELECT * FROM EU_Countries;
+-------------------------------+---------------+----+
| Name | NewPopulation | Id |
+-------------------------------+---------------+----+
| Albania | 5101800.0 | 0 |
to
| Andorra
| Austria
|
|
117000.0 | 0 |
12137700.0 | 0 | A 1n ense
| Belgium | 15358500.0 | 0 | C 3% le lic
| Bulgaria | 12286350.0 | 0 |
n c l% erab
| Bosnia and Herzegovina | 5958000.0 | 0 |2 0I ansf
| Belarus |
l l a% on-tr
15354000.0 | 0 |
i
| Switzerland |
o bad s a n eฺ
10740600.0 | 0 |
...
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
a
Note: TheYstatement
o populating
cfor se a table with data is covered in detail later in the course.
lla @ u
d i
b o ba
a e lฺ
( y

MySQL for Beginners 8 - 10


Removing a Table Column

• Use the ALTER TABLE statement with DROP COLUMN.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example:
mysql> ALTER TABLE EU_Countries
-> DROP COLUMN ID;
Query OK, 46 rows affected (0.11 sec)
Records: 46 Duplicates: 0 Warnings: 0

– Changes the structure as follows:


mysql> DESC EU_Countries; to
+---------------+---------------+------+-----+---------+-------+
A 1n ense
3% le lic
| Field | Type | Null | Key | Default | Extra |
+---------------+---------------+------+-----+---------+-------+
C
l% erab
| Name | char(52) | NO | | |
n c|
| NewPopulation | decimal(12,1) | NO | | 0.0
2 0I ansf
| |
+---------------+---------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
i l l a% on-tr
– The ID column has been
d an
baremoved.
B o a s i d eฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @
If a table contains us you cannot drop the column. If you intend to remove the
only one column,
l l a
b a di TABLE instead.
table, use DROP

l ฺ o not remove a column from a table if it is a primary key. You cannot remove a
Youbshould

( yaecolumn that is a foreign key from another table.


For more information about using ALTER TABLE, see the MySQL Reference Manual at:
http://dev.mysql.com/doc/refman/5.5/en/alter-table.html.

MySQL for Beginners 8 - 11


Modifying a Table Column

• Use the ALTER TABLE statement with MODIFY COLUMN.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example:
mysql> ALTER TABLE EU_Countries
-> MODIFY COLUMN NewPopulation
-> INT UNSIGNED NOT NULL;
Query OK, 46 rows affected (0.11 sec)
Records: 46 Duplicates: 0 Warnings: 0

– Changes the structure as follows: to


1 n s e
mysql> DESC EU_Countries;
% A icen
+---------------+------------------+------+-----+---------+-------+
| Null | Key | C
3
Default | le
l
| Field | Type

n c l% erab
+---------------+------------------+------+-----+---------+-------+
Extra |

| NO 0I| | sf
2 | ra|nNULL
| Name | char(52) | |
| NewPopulation | int(10) unsigned | NO
i l l a% on-t | |

bad s a n eฺ
+---------------+------------------+------+-----+---------+-------+
2 rows in set (0.06 sec)
o
B beenhachanged
– NewPopulationrahas
d x ) G uidto the INT data type.
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
The exampleYa in the @ co shows
slide u sehow you can change the NewPopulation column’s data
i
type from DECIMAL
d lla to INT, to restrict the column value to whole numbers. You can also make
b o ba column to disallow negative values.
the UNSIGNED

If lyou also want to disallow NULL in the column, you must include the NOT NULL attribute in
e
( y a
the column definition for MODIFY COLUMN, even if you originally defined the column with NOT
NULL. This is true for other column attributes as well. If you do not specify them explicitly, the
new definition does not carry them over from the old definition.
You cannot modify a column from a table if it is a primary key and if a foreign key from
another table references the column.

MySQL for Beginners 8 - 12


Modifying a Table Column: Row Changes

The previous ALTER TABLE...MODIFY COLUMN statement


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

example changes the row contents of the table as follows:

mysql> SELECT * FROM EU_Countries;


+-------------------------------+---------------+
| Name | NewPopulation |
+-------------------------------+---------------+
| Albania | 5101800 |
to
1n ense
| Andorra | 117000 |
| Austria | 12137700 | A
| Belgium | 15358500 |
C 3% le lic
| Bulgaria | 12286350 |
n c l% erab
| Bosnia and Herzegovina | 5958000 |
2 0I ansf
| Belarus |
l a% on-tr
15354000 |
i l
bad s a n eฺ
| Switzerland | 10740600 |
o
B ha uid
...
d r a x ) G
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
a
Note: TheYstatement
o populating
cfor se a table with data is covered in detail later in the course.
@ u
la be added using CREATE TABLE can be changed using ALTER TABLE.
Anythinga d
thatilcan
For
l ฺ b ob information about using ALTER TABLE, see the MySQL Reference Manual at:
more
( yaehttp://dev.mysql.com/doc/refman/5.5/en/alter-table.html.

MySQL for Beginners 8 - 13


Adding Indexes and Constraints

• Use the ALTER TABLE statement with ADD options to add


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

indexes and constraints to columns.


• General syntax:
ALTER TABLE table_name ADD INDEX [index_name]
(index_columns)

ALTER TABLE table_name ADD UNIQUE [index_name]


(index_columns)
to
ALTER TABLE table_name ADD PRIMARY KEY
A 1n ense
(index_columns) 3% lic C ble
c l % ra
I n s f e
% 20 tran
d i lla non-
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y in an
As mentioned us you can create tables with different types of indexes and
@earlier lesson,
l l a
i can also add the indexes and constraints to existing tables by using ALTER
constraints.dYou
TABLE. o b a
l ฺ b
( yaeThe index name is optional.

MySQL for Beginners 8 - 14


Adding a Column Index

• Use the ALTER TABLE statement with ADD INDEX.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example:
mysql> ALTER TABLE NewCity
-> ADD INDEX Pop (Population);
Query OK, 0 rows affected (0.22 sec)
Records: 0 Duplicates: 0 Warnings: 0
– Adds the index Pop for the Population column
to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 8 - 15


Adding a Column Index

• Confirm the change by using SHOW CREATE TABLE:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SHOW CREATE TABLE NewCity\G


******************* 1. row *******************
Table: City
Create Table: CREATE TABLE 'city' (
'ID' int(11) NOT NULL auto_increment,
'Name' char(35) NOT NULL default '',
'CountryCode' char(3) NOT NULL default '',
to
'District' char(20) NOT NULL default '',
A 1n ense
'Population' int(11) NOT NULL default '0',
C 3% le lic
PRIMARY KEY ('ID'),
n c l% erab
KEY `CountryCode` (`CountryCode`), 2 0I ansf
KEY 'Pop' ('Population')illa
% n-tr
b a d a no
) ENGINE=InnoDB DEFAULT
B o aCHARSET=latin1
s i d eฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 8 - 16


Dropping a Column Index

• Use the ALTER TABLE statement with DROP INDEX.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example:
mysql> ALTER TABLE NewCity DROP INDEX Pop;
Query OK, 0 rows affected (0.22 sec)
Records: 0 Duplicates: 0 Warnings: 0
– Removes the Pop index

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya in@ o se the change by using SHOW CREATE TABLE:
thecslide, confirm
In the example
l l a u
i
ad SHOW CREATE TABLE NewCity\G
mysql>
o b
elฺb
*************************** 1. row ***************************
(ya Table: NewCity
Create Table: CREATE TABLE `newcity` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` char(35) NOT NULL DEFAULT '',
`CountryCode` char(3) NOT NULL DEFAULT '',
`District` char(20) NOT NULL DEFAULT '',
`Population` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`),
KEY `CountryCode` (`CountryCode`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.08 sec)
You can remove constraints exactly the same way as indexes. Drop the constraint by column,
as in the following example:
ALTER TABLE City DROP FOREIGN KEY CountryCode;

MySQL for Beginners 8 - 17


Quiz

When you add a new column to a table by using ALTER


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

TABLE...ADD COLUMN, it adds the new column and also


populates it with data.
a. True
b. False

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 8 - 18


Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Use the DROP DATABASE statement to delete a database


• Discuss the issues related to dropping a database
• Add a new table to a database by using SELECT
• Delete an entire table
• Add and remove columns of a table
• Modify table columns to
• Add and remove indexes and constraints A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 8 - 19


Practice 8-1 Overview:
Remove a Database
This practice covers dropping an unneeded database.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 8 - 20


Practice 8-2 Overview:
Create a New Table and Remove a Table
This practice covers the following topics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Creating a table from an existing table


• Removing an entire table, including its data

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 8 - 21


Practice 8-3 Overview:
Alter Table Columns
This practice covers the following topics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Modifying the data type of a table column


• Adding a new column to a table

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 8 - 22


Practice 8-4 Overview:
Modify Table Indexes and Constraints
This practice covers the following topics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Adding an index to a table


• Dropping an index from a table
• Adding a primary key constraint to a table

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 8 - 23


Practice 8-5 Overview:
Further Practice
This practice covers the following topics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Creating a new table


• Adding, modifying, and removing column indexes and
constraints
• Removing the new table

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 8 - 24


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Table Data Manipulation

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(
Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Delete and modify table data


• Add new data to a table by using the INSERT and
REPLACE statements
• Modify data in a table by using the UPDATE statement
• Remove table rows by using the DELETE statement

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 9 - 2


Manipulation of Table Row Data

• It is common for databases to require modification:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– This is due to changes in data usage situations.


– Row data can be inserted, updated, replaced, or deleted.
• You must handle database manipulation carefully by
following safety tips:
– Administrators must restrict access to required users only.
– Keep up-to-date backups.
to
– Make ad hoc backups as needed. A 1n ense
– Set the “safe updates” option. C 3% le lic
c % rab
lrow
– Always think in terms of rows. (The entire n fe
0I ansassociated
2
with the data is affected.)
i l l a% on-tr
bad returns
– Verify that the WHERE criteria
o as a n the right rows.
eฺ
B
ra x) h t Gu i d
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @
Data manipulation us Take the following precautions with your data:
can be unsafe.
l l a
• Do a
b digrant users (including yourself) more permissions than required. For example, if
not
l ฺ b oyou are running some ad hoc queries on a database for the finance department, do not
e use the MySQL root account. Instead, create a user who has permission to run only
(ya the needed SELECT queries and then log in as the user.
• Keep daily backups of the data stored in MySQL.
• Always make a backup before you make any major changes, or when using unfamiliar
features.
• For beginners, a useful startup option is the safe updates option. It can be turned on
with the command-line client option --safe-updates, or by issuing SET
SQL_SAFE_UPDATES=1. It is helpful for cases when you might have issued a DELETE
FROM tbl_name statement but forgotten the WHERE clause. Normally, such a
statement deletes all rows from the table. With this option, you can delete rows only by
specifying the key values that identify them. This helps prevent accidents.
• Test queries and updates on a test table before running them on the real table.
• Execute a SELECT statement with the same WHERE clause to verify that the right results
are returned, before running a DELETE or an UPDATE statement.

MySQL for Beginners 9 - 3


INSERT Statement

• After creating a table, you can populate it with row data.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• General syntax includes the INTO clause:


INSERT INTO table_name (<column_list>)
VALUES (<value_list>)

• Example of inserting a single row:


INSERT INTO CountryLanguage (CountryCode,
Language, Percentage)
to
VALUES ('ALB', 'Chinese', 20);
A 1n ense
– The content of the new row: C 3% le lic
n c l% erab
+-------------+------------+------------+------------+
0I | Percentage
n s f |
| CountryCode | Language | IsOfficial
2
i l l a% on-tra
+-------------+------------+------------+------------+
...
| Chinese ba| F
d a n | 20.0
| ALB
B o s e ฺ |
...
d r a x) ha Guid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
The syntaxYafor INSERT
@ cousesuseparate
se column and value lists following the name of the table
i a the single record. The number of columns and values must be the same.
lladd
d
into which you
ba example in the slide, you add Chinese as a language for Albania, with a
In the
lฺ b oINSERT
y a e
percentage of 20, and the default F (false) for the IsOfficial column is acceptable
( because it is not the official language of the country.
In the result for the example in the slide, the false (F) value for the IsOfficial column is the
default value, which is used in the absence of a specific assignment.

MySQL for Beginners 9 - 4


Using INSERT for Multiple Rows

• Create multiple new rows in a table.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example:
INSERT INTO CountryLanguage (CountryCode, Language)
VALUES ('GRL', 'MySQL'), 1st row
('FJI', 'MySQL'), 2nd row
('BEL', 'MySQL'); 3rd row
– The content of the new row:
to
1n ense
+-------------+----------+------------+------------+
| CountryCode | Language | IsOfficial | Percentage | A
+-------------+----------+------------+------------+
C 3% le lic
| BEL | MySQL | F | 0.0 |
n c l% erab
0I ansf
| FJI | MySQL | F | 0.0 |
| GRL | MySQL | F | 0.0 |
2
l a% on-tr
+-------------+----------+------------+------------+
i l
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya example
In the INSERT @ co in the
u e you add MySQL as a language for Greenland, Fiji, and
sslide,
i lla you do not want to give it a percentage, and the default F (false) for the
Belgium. However,
d
o ba column is acceptable. The row data for each of the three rows is enclosed in
IsOfficial
b
a e lฺ
parentheses.
( y The result for the example in the slide is achieved with the following query:
SELECT * FROM CountryLanguage
WHERE CountryCode IN ('GRL', 'FJI', 'BEL')
AND LANGUAGE = 'MYSQL';
In the example result in the slide, the F (false) value for the IsOfficial column is the
default value, which is used in the absence of a specific assignment.
Note: You must enclose all column values in single quotation marks (for string and temporal
data types) in the INSERT statement.

MySQL for Beginners 9 - 5


NULL condition with INSERT

If values are not specified and columns have no default value:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Sets to NULL if column accepts NULL values


• Sets to implicit default for the column data type if it does
not accept NULL
• AUTO_INCREMENT columns automatically generate the
next sequence number

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 9 - 6


REPLACE Statement

• Performs the same as INSERT:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Except when an old row in the table has the same value as a
new row for a PRIMARY KEY or UNIQUE constraint. In that
case, the old row is deleted before the new row is inserted.
• REPLACE is a MySQL extension to the SQL standard.
• General syntax:
REPLACE INTO table_name (<column_list>)
to
VALUES (<value_list>)
A 1n ense
• Example: C 3% le lic
n c l% erab
REPLACE INTO CountryLanguage (CountryCode,
0 I n s f
2
Language, Percentage)
i l l a% on-tra
VALUES ('ALB', 'Albaniana',
o bad s a n 78.1); eฺ
B
ra x) h t Gu a i d
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Unless the Ytable has us KEY or a UNIQUE constraint, using a REPLACE statement
@ a PRIMARY
l l a
b a di It becomes equivalent to INSERT, because there is no index to be used to
makes no sense.

l ฺ b o
determine whether a new row duplicates another.

( yaeValues for all columns are taken from the values specified in the REPLACE statement. Any
missing columns are set to their default values, just as happens for INSERT. You cannot refer
to values from the current row and use them in the new row.
In the example in the slide, you are replacing the current Albaniana language percentage in
the CountryLanguage table, to correct for the change that was made earlier when Chinese
language was added. The content of the row is the following:

mysql> SELECT * FROM CountryLanguage WHERE CountryCode = 'ALB';


+-------------+-----------+------------+------------+
| CountryCode | Language | IsOfficial | Percentage |
+-------------+-----------+------------+------------+
| ALB | Albaniana | F | 78.1 |
| ALB | Chinese | F | 20.0 |
| ALB | Greek | F | 1.8 |
| ALB | Macedonian| F | 0.1 |
+-------------+-----------+------------+------------+

MySQL for Beginners 9 - 7


REPLACE Results

Example:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Query OK, 2 rows affected (0.06 sec)

• Returns a count to indicate the number of rows affected


– This count is the sum of the rows deleted and inserted.
– Count of 1: A row was inserted and no rows were deleted.
– Count greater than 1: One or more old rows were deleted
before the new row was inserted.
to
• 1n ense
Row count makes it easy to determine whether REPLACE
A
3%rows. c
only added a row or whether it also replacedCany e li % rabl
c l
2 0In ansfe
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Yafor a@
It is possible co rowutosereplace more than one old row if the table contains multiple
single
d i lla and the new row duplicates values for different old rows in different unique
unique constraints
b o ba
constraints.
elฺ
(ya

MySQL for Beginners 9 - 8


REPLACE Algorithm

MySQL performs the following algorithmic steps for REPLACE:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

1. Tries to insert the new row into the table


2. When insertion fails because a duplicate-key error occurs
(for a primary key or unique constraint), deletes the
conflicting row that has the duplicate key value from the
table
3. Tries again to insert the new row into the table to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Caution:Y
a has
If a table@ comoreuthan
se one constraint (unique or primary key), replacing one row
can actuallyd i lla to the deletion of several rows, if there are conflicts on more than one
lead
o ba
constraint.
b
a e lฺ main difference between REPLACE and INSERT is that INSERT only adds new data,
The
( y whereas REPLACE can also change existing data.
To use REPLACE, you must have both the INSERT and DELETE privileges for the table.

MySQL for Beginners 9 - 9


Quiz

The only difference between using INSERT and REPLACE is


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

that REPLACE always deletes a row before inserting a new


one.
a. True
b. False

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 9 - 10


UPDATE Statement

• Modifies contents of existing rows


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Is used with the SET clause for column assignments


• General syntax:
UPDATE table_name SET column=expression
[,column=expression,...]
[WHERE condition] [other_clauses]

• Example: to
A 1n ense
mysql> UPDATE Country
C 3% le lic
-> SET Population = Populationl% * 2, ab
Region = 'Dolphin0Country' I n c
s f er
->
% 2 tran
-> WHERE Code = 'SWE';
d i l non-
l a
Query OK, 1 row affected
o ba s (0.03 a e
sec)

Rows matched: 1 Changed:
r B
a x) h Gu a 1 i d
Warnings: 0
a d
n yฺm ent
e j
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
The example Ya in the @ co demonstrates
slide u se how you can update the Country database by
l l a
changing the
country b a diPopulation
Sweden (code
column calculation and the Region to Dolphin Country for the
The results show one row affected, one row matched
l ฺ b o 'SWE').

yae
(selected by the WHERE clause), and one row changed.
(

MySQL for Beginners 9 - 11


UPDATE Statement Ordering

• There is no guarantee about the order in which rows are


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

updated, which can result in errors:


mysql> UPDATE City SET ID = ID+1;
ERROR 1062 (23000): Duplicate entry '2' for key 'PRIMARY'

• Use ORDER BY to control the order:


mysql> UPDATE City SET ID = ID+1
-> ORDER BY ID DESC;
to
1n ense
Query OK, 4079 rows affected (0.13 sec)
Rows matched: 4079 Changed: 4079 Warnings: 0
A
– The content of the new row: C 3% le lic
n c l% erab
0 I
+----+----------------+-------------+---------------+------------+
|s
n f
| ID | Name | CountryCode | District
2 r a Population |

i l l a| %
Kabol n-
o
t | 1780000 |
+----+----------------+-------------+---------------+------------+

bad s|| aQandahar


| 2 | Kabul | AFG
| 3 | Qandahar | AFG n ฺ || 237500 |
| 4 | Herat
B
| AFGo a Herat
i d e 186800 |
... a
dr mx) nt G h u
a n yฺ uditseaffiliates. All rights reserved.
A lej © 2012,
a d
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


To solve theY problem s UPDATE in the slide that causes an error, add an ORDER BY
@ of the ufirst
l l a
b a di the row updates to occur in a particular order, as shown in the second
clause to cause
UPDATE.
l ฺ b o
( yaeThe results shown in the slide are a result of the following query:
mysql> SELECT * FROM City ORDER BY ID;
+------+----------------+-------------+---------------+------------+
| ID | Name | CountryCode | District | Population |
+------+----------------+-------------+---------------+------------+
| 2 | Kabul | AFG | Kabol | 1780000 |
| 3 | Qandahar | AFG | Qandahar | 237500 |
| 4 | Herat | AFG | Herat | 186800 |
| 5 | Mazar-e-Sharif | AFG | Balkh | 127800 |
| 6 | Amsterdam | NLD | Noord-Holland | 731200 |
...
| 4079 | Nablus | PSE | Nablus | 100231 |
| 4080 | Rafah | PSE | Rafah | 92020 |
+------+----------------+-------------+---------------+------------+
4079 rows in set (0.02 sec)
Note: The IDs start at the number 2, due to the update.

MySQL for Beginners 9 - 12


UPDATE with LIMIT

• Use LIMIT to control the number of rows updated:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> UPDATE City SET ID = ID-1 LIMIT 1;


– The content of the row:
+----+----------------+-------------+---------------+------------+
| ID | Name | CountryCode | District | Population |
+----+----------------+-------------+---------------+------------+
| 1 | Kabul | AFG | Kabol | 1780000 |
| 3 | Qandahar | AFG | Qandahar | 237500 |
| 4 | Herat | AFG | Herat | 186800 |
...

— Note that only the first ID was affected by the update, whereas
n e to
the others kept their existing values. A1 ens
C 3% le lic
• UPDATE can include ORDER BY used with
n c l%LIMIT.
f e r ab
2 0I ans
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya in the
The example @ co shows
slide u sethe statement to use if you really want Kabul to have the ID
number 1 in d i llaCity table, even though the last update changed it to 2, but you do not care
the
baother cities.
aboutothe
b
a e lฺ
Note: It is bad practice to update a primary key value.
( y

MySQL for Beginners 9 - 13


When UPDATE Has No Effect

UPDATE has no effect under the following conditions:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• When it matches no rows for updating:


– Due to an empty table
– If no rows match the WHERE clause
• When it does not actually change any column values:
– When the value given is the same as the existing value
to
– If there is no existing row in the table that contains the1n
A e n se
specified key values 3% lic C ble
c l % ra
I n s f e
% 20 tran
d i lla non-
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 9 - 14


Difference Between UPDATE and REPLACE

When handling rows with unique key values, UPDATE and


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

REPLACE are not equivalent:

UPDATE REPLACE

Does nothing if an existing row with Does not require an existing row with the
specified key values does not exist key values, and adds one if none exists

to
Can change some columns in an existing
row while leaving others unchanged
Entirely discards the existing row*
A 1n ense
C 3% le lic
n c l% erab
* REPLACE can leave some columns unchanged when2 the
f
0Inew arownsspecifies the same
%
lla ncontains.
values in those columns that the existing row currently n- t r
d i o
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
l l a
b a di
l ฺ b o
e
(ya

MySQL for Beginners 9 - 15


DELETE Statement

• Use DELETE to remove whole, specified table rows instead


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

of individual columns
• General syntax:
DELETE FROM table_name
[WHERE condition]
[ORDER BY ...]
[LIMIT row_count]
to
– Use WHERE to indicate which rows to remove.
A 1n ense
• Indicate table name only to remove all table C 3% le lic
rows:
n c l% erab
DELETE FROM my_table
2 0I ansf
• Use DELETE with extreme caution, i l l a% because n - tr it does not
b a d a no
have the “undo” feature. B o as i d eฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
The DELETE Y result s number of rows affected, which can be zero (0) if the
@indicatesuthe
l l a
statement did
b a di not cause a change to be made.
l ฺ b o
( yae

MySQL for Beginners 9 - 16


DELETE with ORDER BY and LIMIT

• Control the order and count of the DELETE by using


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

ORDER BY and LIMIT:


• Descending order example:
DELETE FROM CountryLanguage
WHERE Language = 'MySQL'
ORDER BY CountryCode
DESC LIMIT 1;
– The content of the row: n nse to
A 1
+-------------+----------+------------+------------+
3 % l i ce
| CountryCode | Language | IsOfficial | Percentage
l % C ble |
+-------------+----------+------------+------------+
I n c f e ra
| BEL | MySQL | F 20 tra||n s 0.0 |
| la F% -
| FJI | MySQL
| MySQL ad| F i l o n 0.0 |
Removed | GRL
o b s a n eฺ | 0.0 |
B ha uid
+-------------+----------+------------+------------+
r a
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
LIMIT can Yabe useful @ cifoyou want
u seto remove only some instances of a given set of rows.
The example d i linlathe slide assumes that you want to remove only one of the MySQL language
records
b o binathe CountryLanguage table, using CountryCode as the criteria, starting
a e lฺ
alphabetically from the bottom. The following SELECT statement shows what records existed
( y before the DELETE:
mysql> SELECT * FROM CountryLanguage WHERE Language = 'MySQL';
+-------------+----------+------------+------------+
| CountryCode | Language | IsOfficial | Percentage |
+-------------+----------+------------+------------+
| BEL | MySQL | F | 0.0 |
| FJI | MySQL | F | 0.0 |
| GRL | MySQL | F | 0.0 |
+-------------+----------+------------+------------+
3 rows in set (0.01 sec)
If you do not use the ORDER BY clause in conjunction with LIMIT, MySQL cannot guarantee
which one of the items will be deleted.

MySQL for Beginners 9 - 17


DELETE with ORDER BY and LIMIT

• Ascending order example:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

DELETE FROM CountryLanguage


WHERE Language = 'MySQL'
ORDER BY CountryCode
ASC LIMIT 1;
– The content of the row:
+-------------+----------+------------+------------+
| CountryCode | Language | IsOfficial | Percentage |
to
Removed
+-------------+----------+------------+------------+
A 1n ense
3% le lic
| BEL | MySQL | F | 0.0 |
| FJI | MySQL | F | 0.0 | C
l% erab
| GRL | MySQL | F | 0.0 |
n c
2
+-------------+----------+------------+------------+ 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
The example Ya in the @ co assumes
slide u se that you want to remove only one of the MySQL language
records in the i a
llCountryLanguage table, using CountryCode as the criteria, starting
b a d
l ฺ b o
alphabetically from the top.

( yae

MySQL for Beginners 9 - 18


Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Delete and modify table data


• Add new data to a table by using the INSERT and
REPLACE statements
• Modify data in a table by using the UPDATE statement
• Remove table rows by using the DELETE statement

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 9 - 19


Practice 9-1 Overview:
Insert and Replace Table Row Data
This practice covers the following topics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Adding table row data


• Replacing current table row data

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 9 - 20


Practice 9-2 Overview:
Modify and Delete Table Row Data
This practice covers the following topics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Modifying existing table row data


• Deleting specific table rows

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 9 - 21


Practice 9-3 Overview:
Manipulate Table Row Data
in the “Pets” Database
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

This practice covers the following topics:


• Adding table row data
• Replacing current table row data
• Modifying table row data
• Deleting table rows
to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 9 - 22


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Functions

to
A 1n ense
Built-In and Group Functions
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(
Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Use built-in functions in MySQL


• Describe and use string functions
• Describe and use temporal functions
• Describe and use numeric functions
• Describe and use control flow functions
• Use aggregate functions with the SELECT statement to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 10 - 2


Functions in MySQL Expressions

• Functions can be invoked within expressions.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• An expression returns a value that is used in place of the


function call when evaluated.
• General syntax:
function_name([<arg1> [, <arg2>, …, <argn>]])

– The parentheses following the function name are required.


to
• Examples:
A 1n ense
– SELECT NOW(): The NOW function returns the 3 % edate
current l ic
l C
% rabl
and time. c
n
0Ifunction n s fe
– SELECT VERSION(): The VERSION % 2 t r a returns the
MySQL server version currently l a
il being -
onused on the host.
a d n
B ob as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y syntax,
In the general us call includes the function name followed by parentheses
@ a function
i l
(which maydcontainl a arguments used to perform the function).
b a
o around function arguments are permitted. However, there must be no whitespace
Spacesb
l ฺ
( yaebetween a function name and the parenthesis following it. This helps the MySQL parser to
distinguish between function calls and references to tables or columns that happen to have
the same name as a function.
For more information about functions, see the MySQL Reference Manual at
http://dev.mysql.com/doc/refman/5.5/en/functions.html.

MySQL for Beginners 10 - 3


Function Tips

• Functions can be used anywhere a value expression is


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

accepted.
– Most function calls also take arguments.
• Columns can be used as arguments with the correct data
type.
• The output of a function can be used as the input of
another function. to
1 n nse
• An expression with NULL always produces a NULL A
% output. i ce
3
C forbale l
– Unless otherwise indicated in the documentation c l % ra
I n s f e
particular function or operator
% 20 tran
• Mathematical functions return d i la oonn-error.
lNULL
o ba s a n eฺ
– For instance, a division
r a B by hzero a uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
b o ba
elฺ
(ya

MySQL for Beginners 10 - 4


Function Categories

• String: Perform operations relating to strings.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Temporal: Perform operations on dates and times.


• Numeric: Perform several types of mathematical
operations.
• Control Flow: Choose between different values based on
the result of an expression.
• Aggregate: This is based on aggregates or groups ofn to
values. A 1 ense
% ic 3 le l
C
l% erab
n c
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Yacategories
The function @ coare ucovered
se in detail in the following slides.
d i lla
b o ba
a e lฺ
( y

MySQL for Beginners 10 - 5


String Functions

• Perform operations on strings, such as:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Calculating string lengths


– Extracting pieces of strings
– Searching for substrings or replacing them
– Performing case conversion
• String functions are divided into two categories:
– Numeric: Return numbers to
– String: Return strings A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 10 - 6


String Function: Numeric Category Examples

• Returns the number of • Returns the position in the


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

characters in the string: string where substring occurs:


mysql> SELECT CHAR_LENGTH('MySQL'); mysql> SELECT INSTR('MySQL', 'SQL');
+----------------------+ +-----------------------+
| CHAR_LENGTH('MySQL') | | INSTR('MySQL', 'SQL') |
+----------------------+ +-----------------------+
| 5 | | 3 |
+----------------------+ +-----------------------+

• Returns results of string sort comparison (0=same, –1=smaller, 1=other): to


mysql> SELECT STRCMP('abc','def'), A 1n ense
-> STRCMP('def','def'),
C 3% le lic
-> STRCMP('def','abc');
n c l% erab
0 I n s f
| STRCMP('abc','def') | STRCMP('def','def') % 2
+---------------------+---------------------+---------------------+
tra
i l l n -
a | STRCMP('def','abc') |

b a d a| 1no
+---------------------+---------------------+---------------------+
| -1 | 0
B o as e ฺ |

d r a x) h Guid
+---------------------+---------------------+---------------------+

j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
Syntax and @ coinformation
Yaadditional u se for the string (numeric) functions:
d i lla
• CHAR_LENGTH(<string>)
•ฺbo
ba
INSTR(<string>, <substring>): Returns 0 if the substring is not in the specified
a e l string
( y
• STRCMP(<arg1>, <arg2>): Returns 0 if arguments are the same, -1 if arg1 is
smaller than arg2 (according to the current sort order), and 1 otherwise

MySQL for Beginners 10 - 7


String Function: String Category Examples
(CONCAT, REVERSE, LEFT, RIGHT)
• Concatenates the given • Returns string with the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

arguments into one string: characters in reverse order:


mysql> SELECT CONCAT('A', '-', 'Z'); mysql> SELECT REVERSE('MySQL');
+-----------------------+ +------------------+
| CONCAT('A', '-', 'Z') | | REVERSE('MySQL') |
+-----------------------+ +------------------+
| A-Z | | LQSyM |
+-----------------------+ +------------------+

to
• Returns the left-most • 1n ense
Returns the right-most
A
length characters of string: length characters lic
3%of string:
C ble
mysql> SELECT LEFT('MySQL', 3);
c l %
mysql> SELECT RIGHT('MySQL', 3); ra
I n s f e
20 tran
+-------------------+ +-------------------+
| LEFT ('MySQL', 3) |
%
| RIGHT('MySQL', 3) |
lla non-
+-------------------+
d i+-------------------+

oba as a ideฺ
| MyS | | SQL |
+-------------------+ B
ra x) h t Gu
+-------------------+

n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y additional
Syntax and us for the string (string category) functions:
@ information
l l a
b a di
• CONCAT(<arg1> [, <arg2>, …, <argn>])
•ฺbo
e l REVERSE(<string>)
( ya • RIGHT(<string>, <length>)
• LEFT(<string>, <length>)

MySQL for Beginners 10 - 8


String Function: String Category Examples
(LOWER, UPPER, LPAD, RPAD)
• Returns the string with all • Returns the string with all
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

characters in lowercase: characters in uppercase:


mysql> SELECT LOWER('MySQL'); mysql> SELECT UPPER('MySQL');
+----------------+ +----------------+
| LOWER('MySQL') | | UPPER('MySQL') |
+----------------+ +----------------+
| mysql | | MYSQL |
+----------------+ +----------------+

to
• Returns string left-padded with • 1n ense
Returns string right-padded
A
the indicated characters: with the indicated lic
3%characters:
C ble
mysql> SELECT LPAD('MySQL', 8, '.');
c l %
mysql> SELECT RPAD('MySQL', 8, '.');ra
I n s f e
20 tran
+------------------------+ +------------------------+
| LPAD('MySQL', 8, '.') |
%
| RPAD('MySQL', 8, '.') |
lla non-
+------------------------+
d i+------------------------+

oba as a ideฺ
| ...MySQL | | MySQL... |
+------------------------+ B
ra x) h t Gu
+------------------------+

n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y additional
Syntax and us for the string (string category) functions:
@ information
l l a
b a di
• LOWER(<string>)
•ฺbo
e l UPPER(<string>)
( ya • LPAD(<string>, <length>, <padding>)
• RPAD(<string>, <length>, <padding>)

MySQL for Beginners 10 - 9


String Function: String Category Examples (TRIM)

• Removes all the leading and trailing spaces around the string:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT TRIM(' MySQL ') AS str;


+-------+
| str |
+-------+
| MySQL |
+-------+

• Removes the specified string characters at the beginning of the


o
string:
1 n nse t
mysql> SELECT TRIM(LEADING 'Q' FROM 'QQQMySQLQQQ');
3 %A e lice
+--------------------------------------+
l % C bl
+--------------------------------------+Inc
| TRIM(LEADING 'Q' FROM 'QQQMySQLQQQ') |
f e ra
20| tran s
| MySQLQQQ
%
lla non-
i
+--------------------------------------+
d
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Syntax and Y additional us for the string (string category) functions:
@ information
l l a
• TRIM(
b a di [[LEADING | TRAILING] <string> FROM ] <fullstring>):
l ฺ b o - Removes the string characters at the end and/or beginning of <fullstring>
( yae - With no argument after <string>, returns <string> with all leading and trailing
spaces trimmed

MySQL for Beginners 10 - 10


String Function: String Category Examples
(SUBSTRING)
• Returns the part of the string starting at the specified position
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

through the end of string:


mysql> SELECT SUBSTRING('MySQL', 3);
+-----------------------+
| SUBSTRING('MySQL', 3) |
+-----------------------+
| SQL |
+-----------------------+

• Returns the part of the string starting at the specified position,


to
and the number of characters indicated: n
A 1 ense
mysql> SELECT SUBSTRING('MySQL', 2, 2); 3 % e lic
+--------------------------+
l C
% rabl
c
0In ansfe
| SUBSTRING('MySQL', 2, 2) |
+--------------------------+ 2
% n-tr
| yS |
i l l a
+--------------------------+ d
b a a no ฺ
B o as ide
r a ) h u
j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
Syntax and Yaadditional
@ coinformation
u se for the string (string category) functions:
d i lla
• SUBSTRING(<string>,
o b a <startpos> [, <chars>])

l ฺ b
( yae

MySQL for Beginners 10 - 11


String Function: String Category Examples
(SUBSTRING_INDEX)
• Returns the part of the string starting from the left to the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

specified delimiter count: 1


2

mysql> SELECT SUBSTRING_INDEX('training@mysql.com', '@', 1);


+-----------------------------------------------+
| SUBSTRING_INDEX('training@mysql.com', '@', 1) |
+-----------------------------------------------+
| training |
+-----------------------------------------------+

• Returns the part of the string starting from the right to the
o
specified delimiter count: -3
-2 1 n nse t
A e
3%-2);le lic
-1
mysql> SELECT SUBSTRING_INDEX('www.mysql.com', C '.',
+-------------------------------------------+
| SUBSTRING_INDEX('www.mysql.com', '.',In
cl% rab
-2) | sfe
+-------------------------------------------+
% 20 tran
| mysql.com
d i lla non- |
oba as a ideฺ
+-------------------------------------------+
B
ra x) h t Gu
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Syntax and Y additional us for the string (string category) functions:
@ information
l l a
di
• SUBSTRING_INDEX(<string>,
b a <delimiter>, <count>): Searches string for the

l ฺ b ocount occurrence of delimiter (from the left if count is positive, right if negative) and
( yae returns the characters searched through when hitting the count

MySQL for Beginners 10 - 12


Temporal Functions

• Perform operations such as:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Extracting parts of dates and times


– Reformatting values
– Converting values to seconds or days
• Use several formats for the same information, such as:
– 2012-02-10 22:50:15
– Friday, February 10, 2012 to
• Generate temporal data in many ways: A 1n ense
C 3% le lic
– Copy existing data.
n c l% erab
– Execute the built-in function. 2 0I ansf
l l a % n-tr
– Build a string representation
a i
d to be nevaluated
o by the server.
b
o as a ฺ
r a B
) h u ide
j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
TemporalY
a
functions@ cosomewhat
are u se complex due to the many ways in which you can describe
d
a single datei lla time, such as the following:
and
• bo ba
2012-02-10 22:50:15
l ฺ
( yae • Friday, February 10, 2012
• 2/10/2012 6:50:15 P.M. EST
• 2/10/2012 22:50:15 GMT

MySQL for Beginners 10 - 13


Temporal Functions: Date/Time Formats
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Type Default Format

DATE YYYY-MM-DD

TIME HH:MM:SS

DATETIME YYYY-MM-DD hh:mm:ss

TIMESTAMP YYYY-MM-DD hh:mm:ss to


A 1n ense
YEAR YYYY
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya formats
The Date/Time @ cochartuinsethe slide gives a list of all date and time formats permitted to
d i
be used within llatemporal functions.
o a
bData
Seebthe Types lesson for specific information about the values and ranges for these
l ฺ
( yaeformat types.
Functions that expect date values usually accept DATETIME values and ignore the time part.
Functions that expect time values usually accept DATETIME values and ignore the date part.

MySQL for Beginners 10 - 14


Temporal Functions: Function Types

Function Syntax Definition


Current date and time as set on the server host
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

NOW() (DATETIME format)

CURDATE() Current date as set on the server host (DATE format)

CURTIME() Current time as set on the server host (TIME format)

YEAR(<date_expression>) Year in four-digit YEAR format

MONTH(<date_expression>) Month of the year in integer format, per expression

DAYOFMONTH(<date_expression>)
or DAY(<date_expression>)
Day of the month in integer format, per expression
n nse to
A 1
DAYNAME(<date_expression>) Day of the
(English)
week in string format, per
3 % e lice
expression

l % C(in 0–23brange),
l per
Hour of the day in integer format
c r a
0In ansfe
HOUR(<date_expression>)
expression
2
MINUTE(<date_expression>) Minute of the %
i l l n -tr format, per expression
a day inointeger
o bad ofstheaminute
Second n in integerฺ format, per
ide
SECOND(<date_expression>)
expression
r a B ha u
nd yฺmx ent G )
j a
le © 2012,
2 0 A
Copyright
ฺ u tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
The tableY
a o only
cshows se a partial list of the available temporal functions.
@
in the slide
lla u
d i
b o ba
a e lฺ
( y

MySQL for Beginners 10 - 15


Temporal Functions: Extracting Temporal Data
Examples
• Extracting current temporal data (date, time, and day of week):
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT CURDATE(), CURTIME(), DAYNAME(NOW());


+------------+-----------+----------------+
| CURDATE() | CURTIME() | DAYNAME(NOW()) |
+------------+-----------+----------------+
| 2012-02-06 | 17:55:40 | Friday |
+------------+-----------+----------------+

• Addition of a specified interval of days from the current date and


time: to
A 1n ense
mysql> SELECT NOW(), NOW() + INTERVAL 5 DAY;
+---------------------+------------------------+ 3
% e lic
l C
%| rabl
| NOW() | NOW() + INTERVAL 5 DAY
c
+---------------------+------------------------+
2 0In an|sfe
a% on-tr
| 2012-02-06 18:02:35 | 2006-02-11 18:02:35
i l l
+---------------------+------------------------+

o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 10 - 16


Temporal Functions: Extracting Temporal Data
Examples
• Customizing the output format of temporal data:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT NOW(), DATE_FORMAT(NOW(), '%W the %D of %M');


+---------------------+---------------------------------------+
| NOW() | DATE_FORMAT(NOW(), '%W the %D of %M') |
+---------------------+---------------------------------------+
| 2012-02-06 18:02:35 | Friday the 6th of February |
+---------------------+---------------------------------------+

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Yaadditional
Syntax and @ coinformation
u se for the temporal functions:
d i lla (<date>, <format>)
• DATE_FORMAT
•ฺbo
ba
The % symbol is required before any predefined date/time format specifiers.
a e l
( y

MySQL for Beginners 10 - 17


Numeric Functions

Perform mathematical operations such as:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Rounding
• Truncation
• Trigonometric calculations
• Generating random numbers
Function Syntax Definition
ABS(<number>) Returns the absolute value of number
n nse to
Returns –1, 0, or 1 depending on whether1the
SIGN(<number>)
number is negative, zero or positive%
A i ce
3 e l
l to C
% decimals bl
TRUNCATE(<number>, <decimals>) Returns number truncated
a
erlower integer
ncto the closest
f
FLOOR(<number>) Rounds number down 0
2 tran I s
l a %
l numbernup nto-the closest higher integer
CEILING(<number>) Rounds
d i
a number o
B obRounds s a to theeฺclosest integer
a x) h Guid
ROUND(<number>)
r a
a d
n yฺm ent
e j
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
ROUND(<number>):
• Rounds d i la on DECIMAL data types
lup
b o ba to zero, if not specified
Defaults
a e lฺ

( y • For exact-value numbers, a value with a fractional part less than .5 is rounded down to
the next integer if positive, or up to the next integer if negative.
• For approximate-value numbers, the result depends on the C library. On many systems,
this means that a value with any fractional part is rounded to the nearest even integer.

MySQL for Beginners 10 - 18


Numeric Functions: Examples

• Returns the absolute value of the negative and positive values:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT ABS(-42), ABS(42);


+----------+---------+
| ABS(-42) | ABS(42) |
+----------+---------+
| 42 | 42 |
+----------+---------+

• Returns results of sign determination (–1=negative, 0=zero, 1=positive):


to
1n ense
mysql> SELECT SIGN(-42), SIGN(-1), SIGN(0), SIGN(1), SIGN(42);
+-----------+----------+---------+---------+----------+ A
| SIGN(-42) | SIGN(-1) | SIGN(0) | SIGN(1) | SIGN(42) |
C 3% le lic
+-----------+----------+---------+---------+----------+
n c l% erab
0I ansf
| -1 | -1 | 0 | 1 | 1 |
2
+-----------+----------+---------+---------+----------+

i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 10 - 19


Numeric Functions: Additional Functions

• Geometric functions:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– DEGREES(), PI(), RADIANS()


• Trigonometric functions:
– COS(), SIN(), COT()
– ACOS(), ASIN(), ATAN(), ATAN2()
• Other functions:
– EXP(), LN(), LOG(), LOG2(), LOG10() to
– POWER(), SQRT() A 1n ense
C 3% le lic
– MOD() l% ab nc sfer
0
2 tran I
l non-
l a %
d i
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
l l a
o b adi
l ฺ b
(y ae

MySQL for Beginners 10 - 20


Control Flow Functions

• Choose between different values based on the result of


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

an expression.
• IF() function example:
mysql> SELECT IF(1 > 0, 'YES', 'NO');
+------------------------+
FALSE
| IF(1 > 0, 'YES', 'NO') |
+------------------------+ TRUE
| YES |
+------------------------+
to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 10 - 21


Control Flow Functions: CASE Functions

The CASE function provides branching flow of control in two


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

different ways:
• Expression value comparison
• Expression condition evaluation

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 10 - 22


Control Flow Functions: CASE Function Syntax

• Expression value comparison example:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

CASE value
WHEN <compare_value> THEN <result>
[WHEN <compare_value> THEN <result> ...]
[ELSE <result>]
END

• Expression condition evaluation example :


to
CASE A 1n ense
WHEN <condition> THEN <result> C 3% le lic
n c l%
f e r ab
0I ans
[WHEN <condition> THEN <result> ...]
2
[ELSE <result>]
i l l a% on-tr
END
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @
The first example coslideureturns
in the se the result where value=compare_value. The second
i a the result for the first condition that is true. If there was no matching
llreturns
d
slide example
ba the result after ELSE is returned, or NULL if there is no ELSE part.
resultovalue,
e lฺ b
( y a

MySQL for Beginners 10 - 23


Control Flow Functions: CASE Function Examples

mysql> SELECT CASE 3 WHEN 1 THEN 'one'


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-> WHEN 2 THEN 'two' ELSE 'more' END;


'more'

mysql> SELECT CASE WHEN 1>0 THEN 'true‘


-> ELSE 'false' END;
'true'

mysql> SELECT CASE BINARY 'B‘


-> WHEN 'a' THEN 1 WHEN 'b' THEN 2 END;
NULL
to
A 1n ense
3% le lic
SELECT pName, oID, pGender,
CASE C
WHEN pGender = 'm' THEN 'Boy' cl%
n f e r ab
WHEN pGender = 'f' THEN 'Girl'
2 0I ans
ELSE 'Unknown'
l l a % n-tr
END
a i
d a no
FROM pet_info b
o as e ฺ
ORDER BY pGender; B
ra x) h t Gu i d
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
The default Y return@ type of a u s expression is the compatible aggregated type of all return
CASE
values, butd l l a
i depends on the context in which you use it. If you use it in a string context,
also
o
the resultb a
is returned as a string. If used in a numeric context, the result is returned as a
l ฺ b
yae
decimal, real, or integer value.
( The last example in the slide assumes that you want to send name tags to the owners of pets
from the Pets database. You want to make the tags blue for the boys and pink for the girls.
You might use the CASE function to get a list that indicates and separates the pet genders.
The following is the result of the statement in the slide (using the partially populated table):
------------------------------------+
| pName | oID | pGender | CASE |
+--------+-----+---------+----------+
| Claws | 2 | M | Boy |
| Fluffy | 1 | F | Girl |
| Buffy | 1 | F | Girl |
+--------+-----+---------+----------+

MySQL for Beginners 10 - 24


Quiz

The CHAR_LENGTH() function is part of the ____________


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

function category.
a. String
b. Temporal
c. Numeric
d. Control Flow
e. Aggregate
to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 10 - 25


Aggregate Functions

• Perform summary operations on a set of values, such as:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Counting
– Averaging
– Finding minimum or maximum values
• Calculate a single value based on a group of values from
different rows.
• Result value is based only on non-NULL values from the to
n e
selected rows. A1 ens
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Aggregate
a
Yfunctions @ careo alsouknown
se as group functions. A SELECT statement can produce a
list of rows d i
thatllamatch a given set of conditions. This list provides the details about the
o
selected
b barows. However, if you want to know about the overall characteristics of the rows, you
a e lฺ more interested in getting a summary instead. The resulting value is based only on non-
are
( y NULL values from the selected rows (with the exception that COUNT(*) counts all rows).

MySQL for Beginners 10 - 26


Aggregate Function Types

Some of the aggregate function types:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Function Syntax Definition


MIN(<column_name>) Find the smallest value.

MAX(<column_name>) Find the largest value.

SUM(<column_name>) Summarize numeric value totals.


to
AVG(<column_name>) Summarize numeric value averages. A 1n ense
3 % e lic
COUNT(<column_name>) Count rows and non-null values.
l C
% rabl
c
GROUP_CONCAT(<column_name>) Concatenate a set of2 0In to aproduce
strings n sfea single string.
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya can o the DISTINCT
cuse se
All the functions
l l a @ u keyword, although it is not useful for the MAX() and

b a di
MIN() functions.

ฺ b o examples:
DISTINCT
l
( yae SUM(DISTINCT <column_name>)
AVG(DISTINCT <column_name>)
COUNT(DISTINCT <column_name>)
GROUP_CONCAT(DISTINCT <column_name>)

MySQL for Beginners 10 - 27


Aggregate Functions: COUNT Function Examples

• Retrieves a count of all rows in the Country table:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT COUNT(*) FROM Country;


+----------+
| COUNT(*) |
+----------+
| 239 |
+----------+

• Retrieves a count of all the Country table rows that have


non-NULL values in the Capital column: to
n
A 1 ense
mysql> SELECT COUNT(Capital) FROM Country;
C 3% le lic
+----------------+
n c l% erab
| COUNT(Capital) |
2 0I ansf
+----------------+
i l l a% on-tr
| 232 | ad n ฺ
o b a
+----------------+
r a B has uide
a n d mx) nt G
A lej © 2012,
a d yฺ uditseaffiliates. All rights reserved.
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


Y example
In the second s specifying a count of Capital yields a different result
@ in theuslide,
l l a
b adiexample,
than the first
NULLovalues
because not every country has a Capital associated with it. The
are not included in the count.
e l ฺb
( ya

MySQL for Beginners 10 - 28


Aggregate Functions: GROUP BY Clause

• The GROUP BY clause places rows into groups.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Each group consists of rows having the same value in one


or more columns.
– Calculates a summary value for each group
• Example:
mysql> SELECT Continent, AVG(Population)
-> FROM Country
-> GROUP BY Continent;
o
+---------------+-----------------+
1 n nse t
%A e lice
| Continent | AVG(Population) |
+---------------+-----------------+
| Asia | 72647562.7451 | 3
C bl
| Europe | 15871186.9565 |
c l % ra
I n s f e
20 tran
| North America | 13053864.8649 |
| Africa | 13525431.0345 |
%
lla non-
| Oceania | 1085755.3571 |
d i
oba as a ideฺ
| Antarctica | 0.0000 |

B
| South America | 24698571.4286
ra x) h t Gu
|
+---------------+-----------------+
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
If a WHERE Yclause@ s and GROUP BY arranges them into four groups of five
selects 20urows
rows each,d l l a
aisummary function produces a value for each of the four groups.
Without b a
o a GROUP BY clause, an aggregate function calculates a summary value based on the
l ฺ b
( yaeentire set of selected rows. (That is, MySQL treats all rows as a single group.)
In the slide example, you group the Country table rows by continent, and calculate the
average population of countries in each continent.

MySQL for Beginners 10 - 29


Aggregate Functions: GROUP BY Clause and
GROUP_CONCAT Function
• The GROUP_CONCAT() function concatenates results.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example:
mysql> SELECT GovernmentForm, GROUP_CONCAT(Name)
-> AS Countries
-> FROM Country WHERE Continent = 'South America‘
-> GROUP BY GovernmentForm\G
************************ 1. row ************************
GovernmentForm: Dependent Territory of the UK
Countries: Falkland Islands
************************ 2. row ************************
to
GovernmentForm: Federal Republic
A 1n ense
3% le lic
Countries: Argentina,Venezuela,Brazil
************************ 3. row ************************ C
l% erab
GovernmentForm: Overseas Department of France
n c
Countries: French Guiana
2 0I ansf
i l l a% on-tr
************************ 4. row ************************

bad s a n eฺ
GovernmentForm: Republic
o
Countries: Chile,Uruguay,Suriname,Peru,Paraguay,Bolivia,
B ha
Guyana,Ecuador,Colombia
d r a x ) G uid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
Ya in the
The example @ co creates
slide u sea list of the countries that have a particular form of
government d i
on llathe South American continent.
b o ba
a e lฺ
( y

MySQL for Beginners 10 - 30


Aggregate Functions: GROUP BY and HAVING
Clauses
• Use the HAVING clause to eliminate rows based on
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

aggregate values.
– Evaluated after the grouping implied by GROUP BY
• Example:
mysql> SELECT Continent, SUM(Population)
-> FROM Country
-> GROUP BY Continent
-> HAVING SUM(Population) > 100000000;
o
+---------------+-----------------+
1 n nse t
%A e lice
| Continent | SUM(Population) |
+---------------+-----------------+ 3
C bl
| Asia | 3705025700 |
c l % ra
| Europe | 730074600 I n s f e
20 tran
|
| North America | 482993000 |
%
lla non-
| Africa | 784475000 |
d i
| South America | 345780000
B oba as a ideฺ
|
+---------------+-----------------+
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
You can useY the HAVING
@ modifierus to require that the groups produced by a GROUP BY clause
l l a
b a di criteria.
satisfy particular
As b
l ฺ o it resembles the WHERE clause. The difference is that the HAVING clause is
such,

( yaeevaluated after the grouping implied by the GROUP BY clause. This means that the HAVING
condition can refer to aggregate functions. However, any part of a condition that can also
appear in the WHERE clause should not be in the HAVING clause. A good HAVING clause is
always based on aggregate functions (because these are not allowed in the WHERE clause).
The slide example results in a list of continents whose sum (aggregate value) of country
populations is greater than 100,000,000.

MySQL for Beginners 10 - 31


Aggregate Functions: GROUP BY Clause and
WITH ROLLUP Modifier
• Use the WITH ROLLUP modifier to produce multiple
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

levels of summary values.


• Example:
mysql> SELECT Continent, SUM(Population)
-> FROM Country
-> GROUP BY Continent
-> WITH ROLLUP;
+---------------+-----------------+
| Continent | SUM(Population) |
o
+---------------+-----------------+
1 n nse t
%A e lice
| Asia | 3705025700 |
| Europe | 730074600 | 3
C bl
| North America | 482993000 |
c l % ra
| Africa | 784475000 |
I n s f e
| Oceania | 30401150 |
% 20 tran
| Antarctica | 0 |
d i lla non-
oba as a ideฺ
| South America | 345780000 |
| NULL | 6078749450 |
B
ra x) h t Gu
+---------------+-----------------+
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
The exampleY in the us a list of the population of each continent, as well as the
@slide generates
total of the d i l l a
population on all the continents.
b a
o way to do this is to run one query to get the per-continent totals and another to get
Another
b
l ฺ
( yaethe total for all continents. Using WITH ROLLUP enables you to use a single query to get both
the detailed results as well as the total sum of all rows, eliminating the need for multiple
queries or extra processing on the client side.

MySQL for Beginners 10 - 32


Aggregate Functions: Super Aggregate Operation

• Use the WITH ROLLUP and the AVG() function


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Produce a final line that comprises the application of the


given aggregate function.
• Example:
mysql> SELECT Continent, AVG(Population)
-> FROM Country
-> GROUP BY Continent WITH ROLLUP;
+---------------+-----------------+
| Continent | AVG(Population) |
to
1n ense
+---------------+-----------------+
| Asia | 72647562.7451 | A
| Europe | 15871186.9565 |
C 3% le lic
| North America | 13053864.8649 |
n c l% erab
0I ansf
| Africa | 13525431.0345 |
| Oceania | 1085755.3571 | 2
| Antarctica | 0.0000 |
i l l a% on-tr
bad s a n eฺ
| South America | 24698571.4286 |
| NULL
o
| 25434098.1172
B ha
|

d a
+---------------+-----------------+
r x ) G uid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
WITH ROLLUP Ya performs @ co a "super-aggregate"
u se operation. It does not simply generate a sum of
l l a
the numbers
b
application a dofithat
the
appear in the Population column. Instead, the final line comprises the
given aggregate function, because it is written in the SELECT clause (on
l ฺ b o
yae
every single row selected) after GROUP BY.
( To illustrate this, the example in the slide calculates columns using the AVG() function rather
than SUM(). The final rollup line contains the overall average rather than the sum of
averages.
Note: ORDER BY does not work with WITH ROLLUP.

MySQL for Beginners 10 - 33


Spaces in Function Names

• By default, there must be no space between a function


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

name and the parenthesis:


mysql> SELECT PI ();
ERROR 1305 (42000): FUNCTION world.PI does not exist

• You can change this using the IGNORE SPACE SQL


mode:
mysql> SET sql_mode = 'IGNORE_SPACE';
Query OK, 0 rows affected (0.06 sec) to
A 1n ense
mysql> SELECT PI (); C 3% le lic
+----------+
n c l% erab
| PI() | 2 0I ansf
+----------+
i l l a% on-tr
| 3.141593 |
o b ad a n ฺ
+----------+
r a B has uide
a n d mx) nt G
A lej © 2012,
a d yฺ uditseaffiliates. All rights reserved.
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


The SET of Ythe sql_mode
@ us any previous setting.
replaces
l l a
b a di
l ฺ b o
( yae

MySQL for Beginners 10 - 34


Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Use built-in functions in MySQL


• Describe and use string functions
• Describe and use temporal functions
• Describe and use numeric functions
• Describe and use control flow functions
• Use aggregate functions with the SELECT statement to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 10 - 35


Practice 10-1 Overview:
Quiz
This practice covers answering questions about MySQL
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

functions.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 10 - 36


Practice 10-2 Overview:
Use Built-In, String, and Temporal Functions
This practice covers using built-in , string, and temporal
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

function statements.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 10 - 37


Practice 10-3 Overview:
Use Numeric and Control Flow Functions
This practice covers using numeric and control flow statements.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 10 - 38


Practice 10-4 Overview:
Use Aggregate Functions
This practice covers the following topics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Using aggregate functions


• Using the GROUP BY clause, with options

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 10 - 39


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Joining Tables

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(
Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Explain the concept of a join


• Use the JOIN keyword to query multiple tables
• Execute outer and inner joins

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 11 - 2


Combining Multiple Tables

• Some questions cannot be answered using just one table.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Some queries require SELECT statements that include a


combination of multiple tables.
• A join operation is used to combine the data from one
table with the data of another table.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Yaqueries o sosefar in this course retrieve data from a single table at a time.
cshown
The SELECT
lla @ u
i
This lessondaddresses the performance of multiple table queries.
If you
b o ba to find the details of records referenced in a foreign key, you combine data from
want
a e lฺ
two or more tables by performing a table join.
( y

MySQL for Beginners 11 - 3


Joining Tables with SELECT

• Example of two separate tables that can be joined:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

table1 table2
+----+----+ +----+----+
| i1 | c1 | | i2 | c2 |
+----+----+ +----+----+
| 1 | a | | 2 | c |
| 2 | b | AND | 3 | b |
| 3 | c | | 4 | a |
+----+----+ +----+----+
3 rows in set (0.00 sec) 3 rows in set (0.00 sec)

• Joined tables:
SELECT * FROM table1, table2;
– This join results in an to
1 ense
+----+----+----+----+
| i1 | c1 | i2 | c2 |
+----+----+----+----+ Cartesian product.
% A ic
| 1 | a | 2 | c |
C 3 le l
ab all
| 2 | b | 2 | c |
| 3 | c | 2 | c | – The result
n c l% includes
e r
| 1 | a | 3 | b |
0I ans of rows
combinations f
| 2 | b | 3 | b |
2 tr
a% from -
| 3 | c | 3 | b |
| 1 | a | 4 | a |
d i l l o n table1 and table2.
n
oba as a ideฺ
| 2 | b | 4 | a |
| 3 | c | 4 | a |
+----+----+----+----+
B
ra x) h t Gu
9 rows in set (0.00 sec)

n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
When youYcross-join us (as in the example in the slide), each row from one table is
@ two tables
l l a
combined with
b a di each row from every other table, yielding all possible combinations of rows.
l ฺ b o is also known as the Cartesian product. Joining tables this way has the potential
This result

yae
to produce a very large number of rows because the row count is the product of the number of
( rows in each table.
A cross-join between two tables each containing 1000 rows will return 1000 × 1000 = 1 million
rows. That is a lot of rows, even though the individual tables are small. Such a join is also
called an unqualified join.

MySQL for Beginners 11 - 4


Categories of Joins

Category Type Description


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Combines all the rows from one table with all the
Unqualified Join Cross Join rows of another table

Identifies combinations of matching rows from two


Qualified Join Inner Join
tables

Identifies combinations of matching and


Qualified Join Outer Join
mismatching rows from two tables

• Unqualified join: Retains all row pairs to


A 1n ense
• % e lic to
Qualified join: Retains only specific row pairs3according
a particular join condition l C
% rabl
n c fe
Example: 20I ans % n-tr
i l l a
— A city (City table) is a capital
b a d of a no ฺ (Country table),
a country
and a country (Country B o table) a shas cities
i d e (City table)
a
dr mx) nt G h u
a n yฺ uditseaffiliates. All rights reserved.
A lej © 2012,
a d
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


The largeY majority@ usqualified. Most qualified joins serve to combine related tables.
of joins are
l l a
i condition expresses a meaningful relationship between the data sets, such as
That is, thedjoin
b a
the world_innodb
o database in the example in the slide.
e l ฺ b
(ya

MySQL for Beginners 11 - 5


Comma-Separated Joins

• Example of two separate queries that can be joined:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

SELECT Code, Name SELECT CountryCode, Language


FROM Country AND FROM CountryLanguage;
WHERE Continent = 'Africa';

• Joined tables:
mysql> SELECT Code, Name, Language CountryLanguage
-> FROM Country, CountryLanguage
-> WHERE Continent='Africa'
to
1n ense
Country -> AND Code = CountryCode;
+------+---------+------------------+
A
| Code | Name | Language |CountryLanguage
C 3% le lic
l% erab
+------+---------+------------------+
| AGO | Angola | Ambo |
n c
...
2 0I ansf
| BDI | Burundi | French |
i l l a% on-tr
bad s a n eฺ
...
| ZWE | Zimbabwe| Shona
o
B ha
|

d a
+------+---------+------------------+
r x ) G uid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
One way Y
a
to perform@ cotable ujoinseis to specify a list (comma separated) of tables in the FROM
a
clause of the d i lla statement and use the WHERE clause to indicate the relationship
SELECT
between
b o bathe tables.
a e lฺ
As demonstrated in the example in the slide, suppose that you want to find all the languages
( y spoken in every African country. This information cannot be found in just one table of the
world_innodb database. You have to extract the country names from the Country table and
the languages from the CountryLanguage table.

MySQL for Beginners 11 - 6


You can execute two separate queries in which you use the code in each as a reference, and
manually match up the country names to the languages (using the common country codes) as
follows:
mysql> SELECT Code, Name
-> FROM Country
-> WHERE Continent = 'Africa';
+------+---------------------------------------+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| Code | Name |
+------+---------------------------------------+
| AGO | Angola |
| BDI | Burundi |
| BEN | Benin |
| BFA | Burkina Faso |
...

mysql> SELECT CountryCode, Language


-> FROM CountryLanguage;
o
n nse t
+-------------+------------+
| CountryCode | Language | 1
+-------------+------------+
3 %A e lice
| ABW | Dutch |
l % C bl
| ABW | English |
I n c f e ra
| ABW | Papiamento |
20 tran s
| ABW | Spanish | %
lla non-
d i
oba as a ideฺ
| AFG | Balochi |
...
B
ra xin)the h slideGshows
u a more efficient approach of using
The comma-separated join in thedexample
a join to combine the two tables n
ja in one ฺquery t
m to egetn the desired results. In the example, the join
l e y
results in a list of the Code
2 0 d
A andฺucountry
a Name S tudfrom the Country table, and the corresponding
Language froml%
e r r eo this table. Joining the two tables within a SELECT statement
the CountryLanguage
results in Y a virtualcotable, which
a new se exists only for the duration of the statement.
@ u
a of the constructs allowed for single-table SELECT statements.
Joins can useillany
ba d
lฺ b o
y a e
(

MySQL for Beginners 11 - 7


INNER JOIN Keywords

• INNER JOIN replaces the comma separator.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Can be used with the ON or USING clause


• Examples: table
mysql> SELECT Country.Name, City.CountryCode column
-> FROM Country INNER JOIN City
-> ON Country.Name = City.Name;
+------------+-------------+
| Name | CountryCode |
SELECT Country.Name,
+------------+-------------+
to
OR
1nCityense
| Djibouti | DJI | City.CountryCode
| Mexico | PHL | FROM Country INNER JOIN A
% e lic
USING(Name); C3
% rabl
| Gibraltar | GIB |
| Armenia | COL |
c l
| Kuwait
| Macao
| KWT
| MAC
|
| 2 0In ansfe
| San Marino | SMR |
i l l a% on-tr
bad s a n eฺ
| Singapore | SGP |
+------------+-------------+
o
B ha
8 rows in set (0.19 sec)
d r a x ) G uid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
The syntaxYadiscussed
@ coearlieruuses
se the comma separator in the FROM clause to name (and
separate) the
d i la tables. Another inner join syntax uses the INNER JOIN keywords. With
ljoined
o ba those keywords replace the comma separator between table names. Also with
this syntax,
b
a e lฺ JOIN, the conditions that indicate how to perform row matching for the tables move
INNER
( y from the WHERE clause to become part of the FROM clause.
The ON or USING clause conditions indicate how to perform the join.
For example, the inner join in the example in the slide (previously performed using the comma
separator and the WHERE clause) now uses INNER JOIN and FROM...ON to receive the
same result. Recall that the purpose of this statement is to join the City and Country tables,
where the countries have a City with the same name.
If the name of the joined column is the same in both tables, you can use USING() rather than
ON after the table names, and list the name within the parentheses. For example, in the join
query in the slide, the tables are matched by columns with the same name (Name). Therefore,
the syntax can be rewritten with USING() shown in the slide, to get the same results, in this
case.
Note: ON and USING are not exactly identical. USING treats the columns from the two tables
as the same, whereas ON treats them as two different columns.

MySQL for Beginners 11 - 8


JOIN Keywords

• JOIN is equivalent to INNER JOIN.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Can be used with the ON and WHERE clauses


• Example:
mysql> SELECT COUNT(City.Name)
-> FROM City
-> JOIN Country
-> ON CountryCode = Code
n nse to
-> WHERE Continent = 'South America';
A 1
+------------------+
3 % e lice
| COUNT(City.Name) |
l % C bl
+------------------+
I n c f e ra
| 470 | 20 tran s
%
+------------------+
1 row in set (0.05 sec)ad
illa non-
B ob as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Along with Ythe ON@ subclause,usthe WHERE clause can be used to further narrow the result set.
l l a
For instance,
b a di the query in the example in the slide counts the cities in South America.
Because
l ฺ b o the city rows do not have information about their continent, you need to join the city

yae
to its country information. The query in the example combines two tables (City and Country)
( to show a count of all cities in South America. The ON subclause specifies that a City row can
be combined only with a Country row when the CountryCode column value in the City table
equals the value of the Code column in the Country table, and the WHERE clause narrows the
result by stating that the join applies only where the continent is South America. The
expression following the ON keyword must be a condition.
In general, use the ON clause for conditions that specify how to join tables, and use the WHERE
clause to restrict which rows you want in the result set.
Note: The INNER JOIN keywords are equivalent to the JOIN keyword, and they can be used
interchangeably.

MySQL for Beginners 11 - 9


Outer Joins

• Identify combinations of matching and mismatching rows


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

from two tables


• Can use two different types of SELECT query syntax:
– LEFT JOIN: Uses the table to the left of the keywords to
base the join comparison on
– RIGHT JOIN: Uses the table to the right of the keywords to
base the join comparison on
to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
You do not Yget @ co uassyou
a mismatches e would with a cross-join.
The LEFTad illa and RIGHT JOIN answer the same kinds of questions, but differ slightly in
JOIN
their
l ฺ b ob A LEFT JOIN can always be rewritten into an equivalent RIGHT JOIN.
syntax.

( yaeFor example, an inner join can associate country names listed in the Country table with the
languages spoken in those countries through a join based on country codes with the
CountryLanguage table. But it cannot tell you which countries are not associated with any
language in the CountryLanguage table. Answering the latter question is a matter of
identifying which country codes present in the Country table are not present in the
CountryLanguage table. In the following example, the LEFT JOIN results in a list that
shows where there were NULLs for the Language:

MySQL for Beginners 11 - 10


mysql> SELECT Name, Language
-> FROM Country
-> LEFT JOIN CountryLanguage
-> ON Code = CountryCode;
+-----------------------------+------------------+
| Name | Language |
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

+-----------------------------+------------------+
| Aruba | Dutch |
| Aruba | English |
| Aruba | Papiamento |
| Aruba | Spanish |
| Afghanistan | Balochi |
...
| Antarctica | NULL |
| French Southern territories | NULL |
| Antigua and Barbuda | Creole English |
| Antigua and Barbuda | English |
to
| Australia | Arabic |
A 1n ense
3% le lic
| Australia | Canton Chinese |
| Australia | English | C
l% erab
| Australia | German |
n c
...
2 0I ansf
990 rows in set (0.00 sec)
i l l a% on-tr
b a dcolumn.
Note: NULLs are returned for nonexistent rows ofa
o a n ฺ
r a B has uide
a n d mx) nt G
A lej adyฺ tude
2 0 oฺu s S
a el corre e thi
%
Y @ us
l l a
b a di
l ฺ b o
( yae

MySQL for Beginners 11 - 11


LEFT JOIN Keywords

• LEFT JOIN uses the WHERE clause to find mismatches.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example:
mysql> SELECT Name, Language
-> FROM Country
-> LEFT JOIN CountryLanguage
-> ON Code = CountryCode
-> WHERE CountryCode IS NULL;
+----------------------------------------------+----------+
o
| Name | Language |
1 n nse t
%A e lice
+----------------------------------------------+----------+
| Antarctica | NULL |
3
C bl
| French Southern territories | NULL |
c l % ra
| Bouvet Island | NULL |
I n s f e
| Heard Island and McDonald Islands
20 tran
| NULL
%
|

lla non-
| British Indian Ocean Territory | NULL |
d i
| South Georgia and the South Sandwich Islands | NULL |
oba as a ideฺ
+----------------------------------------------+----------+
B
ra x) h t Gu
6 rows in set (0.00 sec)

n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
A LEFT JOINY is @ aptly named usdue to the fact that the comparison that takes place between
l l a
With o adibe combined
the tables to
anbappropriate
is based on the first (or left-most) table named in the statement.
WHERE clause, an outer join can filter out matches to display only where a
e l
row ฺbin one table has no match in another table.
( ya The query in the example in the slide is performed with a LEFT JOIN, which requires row
combinations to have NULL in the right table.

MySQL for Beginners 11 - 12


RIGHT JOIN Keywords

• RIGHT JOIN uses the WHERE clause to find mismatches.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Roles of tables reversed from LEFT JOIN.


• Example:
mysql> SELECT Name, Language
-> FROM Country
-> RIGHT JOIN CountryLanguage
-> ON Code = CountryCode
to
-> WHERE CountryCode IS NULL;
A 1n ense
Empty set (0.00 sec)
C 3% le lic
– This comparison uses the second tablenand c l%results
f e r abin an
empty set. 2 0I ans
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @between
The only difference co uasLEFT e JOIN and a RIGHT JOIN is that the roles of the tables
are reversed.
d i lAlaRIGHT JOIN produces a result for each row in the right table, whether or not
bamatch in the left table.
it hasoany
b
a e
Thelฺ previous example showed the result of a LEFT JOIN. The example in this slide is the
( y same statement as in the preceding slide, but with a RIGHT JOIN.

MySQL for Beginners 11 - 13


Outer Joins: USING and NULL

• USING: Uses multiple columns that exist in both tables


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– For example, when tables a and b both contain columns c1,


c2, and c3, the following join compares the corresponding
columns from the two tables:
... a LEFT JOIN b USING (c1,c2,c3) ...

• NULL: Used to find rows with no counterpart in other table


– No matching row for the right table of LEFT JOIN gives a
NULL result.
n nse to
A 1
– Example:
3 % e lice
SELECT table1.id * FROM table1 cl%
C bl
I n f e ra
LEFT JOIN table2 20 tran s
ON table1.id=table2.iddilla
% n-
a n o
WHERE table2.id B ISob NULL s a d eฺ
ra x) h t Gu a i
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
The USING Y example us would also use the following to indicate table relationships:
@ in the slide
l l a
... ON a
b di
a.c1=b.c1 AND a.c2=b.c2 AND a.c3=b.c3 ...
o
ฺb is no matching row for the right table in the ON or USING part of a LEFT JOIN, a row
If lthere
e
ya with all columns set to NULL is used for the right table.
(
The example in the slide finds all rows in table1 with an id value that is not present in table2
(that is, all rows in table1 with no corresponding row in table2). This assumes that
table2.id is declared NOT NULL.
For more information about JOIN syntax, see the MySQL Reference Manual:
http://dev.mysql.com/doc/refman/5.5/en/join.html.

MySQL for Beginners 11 - 14


Table Name Aliases

• Table reference can be aliased:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– tbl_name AS alias_name
– tbl_name alias_name
— AS keyword is useful but is optional.

• Examples:
mysql> SELECT t1.Name, t2.CountryCode
-> FROM Country AS t1, City AS t2
to
-> WHERE t1.Name = t2.Name;
A 1n ense
OR
C 3% le lic
mysql> SELECT t1.Name, t2.CountryCode
n c l% erab
-> FROM Country t1, City t220
I n s f
i l l a% on-tra
bad s a n eฺ
-> WHERE t1.Name = t2.Name;
o
B ha
d r a x ) G uid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
The exampleYa in the @ co joins
slide u e Country and City tables where the countries have a city
sthe
with the same i a The Country table is selected and given an alias of t1, and City is
llname.
selected
d
baand given an alias of t2. The query results in a list of country names and codes:
ฺ b o
l+------------+-------------+
a e
y | Name
( | CountryCode |
+------------+-------------+
| Djibouti | DJI |
| Mexico | PHL |
| Gibraltar | GIB |
| Armenia | COL |
| Kuwait | KWT |
| Macao | MAC |
| San Marino | SMR |
| Singapore | SGP |
+------------+-------------+
8 rows in set (0.47 sec)

MySQL for Beginners 11 - 15


Quiz

Inner joins identify combinations of matching table rows from


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

two tables, as well as the instances where a row in one table


has no match in another table.
a. True
b. False

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 11 - 16


Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Explain the concept of a join


• Use the JOIN keyword to query multiple tables
• Execute outer and inner joins

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 11 - 17


Practice 11-1 Overview:
Perform Inner and Outer Joins
This practice covers performing:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Inner joins by using the INNER JOIN keyword


• Outer joins by using the LEFT JOIN and RIGHT JOIN
keywords

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 11 - 18


Practice 11-2 Overview:
Create Queries Requiring Joins
This practice covers constructing join queries to answer
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

specific questions.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 11 - 19


Practice 11-3 Overview:
Additional Optional Practice
This practice covers in-depth extensions to the questions in
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Practice 11-2.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 11 - 20


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Table Subqueries

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(
Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Recognize the different types of subqueries


• Use multiple methods for performing nested queries
(subqueries)
• Explain and perform the process of converting subqueries
to joins

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 12 - 2


Subquery: Overview

A subquery is a query nested inside another query. It is:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• A powerful tool that can be used in many SQL statements


• An alternative to a join
• Always enclosed in parentheses ( )
• Also known as an inner query
• Executed as part of the main or outer query to
A 1n ense
• Determined by the type of table to be queried 3% l ic
C bl e
• Discarded after execution (similar to aIn cl% feratable)
temporary
2 0 ans
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
A subquery co within
Yacan be@nested u se a variety of SQL statements. This course focuses on
i
subqueriesdthatllaappear in SELECT statements.
b o ba
a e lฺ
( y

MySQL for Beginners 12 - 3


Basic Subquery: Example

mysql> SELECT Language


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Main/outer query
-> FROM CountryLanguage
-> WHERE CountryCode = (SELECT Code
-> FROM Country
-> WHERE Name='Finland');
+----------+
| Language | Subquery/
Inner query
+----------+
to
| Estonian |
A 1n ense
| Finnish |
C 3% le lic
| Russian |
n c l% erab
| Saame |
2 0I ansf
a% on-tr
| Swedish |
i l l
bad s a n eฺ
+----------+
o
B ha
d r a x ) G uid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
The example Ya in the @ co shows
slide u sehow a simple subquery works. You use the two tables,
Country and d i la
lCountryLanguage (from the world_innodb database), to find the languages
spoken o b
inaFinland. It does not combine the tables as in a join, but uses separate, nested
l ฺ b
yae
queries to provide a result.
(

MySQL for Beginners 12 - 4


Advantages of Using a Subquery

• Subqueries are useful in cases when a join does not work


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

or is not optimal.
• SQL statements with subqueries are generally more
structured.
– Puts the “S” in “SQL”
• SQL is similar to the English language
– Like a subordinate clause, it is read from the inside -> n
out: to
A 1 ense
— Focuses on subquery first, and then moves to analysis
C lic
3% oflethe
outer query
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
SubqueriesYaare useful
@ coin cases
u sewhere a join cannot solve a problem, or where it is easier to
d
use a nested i la instead of a join. SQL statements with subqueries epitomize the meaning
lquery
o ba Query Language.
of Structured
b
a e lฺ
( y

MySQL for Beginners 12 - 5


Placement of Subqueries

Subqueries can be placed in different locations in a SELECT


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

statement:
• Column designation/list
– Example:
mysql> SELECT 1 AS a, (SELECT 1+1) AS b;
+---+---+
| a | b |
+---+---+ to
| 1 | 2 | A 1n ense
+---+---+
C 3% le lic
1 row in set (0.11 sec) cl% rab In nsfe
2 0
• FROM clause
i l l a% on-tra
• WHERE clause o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
b o ba
l ฺ
(y ae

MySQL for Beginners 12 - 6


Subquery Categories

• Non-correlated:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Does not reference outer query


– Has no dependencies on outer query
– Can stand alone (run the query on its own)
• Correlated:
– References columns in the outer query
to
– Is dependent on outer query A 1n ense
3 % e lic
– Cannot stand alone l C
% rabl
c
2 0In ansfe
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 12 - 7


Non-Correlated Subquery: Example

mysql> SELECT Name FROM City WHERE CountryCode IN


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-> (SELECT Code FROM Country


-> WHERE Continent = 'Oceania');
+--------------------+
| Name |
+--------------------+
| Tafuna |
| Fagatogo |
| Sydney |
...

AND THE STAND-ALONE SUBQUERY...


n e to
mysql> SELECT Code FROM Country 1
A icen s
%
3 le l
-> WHERE Continent = 'Oceania'; C
l% erab
n c
0I ansf
+------+
| Code | 2
% n-tr
+------+
i l l a
| ASM |
b a d a no
| AUS |
B o as i d eฺ
...

n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y example
The first query @ in the usslide uses a non-correlated subquery to list the names of all the
l l a
i table that correspond with countries in the Country table that are part of the
cities in thedCity
continent
o b a
of Oceania. First, the inner query (subquery) finds all the country codes by
l ฺ b
yae
continent. The outer query then selects the city names to go with each code in the City table.
( Because the subquery does not reference the City table (in the outer query), it is not a
correlated subquery.
The second example in the slide demonstrates that the first subquery is non-correlated
because it can be run as a stand-alone query.

MySQL for Beginners 12 - 8


Correlated Subquery: Example

mysql> SELECT Country.Name,


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-> (SELECT COUNT(*) FROM City


-> WHERE CountryCode = Country.Code)
-> AS CityCount FROM Country;
+----------------------+-----------+ Values from
| Name | CityCount | outer table
+----------------------+-----------+
| Aruba | 1 |
| Afghanistan | 4 | to
| Angola | 5 | A 1n ense
| Anguilla | 2 |
C 3% le lic
... cl% rab In nsfe
2 0
– The WHERE expression makes the
i l l a%subquery n - tra correlated;
values for the expression amust d be o
nsupplied by the outer
o b a ฺ
query for the subquery
r a B to execute.
) h as uide
j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
a
The queryYexample @ cothe slide
in u seuses a correlated subquery to count the number of cities in the
i a a matching country code to those in the Country table. The outer query
llhave
d
City table that
ba the country names and their respective city counts. The subquery reference to
b o
then selects
lฺ Country table from the outer query is what makes it a correlated subquery. Because of
y a e
the
( this reference, this subquery cannot be executed as a stand-alone query. If you try to run the
subquery as a stand-alone statement, you get an error:
mysql> SELECT COUNT(*) FROM City
-> WHERE CountryCode = Country.Code;
ERROR 1054 (42S22): Unknown column 'Country.Code' in 'where clause'

MySQL for Beginners 12 - 9


Subquery Result Table Types

Subqueries can return different amounts and types of table


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

data.
• Scalar: Zero or one row, with a single column:

• Row: Zero or one row, with one or more columns:

• Column: Zero or more rows, with one column: to


A 1n ense
C 3% le lic
n c l% erab
• Table: Zero or more rows, with multiple 0I columns: n s f
2
i l l a% on-tra
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
The type Y
a returned
of table@ co byuthe sesubquery determines how it can be used, and which
i a used by the outer query to interact with the table returned by the subquery.
llbe
d
operators can
baouter query has finished executing, the tables returned by any subqueries are
Whenothe
e lฺ b
discarded, making a subquery act like a temporary table with statement scope (which means
( y a that the server frees up any storage allocated to the subquery results after the statement has
finished execution).

MySQL for Beginners 12 - 10


Scalar Subqueries

• Go almost anywhere a scalar value is allowed, such as:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Function parameters
– Mathematical operators
• Example:
mysql> SELECT Name FROM City
-> WHERE Population >
-> (SELECT Population FROM City
o
-> WHERE Name='Tokyo'); 1 n nse t
% A ice
+------------------+
C 3 l e l
l% erab
| Name |
+------------------+
I n c f
| São Paulo |
2 0 n s
| Jakarta |
i l l a% on-tra
ad a n ฺ
| Mumbai (Bombay) |
| Shanghai |
o b
...
r a B has uide
a n d mx) nt G
A lej © 2012,
a d yฺ uditseaffiliates. All rights reserved.
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


You can use Y subqueries@ as ufunction s parameters, mathematical operators on subqueries that
i l
evaluate todnumeric l a values, and so forth. The example in the slide shows how to use a scalar
subqueryo b aas part of a WHERE clause condition. It is being used to find the population of Tokyo
l ฺ b
yae
as the value to be used for the outer query WHERE clause, which is looking for the cities with a
( population greater than that of Tokyo.
If you execute the subquery from the example in the slide as a stand-alone statement, you
see that it yields a single, scalar value:
mysql> SELECT Population FROM City WHERE Name='Tokyo';
+------------+
| Population |
+------------+
| 7980230 |
+------------+
1 row in set (0.00 sec)

MySQL for Beginners 12 - 11


Subquery Type/Placement Chart

Cross-reference types with placement:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Placement Scalar Row Column Table

Column/Select list X

FROM X X X X

WHERE: = X X
to
WHERE: <, > X X
A 1n ense
3 % e lic
WHERE: IN, ALL,
X l C
% X rabl
c
0In ansfe
ANY, SOME
2
X la% X -tr X X
WHERE: EXISTS
i l o n
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
The chartY
a o the
cshows secross-reference of usage between subquery table result
@
in the slide
la
llocations u
types and the
a d i in a SELECT statement where each type is allowed. For example, it
shows
b o b
that only a scalar subquery result is allowed in the column designation of a SELECT
l ฺ
yae
statement. However, all types of subquery table results are allowed in the FROM portion of a
( statement. Additional explanation and examples are provided later in this lesson.

MySQL for Beginners 12 - 12


Column Designation Subquery

• Runs once for each row of the subquery result


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Correlated example:
mysql> SELECT Name,
-> (SELECT MAX(Population) FROM City
-> WHERE City.CountryCode = Country.Code)
-> AS LargestCity
-> FROM Country;
o
n nse t
+----------------------+-------------+
| Name | LargestCity |
1
+----------------------+-------------+
3 %A e lice
| Aruba | 29034 |
l % C bl
ra
| Afghanistan | 1780000 |
| Angola | 2022000 |
I n c f e
| Anguilla | 961 |
20 tran s
| Albania | 270000 | %
lla non-
| Andorra |
d
21189 |i
| Netherlands Antilles |
... B oba as a ideฺ
2345 |

n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
The outerY query is @run onceufors each row of the result retrieved from the subquery (each result
l l a
must be one
b a dicolumn and a maximum of one row).
Because
l ฺ b o of the subquery reference to the outer query table, the example in the slide is a
( yaecorrelated subquery. It requires information from the outer query (Country table) to complete
the subquery before the outer query can be run.
Note: When the subquery is in the column designation, a table name alias is required. One
way to accomplish this is with the AS clause, as shown in the example in the slide.

MySQL for Beginners 12 - 13


FROM Subquery

• A FROM subquery creates a derived table:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Special type of subquery that is used only in the FROM clause


• The subquery must be given a table alias.
• Example:
mysql> SELECT AVG(cont_sum)
-> FROM (SELECT Continent, SUM(Population)
o
-> AS cont_sum FROM Country
1 n nse t
-> GROUP BY Continent)
3 %A e lice
l % C bl
-> AS t;
I n c f e ra
+----------------+
20 tran s
| AVG(cont_sum) | %
lla non-
+----------------+
d i
| 868392778.5714 |
+----------------+ Bo
ba s a eฺ
ra x) h t Gu a i d
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
A subquery Y (that @ us table) can be used in the FROM clause of a SELECT
creates a derived
statement. d l l a
A iderived table is a special type of subquery that appears only in the FROM clause.
Derivedo b a
tables are sometimes called virtual tables or inline views.
l ฺ b
( yaeEvery table that appears in a FROM clause must have a name, so a subquery in the FROM
clause must be followed by a table alias.
In the query example in the slide, the average of the sums of the population of each continent
is determined. SELECT in the FROM clause is a table subquery, even if not all of its values are
used by the outer query as displayed in the example, where the Continent column selected
by the subquery is not used by the outer query.
Note: When the subquery is in the FROM clause, a table name alias is required. Subqueries in
FROM clauses cannot be correlated with the outer statement.
For information about optimization of FROM subqueries, see the MySQL Reference Manual:
http://dev.mysql.com/doc/refman/5.6/en/from-clause-subquery-optimization.html.

MySQL for Beginners 12 - 14


WHERE Subquery

• Most common location for subqueries:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Per type/placement chart


– All table type results can be obtained.

Placement Scalar Row Column Table

Column/Select list X

FROM X X X X
to
WHERE: = X X
A 1n ense
3 % e lic
WHERE: <, > X X
l C
% rabl
c
In nsfe
2 0
a% on-tra X
WHERE: IN, ALL,
X
ANY, SOME
i l l
o badX s a n X eฺ X X
WHERE: EXISTS
a B h a u i d
a n dr mx) nt G
A lej © 2012,
a d yฺ uditseaffiliates. All rights reserved.
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


Subqueries Y are most@ commonlyus placed in the WHERE location in a query statement. As shown
l l a
b a di type/location chart, WHERE has the maximum options available with regard to
in the subquery

l ฺ b o table results.
the types of

( yae

MySQL for Beginners 12 - 15


WHERE Subquery with Operators

• Operators: =, <, >


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Compares outer query with subquery results


• Example:
mysql> SELECT Continent, Name, Population
-> FROM Country c
-> WHERE Population = (SELECT MAX(Population)
-> FROM Country c2
-> WHERE c.Continent = c2.Continent
n e to
-> AND Population > 0);
+---------------+--------------------+------------+ 1
A icen s
| Continent | Name | Population | %
3 le l
+---------------+--------------------+------------+ C
| 18886000 cl| % rab
0I a|| nsfe
n
| Oceania | Australia
| South America | Brazil
2
| 170115000

tr |
|%
| Asia | China | 1277558000
i l l a n -
no |
| Africa | Nigeria 111506000
| Europe
a d ||a146934000
| Russian Federation
b 278357000ฺ |
o as
| North America | United States
B ide
a h
+---------------+--------------------+------------+
r ) u
j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
Yacondition o these=, <, or > operator compares the outer query to the subquery
cusing
The WHERE
l l a @ u
ad
results as an ioperand.
In theb o b
correlated subquery example in the slide, the country on each populated continent that
l ฺ
( yaehas the largest population is calculated. The value of the Continent column (which appears in
the outer query) is used to limit which rows to consider for the MAX() calculation in the
subquery. The table aliases c and c2 are used in the example. This is necessary because the
columns that are used to correlate values from the inner and outer queries come from
different references to the same table, and they have the same name.

MySQL for Beginners 12 - 16


Subqueries in Comparisons

Constructs commonly used in the WHERE clause:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• IN and NOT IN
• ANY
• ALL
• SOME
• EXISTS and NOT EXISTS to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @ o sinedetail in the following slides.
areccovered
These constructs
l l a u
ad i
o b
e l ฺb
( ya

MySQL for Beginners 12 - 17


WHERE with IN or NOT IN

• IN is functionally equivalent to = ANY.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• It answers the question, “Does this value appear in the


subquery?"
• Example of IN:
mysql> SELECT Name, Population FROM City
-> WHERE CountryCode
-> IN(SELECT Code FROM Country
to
-> WHERE Continent = 'Europe')
A 1n ense
-> ORDER BY Name; 3 % e lic
+----------------------+------------+
l C
% rabl
n c fe
+----------------------+------------+0I
| Name | Population |
2 n s
| A Coruña (La Coruña) |
l
243402
l a % | n-tra
| Aachen | i
d 243825 n||o ฺ
|ba 161161 a
| Aalborg
B o as ide
...
r a ) h u
j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
When IN Y
a withcoa subquery, se it is functionally equivalent to = ANY. (Note that the equal
is used@ u
llofa the equivalence.) Many consider IN to be more readable than = ANY,
i
“=” sign is part
d
because
b o bawhat you really want to know from the outer query is if the requested value appears
inlฺthe subquery. The condition is true for rows in the outer query that match any row returned
e
( y a by the subquery.
The NOT IN construct is the opposite of IN, and is true for rows in the outer query that match
no rows returned by the subquery.
The example in the slide uses the IN keyword for a subquery that returns the country codes
for European countries, which are then used in the outer query to return the population of
each of these countries.

MySQL for Beginners 12 - 18


WHERE with ALL, ANY, and SOME

• Allow quantified comparison with multiple rows:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Required for a comparison between a scalar value and a


column subquery
• Example of ALL:
mysql> SELECT Name FROM City
-> WHERE Population >
-> ALL(SELECT Population FROM City
to
-> WHERE CountryCode = 'CHN'); A 1n ense
+-----------------+ 3 % e lic
l % C bl
| Name |
c r a
+-----------------+
2 0In ansfe
a% on-tr
| São Paulo |
| Mumbai (Bombay) | i l l
| Seoul
+-----------------+Bo
|
bad s a n eฺ
d r a x) ha Guid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
You mustY
a
@ co comparison
use a quantified u se to compare between a scalar value and a subquery
i l l
that returnsdseveral
a rows of data in a single column (a column subquery). The quantifier
keywordso b aALL, ANY, and SOME allow comparison with multiple rows.
l ฺ b
( yaeUsing the ALL construct in a comparison with a column subquery limits the result set to only
those rows where the comparison is true for all values produced by the subquery.
Consider the statement in the example in the slide that returns the names of countries that
have a population greater than all the cities in China.
Note: In the example statement, if you use the ANY construct instead, it shows all cities that
are larger than any Chinese city (including all cities larger than the smallest city in China).

MySQL for Beginners 12 - 19


ANY: Example

• Allows any qualifying subquery values


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example:
mysql> SELECT Name
-> FROM Country
-> WHERE Continent = 'Europe'
-> AND Code = ANY (SELECT CountryCode
-> FROM CountryLanguage
o
-> WHERE Language = 'Spanish')
1 n nse t
-> ORDER BY Name;
3 %A e lice
+---------+
l % C bl
| Name |
I n c f e ra
+---------+
20 tran s
| Andorra |
%
lla non-
| France |
d i
ba s a
| Spain |
| Sweden |
B o a i d eฺ
+---------+
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y using
Comparisons @the keywordus ANY (as the name implies) succeed for any values in the
l l a
b a di found by the subquery, which succeeds in the comparison.
column of data

l ฺ o subquery example in the slide finds the countries on the European continent and,
Thebcolumn

( yaefor each one, tests whether the country is among the worldwide list of countries where
Spanish is spoken.
The example in the slide can also be done using the IN keyword instead:
mysql> SELECT Name FROM Country
-> WHERE Continent = 'Europe'
-> AND Code IN(SELECT CountryCode
-> FROM CountryLanguage
-> WHERE Language = 'Spanish') ORDER BY Name;
+---------+
| Name |
+---------+
| Andorra |
| France |
| Spain |
| Sweden |
+---------+

MySQL for Beginners 12 - 20


ANY: Example Subquery

Run a subquery to confirm results:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT CountryCode


-> FROM CountryLanguage
-> WHERE Language = 'Spanish‘;
+-------------+
| CountryCode |
+-------------+
| ABW |
| AND |
...
| USA | to
| VEN |
A 1n ense
3% le lic
| VIR |
+-------------+
C
l% erab
28 rows in set (0.00 sec)
n c
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 12 - 21


WHERE with EXISTS and NOT EXISTS

• Tests whether a subquery returns rows


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Example of EXISTS:
mysql> SELECT Continent FROM Country
-> WHERE EXISTS (SELECT * FROM City
-> WHERE Code = CountryCode
-> AND Population > 8000000) +---------------+
| Continent |
-> GROUP BY Continent; to
1n ense
+---------------+
+---------------+
| Continent |
| Asia |
A
% e lic
| Europe |
C 3
% rabl
+---------------+ | North America |
NOT EXISTS l
| Asia
| Europe
|
| result → 0In nsfe
| Africa c|

% 2 tra
| Oceania |

l non-
| North America |
i l a | Antarctica |
| South America |
d | South America |
+---------------+
4 rows in set (1.34 sec) B oba as a ideฺ +---------------+

ra x) h t Gu
7 rows in set (0.05 sec)

n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
The EXISTS Y and@ NOT EXISTSus operators merely test whether a subquery returns any rows.
l l a
b a di is true and NOT EXISTS is false.
If it does, EXISTS

l ฺ o
Thebexample in the slide checks for cities whose population is greater than eight million

( yae(subquery), and then returns a list of continents where those cities exist (outer query). If you
change the operator to NOT EXISTS, the results are different. Notice in the result set to the
right of the slide query that the original continents are still listed, along with three additional
continents. Therefore, all these continents contain cities that do not have populations greater
than eight million.

MySQL for Beginners 12 - 22


Finding Table Mismatches

• Use NOT IN to find mismatches as in this example:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

SELECT Name FROM Country


WHERE Code NOT IN
(SELECT CountryCode FROM CountryLanguage);

• Use LEFT JOIN to find mismatches as in this example:


SELECT Name FROM Country
LEFT JOIN CountryLanguage
n nse to
A 1
ON Code = CountryCode
3 % e lice
l % C bl
WHERE CountryCode IS NULL;
I n c f e ra
20 tran s
• Use joins instead of subqueries l l %
a on- where
in cases
i
performance is most important, o bad sbecause a n ฺ joins normally run
faster. r a B ha
) u ide
j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
As shownY
a o saeNOT IN subquery is used to identify countries for which no
cexample,
in the first
@ u
a in CountryLanguage.
lllisted
languages d i
are
b o ba
a e lฺ
( y

MySQL for Beginners 12 - 23


Modifying Tables by Using Subqueries

• Subquery usage is not limited to SELECT statements.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• You can use subqueries in DELETEs and UPDATEs.


• DELETE example:
DELETE FROM NACities
WHERE CountryCode IN
(SELECT Code FROM Country
WHERE LifeExpectancy < 70.0); to
A 1n ense
• UPDATE example:
C 3% le lic
UPDATE table1 SET table1field =ncl% fera
b
2 0I ans
(SELECT MAX(table2.table2field)
i l l a% on-tr
FROM table2
o b ad a n ฺ
B has =uitable2.table2field);
WHERE table1.table1field
r a de
nd yฺmx ent G )
j a
le © 2012,
2 0 A
Copyright
ฺ u tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
It is often Y
a delete
useful to@ co rowsu e on whether they match rows in another table. Also, you
sbased
can updatedrowsi lla in one table using the contents of rows in another table.
o ba statement in the example in the slide removes (from an existing table containing
ThebDELETE
a e lฺ
every North American city) all the cities located in countries where the life expectancy is less
( y than 70 years.
The UPDATE example in the slide performs a correlated subquery based on an aggregate
function applied to another table.
This can be helpful if you need to create a temporary table storing a customer ID (for a
person) and a “last order date,” while you already have another table storing all dates (of that
customers' orders).
Caution: The DELETE example in the slide was purposely based on a non-existent table. Do
not attempt to run this example on the real table in the world_inndob database, because it
removes 1846 rows from the table.

MySQL for Beginners 12 - 24


Quiz

When IN is used with a subquery, it is functionally equivalent


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to:
a. ALL
b. = ALL
c. NOT IN
d. = ANY

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 12 - 25


Subquery Tips

• You may need to run a subquery several times through the


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

data to achieve the desired result.


• A temporary table alias may be necessary.
• Subqueries are used in:
– SELECT, UPDATE, DELETE, and INSERT statement values
– FROM, WHERE, HAVING, and ORDER BY clauses
to
– Conditions that use comparison and special-purpose 1n
A e n se
operators: IN, NOT IN, ANY, EXISTS, and NOT3% EXISTSlic
l % C ble
• Arithmetic operators can appear on either I n c sidefeofraa
subquery: =, <>, <, >, <=, >=, !=. 2 0 ans
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
b o ba
elฺ
(ya

MySQL for Beginners 12 - 26


Converting Joins to Subqueries

• You can use a subquery instead of a join, for an


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

easier-to-construct query.
• Example of join versus subquery:
mysql> SELECT DISTINCT Language SELECT DISTINCT Language
-> FROM Country
OR FROM CountryLanguage
-> JOIN CountryLanguage WHERE CountryCode IN
-> ON CountryCode = Code (SELECT Code FROM Country
-> WHERE Continent='Africa';
+-----------------------+
WHERE Continent='Africa')
to
| Language |
A 1n ense
3% le lic
+-----------------------+
| Ambo | C
l% erab
| Chokwe |
n c
| Kongo |
2 0I ansf
a% on-tr
| Luchazi |
| Luimbe-nganguela | i l l
...
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya example
The first query @ co in the
u e shows the JOIN syntax, which answers the question,
sslide
d
“What are the i la
llanguages spoken in Africa?” These queries can return results only from the
outero b a In both examples,
query. only the Language column from the CountryLanguage table
l ฺ b
yae
returns results.
(

MySQL for Beginners 12 - 27


Converting Subqueries to Joins

• Joins can be more efficient than subqueries.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Convert a subquery to a join if it is running slowly.


• Example of subquery versus join:
mysql> SELECT Name FROM Country mysql> SELECT Name FROM
-> WHERE Code IN OR -> Country, CountryLanguage
-> WHERE Code = CountryCode;
-> (SELECT CountryCode
+-------------+
-> FROM CountryLanguage); | Name |
+------------------------------+ +-------------+ to
| Name | | Aruba |
A 1n ense
+------------------------------+ | Aruba
| Aruba
|
| C 3% le lic
l% erab
| Aruba |
| Afghanistan | | Aruba |
n c
| Angola | | Afghanistan |
2 0I ansf
| Anguilla |
i l l a% on-tr
| Afghanistan |

bad s a n eฺ
| Albania | | Afghanistan |
... | Afghanistan |
o
B ha uid
...
d r a x ) G
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
Yathat finds o sbetween
cmatches e
A subquery
l l a @ u tables often can be rewritten as an inner join or outer
join.
b a di
l ฺ o example in the slide uses an IN subquery to identify countries for which languages
Thebfirst

( yaeare listed in the CountryLanguage table.


To convert the subquery example to an inner join, you do the following:
• Move the CountryLanguage table named in the subquery to the FROM clause.
• The WHERE clause compares the Code column to the country codes returned from the
subquery.
• Convert the IN expression to an explicit direct comparison between the country code
columns of the two tables.
These changes result in the second (comma-separated inner join) example.
Note that this output is not quite the same as that from the subquery, which lists each
matched country just once. To list each name just once, as in the subquery, add DISTINCT to
the join (as shown in the following slide).

MySQL for Beginners 12 - 28


Converting Subqueries to Joins

Update the join to list each name only once:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT DISTINCT Name FROM


-> Country, CountryLanguage
-> WHERE Code = CountryCode;
+------------------------+
| Name |
+------------------------+
| Aruba |
| Afghanistan | to
| Angola |
A 1n ense
| Anguilla |
C 3% le lic
| Albania |
n c l% erab
0I ansf
| Andorra |
| Netherlands Antilles | 2
| United Arab Emirates |
i l l a% on-tr
| Argentina |
o bad s a n eฺ
...
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 12 - 29


Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Recognize the different types of subqueries


• Use multiple methods for performing nested queries
(subqueries)
• Explain and perform the process of converting subqueries
to joins

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 12 - 30


Practice 12-1 Overview:
Perform Different Types of Queries
This practice covers performing subqueries in the FROM and
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

WHERE clauses.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 12 - 31


Practice 12-2 Overview:
Perform Several Advanced Subqueries
This practice covers constructing more advanced subqueries to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

answer specific questions.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 12 - 32


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Exporting and Importing Data

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(
Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Export data by using a query


• Export data by using the mysqldump database backup
client
• Import data with MySQL statement files
• Import data by using the mysqlimport client program

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 13 - 2


Exporting Data

• Backups are important!


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Backup principles:
– Perform regularly.
– Provide consistent and meaningful naming scheme.
– Expire backup files.
– Include with regular system backups.
• Reasons for exporting data: to
– Copying databases from one server to another: %A
1n ense
C 3 le lic
— From within the same host
n c l% erab
— To another host 2 0I ansf
– Testing a new MySQL release i l l % real
awith n - tr
data
b a d a no
– Transferring data from B oone RDBMS s tod ฺ
eanother
ra x) h t Gu a i
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
MySQL offersY various @ methods us for exporting and importing database data. SQL statements
l l a
can be used
b a dito create (or invoke) the necessary files. There are also MySQL client programs
l ฺ b o
that assist in exporting and importing.

( yaeIt is important to back up (export) your databases in case tables are lost or damaged. If a
serious system crash occurs, you want to be able to restore your tables to the state they were
in at the time of the crash with as little data loss as possible.
Database backups are also useful for copying databases to another server. Most commonly,
a database is transferred to a server running on another host, but you can also transfer data
to a different server running on the same host. You might do this if you are testing a server for
a new release of MySQL and want to use it with some real data from your production server,
or to load the data into external applications. It is also useful for transferring data between
different RDBMSs.

MySQL for Beginners 13 - 3


Exporting with a Query

• Write query results directly into a file by using SELECT


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

with the INTO OUTFILE clause.


• Example:
SELECT * INTO OUTFILE 'D:/DataBackup/Country.txt'
FROM Country

– The name of the file indicates the location of the write.


• Default file format: n nse to
A 1
– Values are delimited by tab characters.
3 % e lice
– Lines are terminated with newlines. l % C bl
I n c f e ra
• The file format can be changed by using 20 trspecific an s INTO
l a % -
OUTFILE options.
a d il non
B ob as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y in@this way,uplace
To use SELECT s the INTO OUTFILE clause before the FROM clause.
l l a
As shownain
b dithe example in the slide, you can use the SELECT...INTO FILE to write the
contents
l ฺ b o of the entire Country table into a file named Country.txt.
( yae

MySQL for Beginners 13 - 4


Exporting with a Query: INTO OUTFILE

INTO OUTFILE changes the standard SELECT operation:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• A file is written to the server host rather than to the


executing client.
• Data is written to a new file only; there are no overwrites.
• The file contains one line per row selected by the
statement.
• The user that executes the statement must have the1FILE
n nse to
A
privilege. 3% lice C ble
• The file is created with file system access l % ra
c permissions.
I n s f e
% 20 tran
d i lla non-
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
l l a
b a di
l ฺ b o
e
(ya

MySQL for Beginners 13 - 5


Exporting with a Query: CSV Format

• Create a text file that contains information in


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

comma-separated values (CSV) format:


– Values are enclosed in double quotation marks.
– Lines are terminated by carriage returns.
• Example:
SELECT * INTO OUTFILE '/tmp/table1.txt'
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
to
LINES TERMINATED BY '\r' A 1n ense
3 % e lic
FROM table1
l C
% rabl
c
2 0In ansfe
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 13 - 6


Exporting with a MySQL Utility

The mysqldump utility “dumps” table contents in a text format.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Redirect output to a file, or store output directly in a file.


• Export tables in a variety of ways:
– Full structure
– Data only
– Table structure only
– Standard format
o
– MySQL specifics for optimized speed
1 n nse t
– Compressed 3 %A e lice
l % C bl
• Use mysqldump to dump: I n c f e ra
20of its n s
atables
– A specific database, with all orasome
l % - t r
– Multiple databases a d il non
– All databases on rthe B ob aserver
MySQL s a
i d eฺ
d a x) h Gu
j a n ฺ m e n t
e
Al ©ฺu2012, y
2 0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
a
The dumpYfile typically
@ cocontains
u seSQL statements to create the table, populate it, or both.
i
However, mysqldump
d lla can also be used to generate files in CSV, other delimited text, or XML
format. o b a
l ฺ b
( yaeThere are three ways to invoke mysqldump in a command shell:
mysqldump [options] db_name [tables]
mysqldump [options] --databases db_name1 [db_name2 db_name3...]
mysqldump [options] --all-databases

MySQL for Beginners 13 - 7


Specifying Databases to Dump

• Export an entire database (for example, the world_innodb


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

database and all its tables):


mysqldump -uusername -ppassword world_innodb

• Export specific tables (for example, the City table in the


world_innodb database):
mysqldump -uusername -ppassword world_innodb City

• Export multiple databases (for example, the world_innodb to


n e
and sakila databases): A1 ens
C 3 le % lic
mysqldump -uusername -ppassword --databases
n c l %
f e r ab
world_innodb sakila I 2 0 ans
– All databases on the MySQLilserver: l a% on-tr
d an
ba-ppassword
mysqldump -uusername
B o s d ฺ
e--all-databases
ra x) h t Gu a i
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y specify
If you do not s the entire database is dumped.
@ a tableuname,
l l a
b a di
l ฺ b o
e
(ya

MySQL for Beginners 13 - 8


mysqldump Utility Options

• Execute mysqldump --help to list all available options.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Some of the most common mysqldump options:


--opt: Optimizes mysqldump for best performance; enabled
by default
-C (--compress): Uses compression (good for slow
connection)
--tab=dir_name: Produces tab-separated text-format data
files to
n
A 1 ense
-d (--no-data): Dumps only the structures; no 3 % is e lic
data
dumped. l C
% rabl
c
In nsfe
2 0
-X (--xml): Dumps the data as well-formed
i l l a% on-traXML
--compatible=name: Works o badwith a n ฺ or older MySQL
databases
versions r a B has uide
a n d mx) nt G
A lej © 2012,
a d yฺ uditseaffiliates. All rights reserved.
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


Y the --tab
You can use @ option usto export to multiple files, with one set of files (.sql or .txt)
l l a
b a di The option value is the directory in which to write the files.
for each table.

l ฺ o
Theb--comment option writes additional information in the dump file, such as program

( yaeversion, server version, and host. This option is enabled by default. To suppress this
additional information, use --skip-comments.
The --compatible option does not guarantee compatibility with other servers. It enables
only those SQL mode values that are currently available for making dump output more
compatible. For example, --compatible=oracle does not map data types to Oracle types
and does not use Oracle comment syntax.
mysqldump does not dump the INFORMATION_SCHEMA database by default. It dumps
INFORMATION_SCHEMA only if you name it explicitly on the command line, although you must
currently also use the --skip-lock-tables option.

MySQL for Beginners 13 - 9


Dumping to a Text File

Dump databases to a text file (.txt) by using mysqldump with


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

the redirect operator (>) to indicate the file name and location:
• Example: Export the entire world_innodb database.
mysqldump -uusername -ppassword world_innodb >
world_innodb.txt

• Example: Export the City and Country tables in the


world_innodb database.
nCitynse to
1
mysqldump -uusername -ppassword world_innodb
A
Country > world_innodb.txt % lice C 3 le
• Example: Drop a table if it exists on the n c l %
target f r ab
server.
e
2 I
0database n s
– The City table in the world_innodb
a% on-t r a
i l l
d a n --add-drop-table
mysqldump -uusername b a-ppassword
world_innodb City B o a s
> world_innodb.txt i d eฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
The data Y created@ in the .txtusfile assumes that no table exists on your destination server.
l l a
b di
The --add-drop-table
afile option adds code to drop a table if it exists in the new database
whenothe is imported.
e l ฺbuse the dumped SQL, you need to connect to a MySQL server by using a client and then
( ya To
execute the statements. For example, the mysql command-line client can be used to run
SQL statements stored in a file using the SOURCE command. A complete example of the
command line might look like the last example in the slide.
To export data to the client's local machine, you can use the mysql client:
shell> mysql -uroot -p world -e"SELECT * FROM country" >
filename
For more information about the mysqldump utility, see the MySQL Reference Manual:
http://dev.mysql.com/doc/refman/5.5/en/mysqldump.html.

MySQL for Beginners 13 - 10


Text File Contents

Output from the --add-drop-table example statement:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-- MySQL dump 10.13 Distrib 5.5.16, for Win32 (x86)


--
-- Host: localhost Database: world_innodb
-- Server version 5.5.16-enterprise-commercial-advanced
--
-- Table structure for table `city`
--
DROP TABLE IF EXISTS `city`;
CREATE TABLE `city` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` char(35) NOT NULL DEFAULT '',
`CountryCode` char(3) NOT NULL DEFAULT '',
`District` char(20) NOT NULL DEFAULT '',
`Population` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`),
to
KEY `CountryCode` (`CountryCode`),

A 1n ense
CONSTRAINT `city_ibfk_1` FOREIGN KEY (`CountryCode`) REFERENCES `country` (`Code`)
) ENGINE=InnoDB AUTO_INCREMENT=4080 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
C 3% le lic
--

n c l% erab
0I ansf
-- Dumping data for table `city`
--
2
a% on-tr
INSERT INTO `city` VALUES

i l l
(1,'Kabul','AFG','Kabol',1780000),(2,'Qandahar','AFG','Qandahar',237500),(3,'Herat','

bad s a n eฺ
AFG','Herat',186800),(4,'Mazar-e-Sharif','AFG','Balkh',127800),
(5,'Amsterdam','NLD','Noord-Holland',731200),(6,'Rotterdam','NLD','Zuid-
o
Holland',593321),(7,'Haag','NLD','Zuid-Holland',440900),
B ha
...

d r a x ) G uid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 13 - 11


Importing Data

New data can be imported into a database by using a MySQL


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

(.sql) statement file, which contains all the information


needed to create tables.
• Example: Import the world_innodb database from file by
using the mysql command.
mysql -uusername -ppassword world_innodb <
world_innodb.sql

e to
1n
– Use the input operator (<) to indicate the SQL file name.
A icens
• Example: Import the data file within the mysql 3 %client.
e l
C
l% erab l
n c
SOURCE D:/DataBackup/world_innodb.sql
2 0I ansf
Caution: Do not import over an i l l a% odatabase
existing n -tr file with the
a d n
same name.
B ob as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Shell-level Yclient @ commandsudo s not require a semicolon (;) at the end of the statement.
l l a
di can also be used to import data.
A text filea(.txt)
b
l ฺ b o
e
(ya

MySQL for Beginners 13 - 12


Importing from a Data File

You should know the following characteristics of the data file:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• The column value separator


• The order of the columns
• The row separator
• The file system where the file resides
• What are the values enclosed within? (example: double
quotation marks)
to
• Are the column names specified in the file? A 1n ense
% ebefore
• Is there a header indicating rows of the tableCto3 skip l ic
c l % rabl
importing?
2 0In ansfe
• Are privileges required to access % n-tr
illa the file?
a d a no
b
o as eฺ
B
ra x) h t Gu i d
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 13 - 13


Importing with the LOAD DATA INFILE Statement

• LOAD DATA INFILE is the reverse operation of SELECT


with INTO OUTFILE.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– However, it uses similar clauses and format specifiers.


• It reads row values from a file into a table.
• Files can be in tab-delimited or comma-separated format.
• Example:
LOAD DATA INFILE 'D:/DataBackup/City.txt'
to
INTO TABLE City
A 1n ense
• MySQL assumes that the file is located on the % ehost
3server l ic
l C
% rabl
in the database data directory. c
2 0In ansfe
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Yaform@ o seDATA INFILE statement specifies only the name of the data
ofcthe LOAD
lla into which uto load the file, as shown in the example in the slide.
The simplest
i
file and thedtable
o ba for LOAD DATA INFILE is as follows, where optional parts of the statement are
Thebsyntax
a e lฺ
indicated by square brackets:
( y LOAD DATA [LOCAL] INFILE 'file_name'
[IGNORE | REPLACE]
INTO TABLE table_name
format_specifiers
[IGNORE n LINES]
[(column_list)]
[SET (assignment_list)]

MySQL for Beginners 13 - 14


Importing with LOAD DATA INFILE: CSV Format

• Import a text file that contains information in


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

comma-separated values format.


• Example:
LOAD DATA INFILE '/tmp/table1.txt'
INTO TABLE table1
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
o
n nse t
LINES TERMINATED BY '\r'
1
3 %A e lice
l % C bl
I n c f e ra
20 tran s
%
lla non-
d i
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y is given
The file name us string. On Windows, the pathname separator character is
@ as a quoted
“\”, but MySQL l l a
i treats the backslash as the escape character in strings. To deal with this
b adseparators
issue,owrite in Windows pathnames either as “/” or as “\\”. To load a file named
l ฺ b
yae
D:\mydata\data.txt, specify the file name as shown in either of the following statements:
( LOAD DATA INFILE 'D:/mydata/data.txt' INTO TABLE t
LOAD DATA INFILE 'D:\\mydata\\data.txt' INTO TABLE t
The example in the slide shows how to use a LOAD DATA INFILE statement to import a file
named /tmp/data.txt that contains information in comma-separated values (CSV) format,
with values enclosed within double quotation marks and lines terminated by carriage returns
into a table named table1.

MySQL for Beginners 13 - 15


Importing with LOAD DATA INFILE:
File Control
• MySQL file assumptions and defaults:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– File is located on the server host.


– File is in CSV format.
– Each input line contains a value for each column in the table.
• LOAD DATA INFILE clauses can control data operations:
– Skipping data file rows
– Loading specific table columns
to
– Skipping or transforming column values
A 1n ense
– Control of duplicate records/rows
C 3% le lic
– Tracking of records/rows
n c l% erab
– Control privileges 2 0I ansf
l l a % n-tr
– Data file format specification
a i
d (field o line terminators)
nand
b a ฺ
– Bo as
Whether to import NULLs
ra x) h t Gu ide
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
The FILEYprivilege usto control the import operation.
@is required
l l a
LOAD DATA
b a diINFILE can read data files that are located on the server host or on the client
host:
l ฺ b o
( yae • The MySQL server reads the file directly from the server host.
• If the statement begins with LOAD DATA LOCAL INFILE rather than with LOAD DATA
INFILE, the file is read from the client host on which the statement is issued. In other
words, LOCAL means local to the client host from which the statement is issued. In this
case, the client program reads the data file and sends its contents over the network to
the server.

MySQL for Beginners 13 - 16


Importing with a MySQL Utility

The mysqlimport utility loads data files into tables. It provides


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

a command-line interface to LOAD DATA INFILE.


• General syntax example:
mysqlimport <options> db_name <input_file>

• mysqlimport matches the file name with the table name,


and then issues LOAD DATA INFILE to load the file to
the table. to
A 1n ense
• You can name several input files. 3% le lic
• Input files must contain only data values,cand
C
l% not b
n f e r aSQL
statements. 2 0I ans
l l a % n-tr
• Tables must already exist. ad i no
B ob as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
mysqlimportY examines@ theusoptions given on the command line. It then connects to the
l l a
i each input file named in the statement, issues a LOAD DATA INFILE
server and,dfor
o
statementb athat loads the file into the appropriate table.
l ฺ b
eBecause mysqlimport works this way, to use it most effectively, you must be familiar with
(ya the LOAD DATA INFILE statement.
In the example in the slide, db_name names the database containing the table to be loaded
and input_file names the file that contains the data to be loaded.
mysqlimport uses each file name to determine the name of the corresponding table into
which the file's contents are loaded. The program does this by stripping off any file name
extension (the last period and anything following it) and using the result as the table name.
For example, mysqlimport treats a file named City.txt or City.dat as input to be
loaded into a table named City. After determining the table name corresponding to the file
name, mysqlimport issues a LOAD DATA INFILE statement to load the file into the table.
mysqlimport is not intended for processing dump files that consist of SQL statements.
By default, input files are assumed to be the same format as the LOAD DATA INFILE
statement.

MySQL for Beginners 13 - 17


mysqlimport Utility Options

• Execute mysqlimport --help to list all options.


• Some of the most common mysqldump options:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

--lines-terminated-by=string: Specifies the character


sequence that each input line ends with. The default
is \n.
--fields-terminated-by=string: Specifies the delimiter
between data values within input lines. The default
is \t (tab).
to
--fields-enclosed-by=char: Can be used if values A 1nare ense
quoted. Common value is the double quote character C 3% le(").lic
n c l% erab
--ignore or --replace: Can be used 0I to handle n s f input
2 tra are already
records that contain unique key
i l l a%values -that
n
present in the table b a d a no
B o as i d eฺ
--local: Allows use
n d ) h data
raof a xlocal t G u on the client host
file
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
The options Y listed@ usgive you the flexibility to load input files containing data in a
in the slide
l l a
b a di
variety of formats.

l ฺ b o
( yae

MySQL for Beginners 13 - 18


mysqlimport Option: Examples

Examples:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysqlimport --lines-terminated-by="\r\n"
world_innodb City.txt
mysqlimport --fields-terminated-by=","
--lines-terminated-by="\n"
world_innodb City.txt
to
1n ense
mysqlimport --fields-enclosed-by='"'
A
world_innodb City.txt
C 3% le lic
n c l% erab
• Import the City.txt file into the City 0I table n in
s f the
2
world_innodb database. i l l a% on-tra
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya in @ thec
o san e input file named City.txt into the City table in the
The examples u
slide load
lladatabase using different options.
world_innodbd i
b o ba
a e lฺ
( y

MySQL for Beginners 13 - 19


Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Export data by using a query


• Export data by using the mysqldump database backup
client
• Import data with MySQL statement files
• Import data by using the mysqlimport client program

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 13 - 20


Practice 13-1 Overview:
Quiz
This practice covers answering questions about exporting and
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

importing data.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 13 - 21


Practice 13-2 Overview:
Export Files Using a Query
This practice covers using SELECT with INTO OUTFILE
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

statement for exporting database data.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 13 - 22


Practice 13-3 Overview:
Import Files from a Data File
This practice covers the use of a LOAD DATA INFILE
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

statement for importing database data.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 13 - 23


Practice 13-4 Overview:
Back Up Database Files with a Utility
This practice covers the use of the mysqldump utility for
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

backing up a database.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 13 - 24


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

MySQL Graphical User Interface Tools

to
A 1n ense
Workbench and Enterprise Monitor 3%
e l ic
l C
% rabl
c
2 0In ansfe
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(
Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Explain the primary features of the MySQL Workbench


GUI tool
• Use the MySQL Workbench tool
• Explain the primary features of the MySQL Enterprise
Monitor GUI tool

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 5 - 2


MySQL GUIs

• MySQL provides several graphical user interface tools.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• MySQL Workbench and MySQL Enterprise Monitor are


of considerable assistance to all MySQL users.
• This course provides only an overview of these GUI tools.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
For more Y
a o MySQL
cabout se Workbench, MySQL Enterprise Monitor, and other GUI
@
information u
la website, as well as other MySQL courses.
lMySQL
d
tools, see thei
b o ba
a e lฺ
( y

MySQL for Beginners 5 - 3


MySQL Workbench

MySQL Workbench is a unified GUI tool for database


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

architects, developers, and DBAs for managing the MySQL


server and data.
• Three separate functional modules:
– SQL Development
– Data Modeling
– Server Administration
• Two versions of Workbench: to
– Community Edition (OSS) A 1n ense
3 % e lic
– Standard Edition (SE)
l C
% rabl
c
• OS platforms: 2 0In ansfe
– Windows i l l a% on-tr
– Linux
o bad s a n eฺ
– Mac OS X r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @iscoused utoswrite
MySQL Workbench
e and execute SQL queries and scripts, edit data, visually
d i
design database lla models, and manage the MySQL server.
o ba modules are covered in detail in the following slide.
Functional
b
a e lฺ
( y MySQL Workbench is available in two versions:
• Community Edition (OSS):
- Foundation of all Workbench editions
- Full-featured, powerful database management tool
- Open-source GPL (general public license), available free from the MySQL website
• Standard Edition (SE):
- Commercial extension of the OSS version
- Advanced features
- Available for purchase from the MySQL website
For information about the requirements for installing MySQL Workbench, refer to the MySQL
Workbench Reference Manual at http://dev.mysql.com/doc/workbench/en/index.html.
You can also download MySQL Workbench from:
http://dev.mysql.com/downloads/workbench/.

MySQL for Beginners 5 - 4


MySQL Workbench: Functional Modules

• SQL Development
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Edit and execute SQL queries and scripts.


– Create or alter database objects.
– Edit table data.
• Data Modeling
– Extended entity-relationship (EER) modeling
– Edit and execute SQL queries and scripts.
– Design, generate, and manage databases. to
A 1n ense
• Server Administration C 3% le lic
– Start and stop the server. n c l% erab
– Edit database server configuration. 2 0I ansf
l l a % n-tr
– Manage users. a i
d a no
– Import and export data.
b
o as eฺ
B
ra x) h t Gu i d
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
The SQL Y @ module
Development us replaces the MySQL Query Browser tool. The Server
l l a
b a di module replaces the MySQL Administrator tool.
Administration

l ฺ o information about Workbench, see the MySQL website at


Forbmore

( yaehttp://mysql.com/products/workbench/.

MySQL for Beginners 5 - 5


MySQL Workbench: Primary GUI Window
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
a MySQL
When youYinvoke@ co Workbench,
u se the top-level GUI opens to show the current
i
informationdfor
a module. Click a module title to access a specific tool and complete the
lleach
tasks.oba
e l ฺb
( ya

MySQL for Beginners 5 - 6


MySQL Workbench: SQL Development Window

Enter SQL
statements.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Schemas/
Schema databases
navigation and tables to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya the
You can access @ co Editor
SQL u sefrom the main window of the MySQL Workbench GUI, to use
d i lla database objects.
SQL to manipulate
Note:b o baSQL Development module was covered in the lesson titled “Basic Queries.”
The
a e lฺ
( y

MySQL for Beginners 5 - 7


MySQL Workbench: Data Modeling Module

• Enables users to model, design, generate, and manage all


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

types of databases
• Features a model-driven database design:
– Modeling the purpose and relationships of data for existing
and new databases
– Best means for representing the definition of data elements
– Use of extended entity-relationship (EER) diagrams
to
• Includes everything a data modeler needs for: A 1n ense
– Creating extended entity-relationship (EER) models C 3% le lic
n c l% erab
– Change management
2 0I ansf
– Documentation i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
The DataY
a o ofsMySQL
cmodule e
Modeling
l l a @ u Workbench features a model-driven database design

b a di
approach acknowledged by experienced data professionals as the best method for managing

l ฺ b o
the capture, definition, and implementation of data throughout an organization. It models the

yae
use and relationships of data that exist in the database. This applies to both existing systems
( and the ones that are in the process of being constructed. It includes everything a data
modeler needs for creating complex ER models, and also delivers key features for performing
difficult change management and documentation tasks that normally require much time and
effort.
Models are the best means for representing the definition of data elements that support the
various data stores found throughout an enterprise. This being the case, it is not surprising
that most IT organizations use practices such as extended entity-relationship diagramming or
other forms of modeling to capture and preserve their data structures.

MySQL for Beginners 5 - 8


MySQL Workbench: Data Modeling Features

These features are in the following categories:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Database design
– Allows you to create one or multiple models
– Displays different views of the objects (such as tables, views,
and stored procedures)
• Forward and reverse engineering: Generates all the
SQL code necessary to create a physical database on a
target server to
n
A 1 ense
• Database maintenance: Compares a data model 3% against
e l ic
a target MySQL server, and performs a synchronization l C
% rabl
c
between the two 2 0In ansfe
i l l a% on-tr
• Reporting and documentation:
o bad s aProvides n ฺ the
e
point-and-click utility r a B documents
that h a u iddatabase designs
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
The SQL Y
a
@
Developmentcomoduleu seensures out-of-the-box success for a variety of users within
d i lla This feature set supplies many benefits during the model-driven data
modern enterprises.
o ba process.
management
b
a e lฺ
( y

MySQL for Beginners 5 - 9


MySQL Workbench: Data Modeling Window

EER
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

diagrams

Schemas/
User databases
navigation and tables

to
A 1n ense
C 3% le lic
Additional panels:
n c l%Schema
f e r ab
Privileges,
2 I Scripts,
0SQL n s and
a% on-t Model r a
Notes
i l l
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
a
When youYfirst open
o se(and you have added an EER diagram), the default layout of
cWorkbench
i l l ais displayed uas shown in the slide.
@
o b ad
the application
MySQL b Model and other open windows (such as EER Diagram) appear as tabbed windows
l ฺ
( yaein the main window (top-left). Functional palettes appear as small vertically placed windows
(on the left). They are tabbed and docked.

MySQL for Beginners 5 - 21


MySQL Workbench: Data Modeling Panels

The panels within the MySQL Model window are:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• EER Diagram: Contains EER diagrams, or existing model


diagrams, for database models in Workbench
• Physical Schemata: Shows the active schemata and the
objects that they contain
• Schema Privileges: Manages MySQL users and
privileges to
• SQL Scripts: Loads and modifies SQL scripts %A1 icen
n se
C 3 le l
• Model Notes: Writes project notes thatnare c l%saved
f e r abwith
your project 2 0I ans
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
For each Y
a panels,
of these@ co objects
u se can be added to a project by clicking the appropriate Add
d
<Object> icon. i llaOn this page, you can use the shortcut menu (accessed by right-clicking the
o
objects)
b btoa rename, edit, cut, copy, or delete the objects.
a e lฺ
To expand and contract the Physical Schemata panel, click the arrow on the left of the title
( y bar. When the panel is expanded, all the schemata that are currently loaded are displayed.
The Physical Schemata panel is divided into the following sections:
• Tables
• Views
• Routines
• Routine Groups
If you created your project from a SQL script and plan to create an ALTER script, you can add
the original script in the SQL Script panel, because you need it to create an ALTER script.

MySQL for Beginners 5 - 11


MySQL Workbench: Data Modeling EER Diagram
Functional
tool palettes
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
EER
3 l ic bars
% e Scroll
diagram
l C
% rabl for viewing
c
2 0In ansfe diagram

i l l a% on-tr
Vertical
o b ad a n ฺ
toolbar
r a B has uide
a n d mx) nt G
A lej © 2012,
a d yฺ uditseaffiliates. All rights reserved.
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


A canvasY is provided us EER diagrams, or existing model diagrams, that correspond
@ to contain
i l
to databasedmodelsl a in Workbench.
b a
o toolbar is provided for manipulation of the diagram.
b
Alvertical

( yae Functional tool palettes:
• Bird’s Eye navigator palette: Gives you an overview of the objects placed on an EER
diagram canvas. For this reason, it is most useful when an EER diagram is active. Any
objects that you have placed on the canvas are visible in the navigator.
• Catalog palette: Shows all the schemata that are present in the Physical Schemata
panel of the MySQL Model window. Opening a schema or database displays the
following folder icons: Tables, Views, and Routine Groups.
• Properties Palette: Displays and edits the properties of objects on an EER diagram. It
is especially useful for editing display objects such as layers and notes.
• Additional palettes are also available.

MySQL for Beginners 5 - 12


MySQL Workbench:
Server Administration Window
Server status
indicators
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Administration
features menu

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
Administration i l l a% on-tr
features
o bad s a n eฺ
subwindow
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
b o ba
elฺ
(ya

MySQL for Beginners 5 - 13


MySQL Workbench:
Server Administration Module Features
These features are in the following categories:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Service control: Enables you to start and stop the MySQL


server and view the startup message log
• Server configuration: Enables you to view and edit the
MySQL configuration file
• User administration: Enables you to create user accounts
and assign roles and privileges
• Server connections: Enables you to display the connections
to
to MySQL Server
A 1n ense
• Data export and import: Includes visual toolsC 3% le lic
for
% rab
mysqldump ncl e 0 I s f
• Server logs: Enables you to display 2 n
tralog file entries
i l l a% server n -
o of basic “health”
• System status: Provides an b a d a nview
instant
indicators B o as i d eฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
You mustY have a@ usto log in and to restrict access to various resources.
user account
l l a
i immediate view of the basic health indicators and counters in a MySQL
You can get
b a dan
l ฺ b o
environment. Simple graphs enable DBAs to easily see memory usage, connection usage, hit

( yaerates, and more. System status displayed includes:


• CPU utilization
• Memory usage
• Connection Health: For server health, the following are displayed:
- Connection Usage
- Traffic
- Query Cache Hit Rate
- Key Efficiency

MySQL for Beginners 5 - 14


MySQL Enterprise Monitor

MySQL Enterprise Monitor (MEM) is a web-based monitoring


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

and advising system that significantly improves productivity.


MEM:
• Runs completely within the corporate firewall
• Recommends best practices to:
– Eliminate security vulnerabilities
– Improve replication
to
– Optimize performance and more A 1n ense
• You can access MEM from the MySQL website: C 3% le lic
c l% and r b
aMySQL
– It is available with MySQL Enterprise n
0I ans
Edition f e
2
Cluster Carrier Grade Edition.
i l l a% on-tr
– A “trial” version of the MEM
o badand n ฺ demonstrations
prerecorded
a
are also available.a B
r ) h as uide
j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
YaMEM@to:co use
You can use
i a MySQL servers in a scale-out environment
llmore
• Manage d
ba your current MySQL servers
lฺ
• b o
Tune
a e
y • Find and fix problems with your MySQL database applications, before they can become
( serious problems or costly outages
Because MEM runs completely within your corporate firewall, it proactively monitors your
enterprise database environments. Then MEM provides expert advice on how MySQL can
tighten security, optimize performance, and reduce down time of your MySQL-powered
systems. MEM accomplishes all this while reducing DBA time and effort.
For more MEM information and demonstrations, see the MySQL website at
http://mysql.com/products/enterprise/monitor.html.

MySQL for Beginners 5 - 15


Enterprise Monitor Features

• Enterprise Dashboard: Enables you to manage all


MySQL servers from a consolidated console
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Server/group management: Supports auto-detection,


grouping, and monitoring of replication and scale-out
topologies
• Monitoring page: Enables you to perform an “at-a-glance"
global health check of key systems
• MySQL and custom advisors and rules: Enables 1you
n to nse to
A
enforce MySQL best practices 3% lice C ble
• Advisor rule scheduler: Enables youIntoc schedule l % ra
s f e
unattended operations % 20 tran
d i lla non-
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
MEM providesY a rich us Dashboard that contains "pages" that enable you to have
@ GUI Enterprise
l l a
an immediate,
b a di graphical view of administrative tasks, server and database status, and
advisory
l ฺ b o information.

( yae

MySQL for Beginners 5 - 16


Enterprise Monitor Features

• Customizable thresholds, advisor rules, and alerts:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Help you to identify advisor rule violations and user-


defined advisor rules
• Events and alert history: Lists all advisor rules
executions
• Replication Monitor: Enables you to view real-time
master/slave performance
e to
• Query Analyzer: Monitors query performance andA1n ens
accurately pinpoints SQL code that is causing 3%
a l
slowdown
e ic
l C
% rabl
c
2 0In ansfe
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
b o ba
elฺ
(ya

MySQL for Beginners 5 - 17


Enterprise Monitor: Dashboard

Refresh Setting/
Page Tabs Help
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Support
Status
Server
Navigation

Heat Chart
to
Graphs A 1n ense
C 3% le lic
n c l% erab
2 0ICriticalansf
i l l a% onEvents -tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 5 - 18


Enterprise Monitor: Advisors

MEM ships with the following set of best-practice advisors:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Events and alert history: Lists all advisor rules


executions
• Upgrade: Monitors and advises on using the most secure
and updated version of MySQL
• Administration: Monitors and advises on problems
relating to general database administration, recoverability, to
n e
and performance configuration settings A1 ens
C 3% le lic
• Security: Monitors and advises on tightening
n c l% security
f e r ab
vulnerabilities in the MySQL server20I ans
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Having the
a
YMySQL @ co usMonitor
Enterprise
e and MySQL Advisors constantly checking the
configurationd i la workload of monitored MySQL servers is like having a virtual MySQL DBA
land
always
b o bonaguard.
a e lฺ
( y

MySQL for Beginners 5 - 19


Enterprise Monitor: Advisors

• Replication: Monitors and advises on problems relating to


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

replication setup, security, and master/slave latency


• Memory Usage: Monitors dynamic memory–related server
metrics and advises on configuration changes
• Performance: Monitors dynamic performance–related
server metrics and advises on configuration and variable
settings
to
• Schema: Monitors and advises on unplanned changes A 1n toense
a database schema C 3% le lic
n c l% erab
• Custom: Enables you to create your 0own n f
I best-practice
s
2 a
advisors and rules to fit your specific i l l a% ouse n -trof MySQL
a d n
B ob as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
l l a
b a di
l ฺ b o
e
(ya

MySQL for Beginners 5 - 20


Quiz

You can automatically create an EER diagram from an existing


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

MySQL database by using the MySQL Workbench tool.


a. True
b. False

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 5 - 21


Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Explain the primary features of the MySQL Workbench


GUI tool
• Use the MySQL Workbench tool
• Explain the primary features of the MySQL Enterprise
Monitor GUI tool

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 5 - 22


Practice 14-1 Overview:
Create a Data Model Using MySQL Workbench
This practice covers using the Data Modeling module from
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Workbench to create a data model for the world_innodb


database.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 5 - 23


Practice 14-2 Overview:
Create a Server Instance
Using MySQL Workbench
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

This practice covers using the Server Administration module


from Workbench to create a server instance with the
world_innodb database.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 5 - 24


Practice 14-3 Overview:
View the MySQL Enterprise Monitor
Demonstrations
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

This practice covers running web-based demonstrations that


show the primary features of Enterprise Monitor.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 5 - 25


Practice 14-4 Overview:
(Optional) Create a Model for the Pets Database
Using MySQL Workbench
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

This practice covers the following tasks:


• Making a backup of the Pets database
• Creating a model for the Pets database in Workbench
– Create an EER diagram.
– Set up table relationships.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 5 - 26


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Supplemental Information

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(
Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Explain the general purpose of storage engines in MySQL


• Display and set the storage engine
• Describe the key features of the InnoDB storage engine
• Create views of tables with specific data
• Explain the basics of transactions and transaction
statements
to
• Describe and use ACID transactions A 1n ense
• Define and use the INFORMATION_SCHEMA C database
ic
3% le lfor
obtaining metadata n c l% erab
2 0I ansf
• Describe the PERFORMANCE_SCHEMA -tr
lla% ndatabase i o
a d
b MySQL a nEnterprise
• Explain the key featuresoof s eฺ Backup
B
ra x) h t Gu a i d
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
i l l a
b o bad
l ฺ
(y ae

MySQL for Beginners 15 - 2


Storage Engines and MySQL

• InnoDB is the default storage engine for MySQL Server.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• NBD is the default storage engine for MySQL Cluster.


• Other storage engines exist.
• Each storage engine has different characteristics and
implications.
• You can choose a specific storage engine when you create
a table.
to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
a tables
When youYcreate@ co withuMySQL,
se you can specify the storage engine to be used for each
d i
table. Typically, llayou make this choice according to which storage engine offers features that
o
best fit
b bthea needs of your application. Each storage engine has a particular set of operational
a e lฺ
characteristics. These characteristics include the types of locks that are used to manage
( y query contention, and if the storage engine supports transactions. These engine properties
have implications for query processing performance, concurrency, and deadlock prevention.
Although, there are many other storage engines available, InnoDB is the best fit for most
cases.

MySQL for Beginners 15 - 3


Storage Engines Available on the Server

View the available storage engines:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SHOW ENGINES\G


...
Engine: InnoDB
Support: DEFAULT
Comment: Supports transactions, row-level locking,
and foreign keys
Transactions: YES
...
Engine: MyISAM
Support: YES to
Comment: MyISAM storage engine
A 1n ense
Transactions:
...
NO
C 3% le lic
Engine: MEMORY
n c l% erab
Support: YES 0 I n s f
2
Comment: Hash based, stored
i l l a% inonmemory, -tra useful for
bad s a n eฺ
temporary tables
Transactions: NO
o
B ha
...
d r a x ) G uid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
Yastorage o saree compiled into your server and whether they are available at
cengines
To see what
l l @ u
a SHOW ENGINES
run time, use
a d i the statement.
b
o in the Support column is YES or NO, to indicate that the engine is or is not
Thebvalue
l ฺ
( yaeavailable, DISABLED if the engine is present but turned off, or DEFAULT for the storage
engine that the server uses by default. The engine designated as DEFAULT is considered
available.

MySQL for Beginners 15 - 4


Display Storage Engine Setting:
Using SHOW CREATE TABLE
Example:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SHOW CREATE TABLE City\G


******************* 1. row *******************
Table: City
Create Table: CREATE TABLE `city` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` char(35) NOT NULL DEFAULT '',
`CountryCode` char(3) NOT NULL DEFAULT '',
`District` char(20) NOT NULL DEFAULT '', to
`Population` int(11) NOT NULL DEFAULT '0',
A 1n ense
PRIMARY KEY (`ID`),
C 3% le lic
KEY `CountryCode` (`CountryCode`),
n c l% erab
CONSTRAINT `city_ibfk_1` FOREIGN KEY 2 0I ansf
l l a% on-tr
(`CountryCode`) REFERENCES `country` (`Code`)
i
bad s a n eฺ
) ENGINE=InnoDB AUTO_INCREMENT=4080
o
DEFAULT CHARSET=latin1
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 15 - 5


Display Storage Engine Setting:
Using SHOW TABLE STATUS LIKE
Example:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SHOW TABLE STATUS LIKE 'CountryLanguage'\G


********************* 1. row *******************
Name: countrylanguage
Engine: InnoDB
Version: 10
Row_format: Compact
Rows: 820
to
1n ense
Avg_row_length: 119
Data_length: 98304 A
% e lic
C 3
Max_data_length: 0
c l % rabl
Index_length: 65536
2 0In ansfe
Data_free: 12582912 a%
i l l n - tr
Auto_increment: NULL ad
b a no ฺ
... B o as ide
r a ) h u
j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 15 - 6


Set the Storage Engine to InnoDB

• Set the server storage engine as part of the startup


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

configuration file:
[mysqld]
default-storage-engine=InnoDB

• Set for the current client session using the SET command:
SET @@storage_engine=InnoDB;
o
• Specify using the CREATE TABLE statement:
1 n nse t
CREATE TABLE t (i INT) ENGINE = InnoDB; 3 %A e lice
l % C bl
I n c f e ra
20 tran s
%
lla non-
d i
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y a table
If you create s an ENGINE option to specify a storage engine explicitly, the
@withoutuusing
l l a
MySQL server
b a di creates the table using the default engine, which is given by the value of the
system variable.
l ฺ b o
storage_engine

( yaeYou can overwrite the server default at the session level by using the SET command (as
shown in the slide).

MySQL for Beginners 15 - 7


InnoDB Storage Engine

InnoDB, the default storage engine for MySQL, provides high


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

reliability and high performance and provides the following


primary advantages:
• Transaction safe (ACID compliant)
• Multi-Versioning Concurrency Control (MVCC)
– InnoDB row-level locking
– Oracle-style consistent nonlocking reads
• Table data arranged on disk to optimize common queries to
• Foreign key referential integrity constraint support A 1n ense
C 3% le lic
• Maximum performance on large data volumes
n c l% erab
• Mixing of queries on tables with different 0I storage
n s f engines
2
% n-tra
i l l a
• Fast auto-recovery after a a
b d a no
crash
• B
Buffer pool for caching o and
data a s d
indexes
i eฺ in memory
a h
dr mx) nt G u
a n yฺ uditseaffiliates. All rights reserved.
A lej © 2012,
a d
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


Y for any@other disk-related
It is difficult us relational database engine to rival the efficiency of
l l a
InnoDB. Here
b a di is additional information about the advantages of using InnoDB:
• boTransaction-safe: ACID compliance is achieved with transaction commit, rollback, and
l ฺ
( yae crash-recovery capabilities to protect user data.
• Foreign key support: InnoDB includes cascaded deletes and updates.
• Recovery/Backup: InnoDB supports consistent and online logical backup.
• Mixing queries: Within the same statement, you can mix InnoDB tables with tables
from other MySQL storage engines. For example, you can use a join operation to
combine data from InnoDB and MEMORY tables in a single query.
Note: This practice is not recommended, especially in replicated environments.
For more information about InnoDB storage engine features, see the MySQL Reference
Manual: http://dev.mysql.com/doc/refman/5.5/en/innodb-storage-engine.html.
For a glossary of terms about the InnoDB storage engine, see the MySQL Reference Manual:
http://dev.mysql.com/doc/innodb/1.1/en/glossary.html.

MySQL for Beginners 15 - 8


InnoDB as the Default Storage Engine

• Is built in to the MySQL server


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Addresses many industry trends that demand a more


efficient storage engine:
– Rising hard drive and memory capacity
– Growing performance-to-price ratio requirement
– Increased performance requiring reliability and crash
recovery
to
1n ense
– Increasingly large, busy, robust, distributed, and important
A
MySQL databases 3% lic C ble
c l % ra
I n s f e
% 20 tran
d i lla non-
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y MySQL
Starting with @ 5.5, theusdefault storage engine for new tables is InnoDB, replacing the
l l a
storage b a di with
previous default
engine
of MyISAM. This change applies to newly created tables that do not specify a
a clause such as ENGINE=MyISAM.
l ฺ b o
( yaeThe InnoDB storage engine in MySQL 5.5 releases includes a number performance
improvements that in MySQL 5.1 were only available by installing the InnoDB Plugin. It is no
longer required to install a separate plugin. This latest InnoDB (now known as InnoDB 1.1)
offers new features, improved performance and scalability, enhanced reliability, and new
capabilities for flexibility and ease of use. Among the top features are Fast Index Creation,
table and index compression, file format management, new INFORMATION_SCHEMA tables,
capacity tuning, multiple background I/O threads, multiple buffer pools, and group commit.
If you have access to MySQL 5.5 (or later) and you have tables created using another storage
engine (for example, MyISAM), you can evaluate if these tables benefit from switching to
InnoDB.

MySQL for Beginners 15 - 9


Other Storage Engines

• Are optional storage engines


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Are selected when configuring MySQL


• Other commonly used storage engines:
– MyISAM: Is primarily used in web, data warehousing, and
other application environments
– MEMORY: Creates tables with contents that are stored in
memory to
• Many more available engines A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Some storageYa engines@ coare always
u se available, such as MyISAM, MERGE, and MEMORY.
i a optional. Support for optional engines typically can be selected when
llare
Other enginesd
bisaconfigured and built. Compiled-in optional engines also typically can be enabled or
MySQL
lฺ b o
y a e
disabled with a server startup option.
( Note: To reduce memory use, do not configure unneeded storage engines into the server.
This requires that you compile MySQL from source rather than using a precompiled binary
distribution. If you are using a binary distribution that includes compiled-in optional engines
that you do not need, disable them at run time.
For more information about all MySQL-supported storage engines, see the MySQL Reference
Manual at: http://dev.mysql.com/doc/refman/5.5/en/storage-engines.html.

MySQL for Beginners 15 - 10


Quiz

If you create a table without using the ____________ option to


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

specify a storage engine explicitly, the MySQL server creates


the table by using the default engine.
a. INNODB
b. ENGINE
c. DEFAULT_STORAGE_ENGINE

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 15 - 11


Creating Views

A view is a database object that is defined in terms of a


SELECT statement that retrieves the data you want the view to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

produce.
• Views are also known as virtual tables.
• Virtual tables are useful for providing custom "views" into
tables for specific uses and users.
• Virtual tables can be used to select from regular tables or
other views.
to
• Views provide several benefits compared to selecting A 1ndata
e n se
directly from base tables. C 3% le lic
• General syntax example: n c l% erab
I
a sf 20 n
lla% n-tr
CREATE VIEW view_name [<column_list>]
d i no ฺ
b
o as a a
ide
AS SELECT_expression
r a B h u
nd yฺmx ent G )
j a
le © 2012,
2 0 A
Copyright
ฺ u tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya are@
Virtual tables co for providing
useful u se custom "views“ to tables for specific uses or users.
The SELECT d i lla
statement provides the definition of the view. The statement can select from
o b a
base b (normal) tables or other views.
e l ฺ
(ya Benefits of selecting data directly from views instead of tables:
• Access to data becomes simplified:
- Can be used to do calculations and display results
- Can be used to select a restricted set of rows or subset of columns
- Selecting data from multiple tables
- Performs these operations automatically
• You can display table contents differently for different users, per individual needs.
• When a change to table structure is required, a view can preserve the appearance of the
original table.
In some cases, a view is updatable and can be used with statements such as UPDATE,
DELETE, or INSERT to modify an underlying base table. For a view to be updatable, there
must be a one-to-one relationship between the rows in the view and the rows in the
underlying table. There are also certain other constructs that make a view nonupdatable.

MySQL for Beginners 15 - 12


CREATE VIEW Examples

• Basic example:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

CREATE VIEW Country_View


AS SELECT * FROM Country;
• Can use many types of SELECT statements:
CREATE VIEW per_capita_v AS
SELECT Name, GNP, Population, GNP/Population
AS per_capita FROM Country;
o
– The contents of the view: 1 n nse t
mysql> SELECT * from per_capita_v; 3 %A e lice
l % C bl
c | fera
+-------------+---------+------------+------------+
| Name | GNP | Population | per_capita
I
0 ansn
2
+-------------+---------+------------+------------+
| Aruba | 828.00 | 103000%
i l l a || o0.008039
n -tr ||
| Afghanistan | 5976.00 |
| 6648.00 | ba
d
12878000a|n 0.000516
22720000 0.000263
| Angola
B o s e ฺ |
...
d r a x) ha Guid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
Ya to@
A view belongs co usBy
a database.
e default, a new view is created in the default database. To
i
create the view
d llaexplicitly in a given database, either change the database (with USE
o ba or specify the name as db_name.view_name when you create it. The first
<database>)
b
a e lฺ
example in the slide creates a view that contains the entire contents of the Country table from
( y the world_innodb database.
Columns retrieved by the SELECT statement can be simple references to table columns. They
can also be expressions that use functions, constant values, operators, and so forth.
Base tables and views share the same namespace within a database, so a database cannot
contain a base table and a view that have the same name.
Unqualified table or view names in the SELECT statement are interpreted with respect to the
default database (on definition rather than at run time). A view can refer to tables or views in
other databases by qualifying the table or view name with the proper database name.
A view can be created from many kinds of SELECT statements. It can refer to base tables or
other views. It can use joins, UNION, and subqueries. The SELECT need not even refer to any
tables. The second example in the slide defines a view that selects three columns from the
Country table, as well as an expression calculated from two of the columns.

MySQL for Beginners 15 - 13


Displaying View Information

• Base table statements also work for views:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– DESCRIBE
– SHOW TABLES
– SHOW TABLE STATUS
• Example of showing the CREATE VIEW syntax:
mysql> SHOW CREATE VIEW per_capita_v\G
********************** 1. row *********************
o
View: per_capita_v
1 n nse t
%A e lice
Create View: CREATE ... VIEW 'per_capita_v'
AS select 'country'.' Name' AS 'Name','country'.'GNP' 3
C bl
AS 'GNP','country'.'Population' AS 'Population',
c l % ra
I
('country'.'GNP' / 'country'.'Population') AS 'per_capita' n s f e
from 'country'
% 20 tran
character_set_client: latin1
d i lla non-
oba as a ideฺ
collation_connection: latin1_swedish_ci
1 row in set (0.00 sec)
B
ra x) h t Gu
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
You can alsoY obtain us about view objects from INFORMATION_SCHEMA, which
@information
contains a d l l a
i table. The INFORMATION_SCHEMA database is covered later in this lesson.
VIEWS
o b a
l ฺ b
( yae

MySQL for Beginners 15 - 14


Views: Showing the Table Types

• You can use SHOW FULL TABLES to differentiate base


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

table and views.


• Example:
mysql> SHOW FULL TABLES FROM world_innodb;
+------------------------+------------+
| Tables_in_world_innodb | Table_type |
+------------------------+------------+
| city | BASE TABLE |
| country | BASE TABLE |
to
| country_view | VIEW |
A 1n ense
3% le lic
| countrylanguage | BASE TABLE |
| per_capita_v | VIEW | C
l% erab
+------------------------+------------+
n c
5 rows in set (0.00 sec) 2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 15 - 15


View Definition Restrictions

• SELECT statement restrictions cannot:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Contain a subquery in the FROM clause


– Refer to system or user variables
– Refer to prepared statement parameters
• Any table or view referred to in the definition must exist.
• The view definition cannot:
– Refer to a temporary table to
A 1n ense
– Create a temporary view
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 15 - 16


Quiz

Views are sometimes called “virtual tables” and can be created


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

using a CREATE TABLES statement.


a. True
b. False

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 15 - 17


Transactions

• A collection of statements that are treated as a single unit.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Use to group multiple statements.


– Use when multiple clients are accessing data from the same
table concurrently.
• All or none of the steps succeed.
– Execute if all steps are good.
– Cancel if steps have error or are incomplete.
to
• MySQL transactions are ACID compliant. A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya is a@
A transaction co foruyou
means seto execute one or more SQL statements as a single unit of
work, suchd i
thatllaeither all or none of the statements succeed. This is done seemingly in
o
isolation a work being done by any other transactions. If all the statements succeed, you
bof
e b
lฺ the transaction to record their effect permanently in the database. If an error occurs
commit
( y a during the transaction, you roll it back to cancel it. Any statements executed up to that point
within the transaction are undone, leaving the database in the state it was in prior to the point
at which the transaction began.
Note: In MySQL, transactions are supported only for those tables that use a transactional
storage engine (such as InnoDB). These statements have no noticeable effect on tables
managed by a nontransactional storage engine.

MySQL for Beginners 15 - 18


Transactions: ACID

• Atomic: All statements execute successfully or are


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

canceled as a unit.
• Consistent: A database that is in a consistent state when
a transaction begins is left in a consistent state by the
transaction.
• Isolated: One transaction does not affect another.
• Durable: All changes made by transactions that complete to
1n ense
successfully are recorded properly in database. Changes
A
% ic
are not lost. C3 ble l l% era
n c
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya processing
Transactional @ co provides
u se stronger guarantees about the outcome of the database
i
operations,dbutllaalso requires more overhead in CPU cycles, memory, and disk space.
o ba properties are essential for some applications and not for others, and you can
Transactional
b
lฺ which ones make the most sense for your applications.
echoose
(ya Financial operations, typically, need transactions, and the guarantees of data integrity
outweigh the cost of additional overhead. Alternatively, for an application that logs webpage
accesses to a database table, a loss of a few records if the server host crashes might be
tolerable.
There are some storage engines that support transactions and some that do not. You can
choose the engine that best matches your application requirements.

MySQL for Beginners 15 - 19


Transaction Diagram

Start
Example of a banking Transaction
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

transaction:
Withdraw No
from account Roll back
#1? (If insufficient funds)

Yes

Deposit in No
account Roll back
#2? (If does not complete)
to
Yes A 1n ense
C 3% le lic
Commit
n c l% erab
0I ansf
(Make changes permanent)
2
i l l a% on-tr
o badTransaction
a
End n ฺ
r a B has uide
a n d mx) nt G
A lej © 2012,
a d yฺ uditseaffiliates. All rights reserved.
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


The diagramY in the usexample of an attempted transfer of $1,000 from your savings
@slide is an
account to d l l a
i checking account. You would not be happy if the money were successfully
your
o
withdrawnb afrom your savings account, but never made it to your checking account.
l ฺ b
( yaeTo protect against this kind of error, the program that handles your transfer request begins a
transaction, and then issues the SQL statements needed to move the money from your
savings to your checking account. It ends the transaction only if everything succeeds. If a
problem occurs, the program instructs the server to undo all the changes made since the
transaction began.

MySQL for Beginners 15 - 20


Transaction SQL Control Statements

• START TRANSACTION (or BEGIN): Explicitly begins a new


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

transaction
• COMMIT: Makes the changes from the current transaction
permanent
• ROLLBACK: Cancels the changes from the current
transaction
• SET AUTOCOMMIT: Disables or enables the default
autocommit mode for the current connection to
n
A 1 ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
By default,
a
YMySQL @ co withuautocommit
runs se mode enabled. This means that as soon as you
l l a
b a
in autocommit
di mode,that
execute a statement
each
updates (modifies) a table, MySQL stores the update on disk. When
statement is considered to be a transaction, unless a START
l ฺ b o
yae
TRANSACTION is issued. After that, the transaction is open until it is explicitly closed by
( COMMIT or ROLLBACK or implicitly with any statement that implicitly closes a transaction.
When not in autocommit mode, there is no need to use START TRANSACTION, because a
new transaction is automatically started when the last one was ended.

MySQL for Beginners 15 - 21


Starting a Transaction

• Disable the autocommit mode by starting a transaction for


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

a single series of statements.


• Example:
START TRANSACTION;
SELECT Code FROM Country WHERE Name='Mexico';
UPDATE Country
SET Name = 'World Cup Winner'
to
1n ense
WHERE Code = 'MEX';
A
COMMIT;
C 3% le lic
% rab
• Re-enable autocommit when you end0Ithe ncltransaction
s fe with
2 n
COMMIT or ROLLBACK.
i l l a% on-tra
• Check the autocommit setting o bad with a n ฺ
SELECT @@AUTOCOMMIT. r a B has uide
a n d mx) nt G
A lej © 2012,
a d yฺ uditseaffiliates. All rights reserved.
2 0 oฺu s St
Copyright Oracle and/or

a el% corre e thi


If you areY using a@ us (transactional) storage engine (such as InnoDB or NDB
transaction-safe
l l a
Cluster), you
b a dican also disable autocommit mode with the following statement:
l ฺ b oSET AUTOCOMMIT=0
( yaeAfter disabling autocommit mode by setting the AUTOCOMMIT variable to zero, you must use
COMMIT to store your changes to disk or ROLLBACK if you want to ignore the changes you
have made since the beginning of your transaction. The autocommit mode then reverts to its
previous state.
You can check the current setting by using a SELECT statement as follows:
mysql> SELECT @@AUTOCOMMIT;
+--------------+
| @@autocommit |
+--------------+
| 1 |
+--------------+
1 row in set (0.41 sec)
Note: The SET autocommit=0 and BEGIN/START TRANSACTION statements affect MDL
locking of non-transactional tables starting with the version 5.5 of the MySQL server.

MySQL for Beginners 15 - 22


Quiz

A transaction is a device for grouping together multiple SQL


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

statements so that either all or none of the statements succeed.


a. True
b. False

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 15 - 23


Retrieving Metadata

In an RDBMS, metadata is “data about data,” or information


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

about the MySQL server such as the name of a database or


table, the data type of a column, and access privileges.
• Two methods for obtaining metadata:
– SHOW statements:
— They provide information about databases, tables, and columns,
as well as status information about the server.
– SELECT with INFORMATION_SCHEMA statement:
n nse to
A 1
— INFORMATION_SCHEMA database provides access%
3 to database
l i ce
metadata.
l % C ble
The SELECT statement is used to query I n c
the f e ra

20 tran s
INFORMATION_SCHEMA database %
lla non-
information.
d i
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 15 - 24


Metadata: SHOW Statements

• The SHOW statement is a MySQL-only feature.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• SHOW statements for obtaining metadata:


– SHOW DATABASES: Databases on the MySQL server host
– SHOW TABLES: Non-temporary tables in a database
– SHOW TABLE STATUS: Like SHOW TABLES, but provides
extra information about each non-temporary table
– SHOW COLUMNS: Information about columns in a given table
– SHOW INDEX: Returns table index information n nse to
A 1
– SHOW CREATE TABLE: Shows the CREATE TABLE
3 % e lice
statement that creates a given table
n l%C abl c er
• SHOW statements are concise and easy nsf
20I to remember. % n-tra
• It cannot store results in other i l l a
b a d tables a nofor ฺlater use.
• You can apply WHERE o as to SHOW
conditions
B ide statements.
r a ) h u
j a nd yฺmx ent G
A le © 2012,
Copyright
tudits affiliates. All rights reserved.
adOracleSand/or
2 0 ฺ u
e l % rreo this
Some SHOWYastatements
@ co canuobtain
se information that the INFORMATION_SCHEMA currently
d i llasuch as:
cannot retrieve,
• o
b ba CREATE FUNCTION
SHOW
elฺ
(ya •

SHOW CREATE PROCEDURE
SHOW MASTER/SLAVE STATUS

MySQL for Beginners 15 - 25


Metadata: INFORMATION_SCHEMA Database

• Provides access to database metadata:


– Schema and schema objects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Server statistics (status variables, settings, connections)


• Is a “virtual database”
– Tables are not “real” tables (base tables) but “system views.”
– Tables are filled dynamically, according to user privileges.
• Is kept in a table format allowing flexible access
– Tables of all tables and columns.
to
– Use arbitrary SELECT statements.
A 1n ense
• Has the standard SQL feature; is usable withCother 3% le lic
database systems n c l% erab
2 0I ansf
• Allows query limits that SHOW does a% not - tr
i
d forl l n
o use
• Can store results in otherbtables a a nlater
B o as i d eฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
ExamplesYof relational@ databaseus metadata include:
l l a
• Tables
b a dithat contain information about all the tables in a database, their names, sizes
l ฺ b oand number of rows in each table
( yae • Tables that contain information about all the table columns in a database, what tables
they are used in, and the type of data stored in each column
In database terminology, this set of metadata is referred to as the catalog. The SQL standard
specifies a uniform means to access the catalog, called INFORMATION_SCHEMA.
In INFORMATION_SCHEMA, there are several read-only tables, which are actually system
views (not base tables) so there are no files associated with them.
In effect, you have a database named INFORMATION_SCHEMA, although the server does not
create a database directory with that name. It is possible to select INFORMATION_SCHEMA as
the default database with a USE statement, but it is possible only to read the contents of
tables. You cannot insert into them, update them, or delete from them.

MySQL for Beginners 15 - 26


Metadata: INFORMATION_SCHEMA Tables

List all tables in the INFORMATION_SCHEMA database:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT TABLE_NAME


-> FROM INFORMATION_SCHEMA.TABLES
-> WHERE TABLE_SCHEMA = 'information_schema'
-> ORDER BY TABLE_NAME;
+---------------------------------------+
| TABLE_NAME |
+---------------------------------------+
| CHARACTER_SETS |
| COLLATIONS | to
| COLLATION_CHARACTER_SET_APPLICABILITY |
A 1n ense
| COLUMNS |
C 3% le lic
| COLUMN_PRIVILEGES |
n c l% erab
...
2 0I ansf
a% on-tr
| USER_PRIVILEGES |
| VIEWS i
| l l
bad s a n eฺ
+---------------------------------------+
o
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co ustables
The INFORMATION_SCHEMA
e contain the following types of information:
d i lla
Table Information
b o ba Columns in tables and views
a e lฺ
• COLUMNS:
( y • ENGINES: Storage engines
• SCHEMATA: Databases
• TABLES: Tables in databases
• VIEWS: Views in databases
Partitioning
• PARTITIONS: Table partitions
• FILES: Files in which MySQL NDB disk data tables are stored
Privileges
• COLUMN_PRIVILEGES: Column privileges held by MySQL user accounts
• SCHEMA_PRIVILEGES: Database privileges held by MySQL user accounts
• TABLE_PRIVILEGES: Table privileges held by MySQL user accounts
• USER_PRIVILEGES: Global privileges held by MySQL user accounts

MySQL for Beginners 15 - 27


Character Set Support
• CHARACTER_SETS: Available character sets
• COLLATIONS: Collations for each character set
• COLLATION_CHARACTER_SET_APPLICABILITY: Which collations are applicable to a
particular character set
Constraints and Indexes
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• KEY_COLUMN_USAGE: Constraints on key columns


• REFERENTIAL_CONSTRAINTS: Foreign keys
• STATISTICS: Table indexes
• TABLE_CONSTRAINTS: Constraints on tables
Server Settings and Status
• KEY_COLUMN_USAGE: Constraints
• GLOBAL_STATUS: The status values for all connections to MySQL
o
n nse t
• GLOBAL_VARIABLES: The values that are used for new connections to MySQL
1
• PLUGINS: Server plugins
3 %A e lice
• PROCESSLIST: Indicates which threads are running
l % C bl
I n c e ra
• SESSION_STATUS: The status values for the current connection to MySQL
f
20 tran s
• SESSION_VARIABLES: The values that are in effect for the current connection to MySQL
%
lla non-
Routines and Related Information d i
• EVENTS: Scheduled events B oba as a ideฺ
• ROUTINES: Stored procedures n d x ) h t Gu
a functions
rand
• TRIGGERS: Triggers in l e ja dyฺm den
databases
2 0A procedure
ฺ ua and S tu parameters, and stored functions
• PARAMETERS: Stored
l% orre o h i s function
InnoDB Y a e c us e t
a @
• INNODB_CMP
a d ill and INNODB_CMP_RESET: Status on operations related to compressed
b o b
InnoDB tables
l ฺ
e• INNODB_CMPMEM and INNODB_CMPMEM_RESET: Status on compressed pages within the
( y a InnoDB buffer pool
• INNODB_LOCKS: Each lock that an InnoDB transaction has requested and holds
• INNODB_LOCK_WAITS: One or more row locks for each blocked InnoDB transaction
• INNODB_TRX: Every transaction currently executing inside InnoDB
• TABLESPACES: Active tablespaces
For more information about the INFORMATION_SCHEMA tables, see the MySQL Reference
Manual at: http://dev.mysql.com/doc/refman/5.5/en/information-schema.html.

MySQL for Beginners 15 - 28


Metadata: Viewing INFORMATION_SCHEMA

Example of INFORMATION_SCHEMA with TABLE_SCHEMA:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT table_name, engine


-> FROM INFORMATION_SCHEMA.TABLES
-> WHERE table_schema = 'world_innodb';
+------------------+--------+
| table_name | engine |
+------------------+--------+
| city | InnoDB |
o
| country | InnoDB |
1 n nse t
%A e lice
| country_view | NULL |
| countrylanguage | InnoDB | 3
C bl
| countrylanguage2 | InnoDB |
c l % ra
I n s f e
20 tran
| per_capita_v | NULL |
+------------------+--------+ %
lla non-
d i
B oba as a ideฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
The exampleY in the us a list of all the tables in the world_innodb database,
@slide requests
l l a
showing just
b a ditwo columns of information: the name of the table and its engine.
Note:
l ฺ b oEach MySQL user has the right to access these tables, but can see only the rows in the
( yaetables that correspond to objects for which the user has proper access privileges.

MySQL for Beginners 15 - 29


Metadata: SCHEMATA

Example of INFORMATION_SCHEMA with SCHEMA_NAME:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT * FROM INFORMATION_SCHEMA.SCHEMATA


-> WHERE SCHEMA_NAME = 'world_innodb'\G
******************* 1. row ********************
CATALOG_NAME: def
SCHEMA_NAME: world_innodb
DEFAULT_CHARACTER_SET_NAME: latin1
DEFAULT_COLLATION_NAME: latin1_swedish_ci to
SQL_PATH: NULL A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co usdatabase
The INFORMATION_SCHEMA
e has a SCHEMATA table that contains database
l l a
b a di
metadata (information about databases).

l ฺ b o
( yae

MySQL for Beginners 15 - 30


Quiz

INFORMATION_SCHEMA has several tables that contain


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

information similar to that displayed by the SHOW statements.


a. True
b. False

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 15 - 31


MySQL Performance Schema

The MySQL Performance Schema is a feature for monitoring


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

MySQL server execution at a low level, with minimal impact on


server performance.
• Focuses primarily on performance data
• Monitors server events on all available platforms supported
by MySQL
– An “event” is anything the server does that takes time.
n nse to
• Inspects internal execution of the server (at runtime) A 1using:
3 % e lice
– Performance Schema storage engine l%C abl
c r
– PERFORMANCE_SCHEMA database 20In nsfe
i l l a% on-tra
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya is@any
A server “event” cotask utheseserver does that takes time and has been instrumented so
that timing d i lla
information can be collected. In general, an event can be a function call, a wait for
o b a
the operating system, a stage of an SQL statement execution such as parsing or sorting, or
l ฺ b
yae
an entire statement or group of statements. Currently, event collection provides access to
( information about synchronization calls and file I/O calls for the server and for several storage
engines.
You can implement data collection by modifying the server source code to add
instrumentation. There are no separate threads associated with the Performance Schema,
unlike other features such as replication or the Event Scheduler.
The PERFORMANCE_SCHEMA database focuses on performance data, differing from
INFORMATION_SCHEMA, which serves for inspection of metadata.
For more information about Performance Schema features, see the MySQL Reference
Manual at: http://dev.mysql.com/doc/refman/5.5/en/performance-schema.html.

MySQL for Beginners 15 - 32


Performance Schema: Implementation

• Performance Schema storage engine:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– Collects event data using “instrumentation points” in server


source code.
— It is easy to add new instrumentation points.
— Instrumented code is backward-compatible when new versions
are implemented.
• PERFORMANCE_SCHEMA database:
– Collected events are stored in tables. to
Tables can be queried using SELECT statements. %A
1n ense
3 le lic

– You can change configuration of data collection C


l% eby b
n c f r aupdating
tables using SQL statements.
2 0I ans
– Tables are views or temporary i l l % nthat
atables - tr are not stored.
b a d a no
B o as i d eฺ
n d ra x) h t Gu
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 15 - 33


Performance Schema: SHOW Database Tables

List all tables in the PERFORMANCE_SCHEMA database:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SHOW TABLES FROM PERFORMANCE_SCHEMA;


+----------------------------------------------+
| Tables_in_performance_schema |
+----------------------------------------------+
| cond_instances |
| events_waits_current |
| events_waits_history |
| events_waits_history_long |
| events_waits_summary_by_instance |
| events_waits_summary_by_thread_by_event_name |
| events_waits_summary_global_by_event_name |
o
n nse t
| file_instances |
| file_summary_by_event_name |
1
| file_summary_by_instance |
3 %A e lice
| mutex_instances |

l % C bl
ra
| performance_timers |
| rwlock_instances |
I n c f e
| setup_consumers |
20 tran s
| setup_instruments
%
lla non-
|
| setup_timers
d i |

oba as a ideฺ
| threads |

B
+----------------------------------------------+

ra x) h t Gu
17 rows in set (0.00 sec)

n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @
The PERFORMANCE_SCHEMA ustables contain the following types of information:
l l a
Setup adi
•ฺbo
b
setup_consumers: The types of consumers for which event information can be stored
l
( yae • setup_instruments: The classes of instrumented objects for which events can be
collected
• setup_timers: The current event timer
Instance
• cond_instances: Condition synchronization object instances
• file_instances: File instances
• mutex_instances: Mutex synchronization object instances
• rwlock_instances: Lock synchronization object instances
Wait Event
• events_waits_current: Current wait events
• events_waits_history: The most recent wait events for each thread
• events_waits_history_long: The most recent wait events overall

MySQL for Beginners 15 - 34


Summary
• events_waits_summary_global_by_event_name: Wait events summarized per
event name
• events_waits_summary_by_instance: Wait events summarized per instance
• events_waits_summary_by_thread_by_event_name: Wait events summarized per
thread and event name
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• file_summary_by_event_name: File events summarized per event name


• file_summary_by_instance: File events summarized per file instance
Miscellaneous:
• performance_timers: Which event timers are available
• threads: Information about server threads

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm entx ) G
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 15 - 35


Quiz

The PERFORMANCE_SCHEMA database stores events in tables.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

You can change the configuration of the data collection by


updating tables using SQL statements.
a. True
b. False

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 15 - 36


MySQL Enterprise Backup

The MySQL Enterprise Backup (MEB) product performs “hot


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

backup” operations for MySQL databases.


• Executes efficient and reliable backups of tables created
by the InnoDB storage engine
• Performs hot backups while the database is running
• Is used when your data is large and takes a long time to
back up
• Is used when it is important to save every change and to
A 1n ense
keep data constantly accessible 3% le lic
C
• Enables you to take complete “warm backups”
n c l% efor
f r abnon-
InnoDB storage engine tables 20I rans
i l l a% on-t
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya do@ o se database operations, and capture changes that occur
notcblock normal
“Hot” backups
l l u
a is happening.
d i
while the backup
a Hot backups are desirable when your database is large
enough
b o bthat the backup takes significant time, and when your data is important enough to
l ฺ
eyour business so that you must capture every change without taking your application, website,
(ya or web service offline.
MySQL Enterprise Backup does a hot backup of all tables that use the InnoDB storage
engine. For tables using MyISAM or other non-InnoDB storage engines, it does a “warm”
backup, where the database continues to run, but those tables cannot be modified while being
backed up. For efficient backup operations, you can designate InnoDB as the default storage
engine for new tables, or convert existing tables to use the InnoDB storage engine.
For more information about Enterprise Backup features, see the MySQL Reference Manual
at: http://dev.mysql.com/doc/refman/5.5/en/mysql-enterprise-backup.html.

MySQL for Beginners 15 - 37


MySQL Enterprise Backup: Preparation

Important tasks to perform before your first backup:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Collect pertinent database information and decide on


directory names.
• Grant user privileges required for backup administration.
• Designate a location with ample storage for backup data.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
The best Y
a forcobackupsseinvolve preplanning and good strategy. Before backing up a
practices
i l l a@server foru the first time, gather some information such as:
d
particular database
bato
• boPath MySQL configuration file
l ฺ
( yae • MySQL port
• Path to MySQL data directory
• ID and password of the privileged MySQL user
• Path under which to store backup data
• Owner and permission information for backed-up files
For most backup operations, the mysqlbackup command connects to the MySQL server
through --user and --password options. This user requires certain privileges. You can
either create a new user with a minimal set of privileges, or use an administrative account
such as the root user.
All backup-related operations either create new files or reference existing files underneath a
specified directory that holds backup data. Choose this directory in advance, on a file system
with sufficient storage. (It can even be remotely mounted from a different server.)

MySQL for Beginners 15 - 38


MySQL Enterprise Backup: Implementation

• Use the mysqlbackup command for all backup and


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

restore operations.
– Is an easy-to-use backup tool
– Backs up database items such as:
— All InnoDB and MyISAM tables and indexes
— Tables managed by other storage engines
— Other files underneath the MySQL data directory
• In addition to creating backups, mysqlbackup can: to
A 1n ense
Pack and unpack backup data

C 3% le lic
Apply to the backup data any changes to InnoDB

n c l% etables
f r ab that
occurred during the backup operation0I s
2 r a n
Restore data, index, and log lfiles

i l a%to their o n -toriginal locations
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Yatable@
The InnoDB co include:
backups u se
d illa system tablespace (which contains all the InnoDB tables, by default)
• TheaInnoDB
•ฺbo
b
Any separate data files produced under the InnoDB file-per-table setting. Each one
l
( yae contains one table and its associated indexes. Each data file can use either the original
Antelope or the new Barracuda file format.
Other files backed up from the MySQL data directory include the .frm files that record the
structure of each table.
Note: Although the mysqlbackup command backs up InnoDB tables without interrupting
database use, the final stage that copies non-InnoDB files (such as MyISAM tables and .frm
files) temporarily puts the database into a read-only state. Therefore, do not run any long
SELECT statements, and keep MyISAM tables small and for read-only or read-mostly work.
For more information about MEB preparation and implementation, see the MySQL Enterprise
Backup User’s Guide at: http://dev.mysql.com/doc/mysql-enterprise-backup/3.6/en/index.html.

MySQL for Beginners 15 - 39


MySQL Enterprise Backup:
Running mysqlbackup
• All connection options can be included on the command
line, or in your configuration file and referenced by the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

command.
• A folder is created in the specified backup location with all
data.
• Example of command-line options:
shell> mysqlbackup --user=dba --password=dba_pswd
--port=3306 --with-timestamp
e to
--backup-dir=D:/mysql_backups backup1n
ens
%A e lic
MySQL Enterprise Backup version 3.6.0 [01.07.2011 ] 3
C bl
...
c l % ra
I n
--------------------------------------------------------------------
s f e
Backup Config Options:
% 20 tran
lla non-
--------------------------------------------------------------------
datadir
d i
= D:\mysql_backups\2012-01-11_10-07-23\datadir

oba as a ideฺ
innodb_data_home_dir = D:\mysql_backups\2012-01-11_10-07-23\datadir
...
B
ra x) h t Gu
d
mysqlbackup completed OK!
n
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y the
You can include us options in the configuration file under [mysqlbackup], and
@connection
specify thed i l l a
configuration file and the backup operation, such as:
b a
omysqlbackup --defaults-file=/usr/local/mysql/my.cnf backup
e l ฺ b
(ya Or, you can specify the configuration file as above, but override some of those options on the
command line.
A backup report goes to standard-out and shows the steps taken to complete the backup, as
well as the location of the input data and the backup output files.
In the example in the slide, the dba user (with the password dba_pswd) is backing up all the
existing MySQL server database data to back up files in the D:/mysql_backups directory,
which resides in a folder named after the date and time of the backup execution. The folder
name is shown in the standard-out report.
Make sure that the user or the cron job running mysqlbackup has the rights to copy files
from the MySQL database directories to the backup directory.
Also, ensure that your connection timeouts are long enough so that the command can keep
the connection to the server open for the duration of the backup run. mysqlbackup pings the
server after copying each database to keep the connection alive.

MySQL for Beginners 15 - 40


MySQL Enterprise Backup:
A Few mysqlbackup Options
• Subcommands:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

backup: Performs the initial phase of a backup


apply-log: Updates the InnoDB table backup using the data
from an incremental backup
• Standard options:
--no-defaults: Do not read default options from any file
--defaults-file=PATH: Only read options from this file
o
• Server repository options: 1 n nse t
--datadir=PATH: Location of MySQL data files 3% e lic
A e
l % C bl
--innodb_data_file_path=VALUE: Specifies
I n c f e ra data
InnoDB
20 tran
file names and sizes. [Example: ibdata1:32M:autoextend s ]
l a
l non % -
• Backup repository options:adi
B ob astoastore
Location i d etheฺ
backup data
--backup_dir=PATH:
d r a x) h Gu
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
There areY
a
many more @ cosubcommands
u se and options for mysqlbackup. See the user guide for a
i a
llexplanation
b a d
full listing and of these options.

l ฺ b o
( yae

MySQL for Beginners 15 - 41


MySQL Enterprise Backup:
Recovering or Restoring a Database
Backup data is ultimately used to recover from a database
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

issue, or to create a clone of the original database in another


location.
• Use mysqlbackup with the copy-back subcommand to
restore files to their original locations.
– Instead of the backup subcommand
• Use MEB with a MySQL binary log to create a “point-in-
time” recovery from the hot backup. to
n
A 1 ense
– Dump all SQL activity after the binlog position of %
3 e l ic
the backup
using mysqlbinlog and pipe back into mysql. l C
% rabl
n c fe without
• Use MEB to set up a replication slave 2 0Idatabase n s
stopping the master, by backing i l l % then-master
aup tra and
d a no
restoring that backup onoaba newsslave eฺ
server.
B
ra x) h t Gu a i d
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y database
After a serious @ problem,us you need to recover your data as quickly as possible.
l l a
You typically
b a dicreate a clone of the original database in another location to run report queries,
or to
l ฺ b o a new replication slave.
create
e
(ya copies
You must shut down the database server before running mysqlbackup with copy-back. It
the data files, logs, and other backed-up files from the backup directory back to their
original locations, and performs any required post-processing on them.
To recover the database to a specific point in time:
• Binary logging must be enabled in MySQL, before taking the backup that serves as the
base for this restore operation
• Find the binlog position that corresponds to the time of the backup. InnoDB stores only
the binlog position information to its tablespace at a transaction commit.
• Pipe the output from mysqlbinlog --start-position=... directly to mysql to
replay all the SQL statements after the last backup
Replication is also used as a means for securing and backing up data to another location.

MySQL for Beginners 15 - 42


Quiz

The following subcommand is used with mysqlbackup to run


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

the initial phase of a backup.


a. backup
b. --datadir
c. copy-back

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 15 - 43


Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Explain the general purpose of storage engines in MySQL


• Display and set the storage engine
• Describe the key features of the InnoDB storage engine
• Create views of tables with specific data
• Explain the basics of transactions and transaction
statements
to
• Describe and use ACID transactions A 1n ense
• Define and use the INFORMATION_SCHEMA C database
ic
3% le lfor
obtaining metadata n c l% erab
2 0I ansf
• Describe the PERFORMNACE_SCHEMA -tr
lla% ndatabase i o
a d
b MySQL a nEnterprise
• Explain the key featuresoof s eฺ Backup
B
ra x) h t Gu a i d
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
i l l a
b o bad
l ฺ
(y ae

MySQL for Beginners 15 - 44


Practice 15-1 Overview:
Display Storage Engine Information
This practice covers using the following statements for
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

retrieving storage engine information:


• SHOW CREATE TABLE
• SHOW TABLE STATUS
• SHOW ENGINES

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 15 - 45


Practice 15-2 Overview:
Display and Create Views
This practice covers listing table types and creating a view from
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

an existing world_innodb table.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 15 - 46


Practice 15-3 Overview:
Obtain Metadata
This practice covers using INFORMATION_SCHEMA to show
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

metadata.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 15 - 47


Practice 15-4 Overview:
(Optional) Create a Backup of MySQL Databases
This practice covers using MySQL Enterprise Backup to create
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

a backup of the MySQL databases on your system.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 15 - 48


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Conclusion

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(
Course Goals

After completing this course, you should have learned to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Describe the features and benefits of MySQL


• Explain the basics of relational databases
• Describe MySQL connectors, and their major features and
differences
• Explain the SQL and MySQL languages
• Describe data/column types with regard to efficient database
design to
A 1n ense
• View a database design structure and content 3%
e l ic
l C
% structurebl
• Create a database design by using an efficient c e r a
• Extract basic database information by 2 In the
0using n s fSELECT
l l a % n-tra
command
a i
d a no
b eฺ
Botypical
• Troubleshoot and identify assyntaxidwarnings
ra x) h t Gu
and errors
n d
l e y ฺm den
ja© 2012,dOracle
2 0A oฺua s Sand/or
Copyright
tu its affiliates. All rights reserved.
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

MySQL for Beginners 16 - 2


Course Goals

(continued)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Delete or modify a database and table row data


• Group query data with aggregation
• Connect data from multiple table rows by using JOIN
• Perform nested subqueries
• Use simple functions (String, Date, Numerical)
• Explain MySQL storage engines and transactions, and the
to
features of the common engines
A 1n ense
• Export and import database data
C 3% le lic
• Obtain database metadata n c l% erab
0 I n s f
2
• Monitor server database performance
i l l a% on-tra
o ad interface
• Describe MySQL graphicalbuser a n tools ฺ
• Perform database backupB a s i d e
ra and ) h recovery
nd yฺmx ent G
u
j a
le © 2012,
2 0 A
Copyright
ฺ u tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 16 - 3


MySQL Curriculum Path
Database developers Database administrators
MySQL and PHP MySQL for Beginners Introductory
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

ILT/LVC ILT/LVC

Intermediate
MySQL Performance
Tuning Bootcamp

MySQL for Database


MySQL MySQL for Developers
Administrators
Bootcamp ILT/LVC
ILT/LVC
to
A 1n ense
e l ic
3% Advanced
l C
% rabl
c
In nsfe
2 0 a Cluster MySQL High
MySQL Advanced
Stored Procedures
MySQL Developer
Techniques i l
Tuning a% on-trMySQL
MySQL Performance
l Availability
d n
oba ILT/LVC
ILT
ILT/LVC ILT/LVC
B s a e ฺ ILT

d r a x) ha Guid
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
Ya @co use
d i lla
b o ba
a e lฺ
( y

MySQL for Beginners 16 - 4


MySQL Resources

• MySQL training
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

– http://www.oracle.com/education
• MySQL certification
– http://www.oracle.com/certification
• Additional learning resources
– http://mysql.com
— Webinars and demos
Articles to

White papers A 1n ense


C 3% le lic
• Developer Zone
n c l% erab
– http://dev.mysql.com/ 2 0I ansf
Product downloads i l l a% on-tr
bad s a n eฺ

Community communication o
B ha uid

d r a x ) G
j a n yฺm ent
e
Al ©ฺu2012, tudits affiliates. All rights reserved.
adOracleSand/or
2 0Copyright
e l % rreo this
Ya @co use
d i lla
b o ba
elฺ
(ya

MySQL for Beginners 16 - 5


We Need Your Evaluation!

• Because we continually update our courses, your feedback


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

is invaluable.
• Thank you for taking the time to give us your opinions.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 16 - 6


Thank You

• Congratulations on completing this course!


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• We appreciate your attendance and participation.


• For training and contact information, see the Oracle
University website at http://www.oracle.com/education.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

MySQL for Beginners 16 - 7


Q&A Session

• Questions and answers


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Questions after class


– Get answers from our online reference manual.
– http://dev.mysql.com/doc/refman/5.5/en/faqs.html
• Example databases
– Download the world_innodb database (as well as others)
from our website.
– http://dev.mysql.com/doc/index-other.html to
(under Example Databases) A 1n ense
% ic 3 le l
C
l% erab
n c
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) G
e j a
2 Al ©ฺu2012,
0Copyright tudits affiliates. All rights reserved.
adOracleSand/or
e l % rreo this
Ya @co use
d i lla
b o ba
l ฺ
(y ae

MySQL for Beginners 16 - 8

You might also like