Professional Documents
Culture Documents
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.
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
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
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ฺ
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ฺ
(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ฺ
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
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
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ฺ
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
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ฺ
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ฺ
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ฺ
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ฺ
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
(continued)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ
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
Day 3
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ
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
• 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
(
• 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
(
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
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
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.
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 training
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ
MySQL certification
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
(
• 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)
• 24 × 7 support
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 My
You can access @ co uSupport
Oracle se at https://support.oracle.com.
d i lla
b o ba
a e lฺ
( y
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
• http://dev.mysql.com includes:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ
ILT/LVC ILT/LVC
Intermediate
MySQL Performance
Tuning Bootcamp
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 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
• 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
– 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
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
(
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
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
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.
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
(
Systems
TCP/IP Local, remote All
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.
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
(
– 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/.
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.
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
(
• The tee file is a text file that logs all mysql client
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
(
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
(
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
(
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
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.
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
(
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
—
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.
• 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.
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).
• Retrieve data:
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
(
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
(
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
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
(
Car Engine
• Candidate key:
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)
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.
• ERDs:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ
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.
• 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
(
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.
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
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
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
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
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.
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
(
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.
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.
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
(
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
(
No Primary No
Store? Retrieve?
Purpose
Yes Yes
No
Modify?
Yes
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.
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
(
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
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
(
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
(
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
(
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 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
– 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
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.
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
• Data types:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ
Storage
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.
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
(
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
• 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.
• 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.
• 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.
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
(
'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
• Data types:
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
(
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.
• Data types:
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.
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
Identify the best data type for the PartName_3NF table column
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
(
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
(
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
(
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
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.
• 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.
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
(
• 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.
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
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.
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.
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.
( 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.
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
(
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
(
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
(
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
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.
l ฺbo
| Oceania | Micronesia/Caribbean |
ya e+---------------+---------------------------+
( 25 rows in set (0.00 sec)
( yae
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)
| 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
(
• 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.
• 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.
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 >.
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.
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
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
(
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.
(
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
(
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
(
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
(
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
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.
( 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.
( 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.
• 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
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.
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
• Example:
mysql> ALTER TABLE EU_Countries
-> DROP COLUMN ID;
Query OK, 46 rows affected (0.11 sec)
Records: 46 Duplicates: 0 Warnings: 0
l ฺ o not remove a column from a table if it is a primary key. You cannot remove a
Youbshould
• 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
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.
• 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
(
• 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;
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
(
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
(
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
(
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
(
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
(
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
(
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
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
(
• 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.
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
(
– 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:
Example:
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
(
• 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.
(
i l l a| %
Kabol n-
o
t | 1780000 |
+----+----------------+-------------+---------------+------------+
— 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
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
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
( yae
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
(
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
(
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
(
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
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
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
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>)
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>)
• Removes all the leading and trailing spaces around the string:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ
l ฺ b
( yae
• 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
DATE YYYY-MM-DD
TIME HH:MM:SS
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
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
(
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
• 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.
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
(
• Geometric functions:
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
(
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
(
CASE value
WHEN <compare_value> THEN <result>
[WHEN <compare_value> THEN <result> ...]
[ELSE <result>]
END
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
(
– 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).
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>)
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.
• 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
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.
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.
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
(
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
(
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
(
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
(
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
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
(
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
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.
Combines all the rows from one table with all the
Unqualified Join Cross Join rows of another table
• 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.
| Code | Name |
+------+---------------------------------------+
| AGO | Angola |
| BDI | Burundi |
| BEN | Benin |
| BFA | Burkina Faso |
...
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.
( 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:
+-----------------------------+------------------+
| 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
• 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.
– 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)
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
(
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
(
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
(
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
(
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
(
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
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
(
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.
(
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
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
• Non-correlated:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ
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.
data.
• Scalar: Zero or one row, with a single column:
– 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
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.
• 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.
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
l ฺ b o table results.
the types of
( yae
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.
• 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
• 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 |
+---------+
• 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.
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
(
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.
(
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
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
(
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
(
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
(
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
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
(
• 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.
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.
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
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
(
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
l ฺ b o
( yae
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
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
(
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
(
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
(
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
(
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
(
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
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
(
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
• SQL Development
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ
( yaehttp://mysql.com/products/workbench/.
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
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
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.
• 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
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.
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
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
( yae
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
(
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
(
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
(
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
(
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
(
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
(
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
(
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
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).
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
(
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.
• Basic example:
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
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
(
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.
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
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.
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
(
l ฺ b o
( yae
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
(
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
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
(
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
(
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.)
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.
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.
l ฺ b o
( yae
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
(
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
(
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
(
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
(
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
(
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
(continued)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ
ILT/LVC ILT/LVC
Intermediate
MySQL Performance
Tuning Bootcamp
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 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
—
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
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
(
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
(