Download as pdf or txt
Download as pdf or txt
You are on page 1of 278

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

to
A 1n ense
C 3% le lic
MySQL forIn cl% ferab
Beginners
2 0 ans
i l l a% on-tr
o ad Guide
bActivity 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 ฺbo
ya e
(

D61918GC30
Edition 3.0
May 2013
D82066
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Disclaimer

This document contains proprietary information and is protected by copyright and 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 in any way.
Except where your use constitutes "fair use" under copyright law, you may not use, share, download, upload, copy, print, display,
perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express authorization
of Oracle.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

The information contained in this document is subject to change without notice. If you 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
warranted to be error-free.

Restricted Rights Notice

If this documentation is delivered to the United States Government or anyone using the documentation on behalf of the United
States Government, the following notice is applicable:

U.S. GOVERNMENT RIGHTS


The U.S. Government’s rights to use, modify, reproduce, release, perform, display, or disclose these training materials are restricted
by the terms of the applicable Oracle license agreement and/or the applicable U.S. Government contract.

Trademark Notice to
A 1n ense
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective
owners.
C 3% le lic
n c l% erab
Author
2 0I ansf
Mark Lewin
i l l a% on-tr
Technical Contributors and Reviewers oba
d an
B s d e ฺ
Andrew Morgan, Martin Hansson, Bob a
raFalsco,x)Math Keep, i
u Kodinov, Mike Lischke,
Georgi
n d m eRoy t G
n Lyseng, Craig McBride, Jeremy Smyth
Guilhem Bichot, Ford Brockman,
l e ja Sanjay
d y ฺManwani,
d
2 0A oฺua s Stu
This book was
a epublished re Oracle
l% orusing:
e t hi Tutor
Y @c us
d i lla
b o ba
a e lฺ
( y
Table of Contents
Practices for Lesson 1: Introduction to MySQL ............................................................................................1-1
Practices for Lesson 1: Overview ...................................................................................................................1-2
Practice 1-1: Accessing MySQL Resources Online .......................................................................................1-3
Solution 1-1: Accessing MySQL Resources Online .......................................................................................1-5
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Practices for Lesson 2: MySQL Server and Client ........................................................................................2-1


Practices for Lesson 2: Overview ...................................................................................................................2-2
Practice 2-1: Installing and Starting the MySQL Server .................................................................................2-3
Solution 2-1: Installing and Starting the MySQL Server .................................................................................2-8
Practice 2-2: Using the Keyboard Editing and Tee Commands .....................................................................2-9
Solution 2-2: Using the Keyboard Editing and Tee Commands .....................................................................2-13
Practice 2-3: Creating the world_innodb Database ........................................................................................2-14
Solutions 2-3: Creating the world_innodb Database ......................................................................................2-15
Practices for Lesson 3: MySQL Database Basics .........................................................................................3-1
Practices for Lesson 3: Overview ...................................................................................................................3-2 to
1n ense
Practice 3-1: Quiz – Database Basics ............................................................................................................3-3
A
3% le lic
Solutions 3-1: Quiz – Database Basics ..........................................................................................................3-5
C
n c l% erab
Practice 3-2: Identifying the Structure of a Table ...........................................................................................3-6
Solutions 3-2: Identifying the Structure of a Table..........................................................................................3-7
2 0I ansf
Practices for Lesson 4: Database Design ......................................................................................................4-1

i l l a% on-tr
Practices for Lesson 4: Overview ...................................................................................................................4-2

b ad a n ฺ
Practice 4-1: Quiz – Database Design ...........................................................................................................4-3
o
r a B has uide
Solutions 4-1: Quiz – Database Design .........................................................................................................4-6

a n d mx) nt G
Practice 4-2: Evaluating a Database ..............................................................................................................4-7

A lej Diagram
Solutions 4-2: Evaluating a Database
yฺ ude
............................................................................................................4-8
a d
2 0StructureoDiagram
Practice 4-3: Creating a Structure
ฺ t
u ...................................................................................................4-15
...................................................................................................4-13
S
el% Table
Solution 4-3: Creating a e
rrData hi s
t.....................................................................................................5-1
Practices fora Lesson 5: c o e
Y @5: Overviewu...................................................................................................................5-2
s
Types

l l a
Practices for Lesson
Practicea
b diQuiz – Data Types ....................................................................................................................5-3
5-1:

l ฺ b o 5-1: Quiz – Data Types...................................................................................................................5-5


Solutions

( yae Practice 5-2: Explaining the Use of Data Types .............................................................................................5-6


Solutions 5-2: Explaining the Use of Data Types ...........................................................................................5-7
Practices for Lesson 6: Database and Table Creation ..................................................................................6-1
Practices for Lesson 6: Overview ...................................................................................................................6-2
Practice 6-1: Displaying Table Creation Information ......................................................................................6-3
Solutions 6-1: Displaying Table Creation Information ....................................................................................6-4
Practice 6-2: Creating a Database .................................................................................................................6-7
Solutions 6-2: Creating a Database ...............................................................................................................6-11
Practices for Lesson 7: Basic Queries ...........................................................................................................7-1
Practices for Lesson 7: Overview ...................................................................................................................7-2
Practice 7-1: Performing Basic Queries .........................................................................................................7-3
Solutions 7-1: Performing Basic Queries .......................................................................................................7-4
Practice 7-2: Perform Basic Queries Using MySQL Workbench ....................................................................7-12
Solution 7-2: Perform Basic Queries Using MySQL Workbench ....................................................................7-14
Practice 7-3: Perform Basic Queries on the Pets Database ...........................................................................7-15
Solution 7-3: Perform Basic Queries on the Pets Database ...........................................................................7-16
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

MySQL for Beginners


iii
Practices for Lesson 8: Database and Table Maintenance ..........................................................................8-1
Practices for Lesson 8: Overview ...................................................................................................................8-2
Practice 8-1: Removing a Database...............................................................................................................8-3
Solutions 8-1: Removing a Database .............................................................................................................8-4
Practice 8-2: Creating a New Table and Removing a Table ..........................................................................8-5
Solutions 8-2: Creating a New Table and Removing a Table .........................................................................8-6
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Practice 8-3: Altering Table Columns .............................................................................................................8-9


Solutions 8-3: Altering Table Columns ...........................................................................................................8-10
Practice 8-4: Modifying Table Indexes and Constraints .................................................................................8-12
Solutions 8-4: Modifying Table Indexes and Constraints ...............................................................................8-13
Practice 8-5: Further Practice.........................................................................................................................8-16
Solutions 8-5: Further Practice .......................................................................................................................8-17
Practices for Lesson 9: Table Data Manipulation..........................................................................................9-1
Practices for Lesson 9: Overview ...................................................................................................................9-2
Practice 9-1: Inserting and Replacing Table Row Data ..................................................................................9-3
Solutions 9-1: Inserting and Replacing Table Row Data ................................................................................9-4
to
A 1n ense
Practice 9-2: Modifying and Deleting Table Row Data ...................................................................................9-6
Solutions 9-2: Modifying and Deleting Table Row Data .................................................................................9-7

C 3% le lic
Practice 9-3: Manipulating Table Row Data in the Pets Database .................................................................9-10

n c l% erab
Solutions Practice 9-3: Manipulating Table Row Data in the Pets Database .................................................9-13

0I ansf
Practices for Lesson 10: Functions................................................................................................................10-1
2
a % n-tr
Practices for Lesson 10: Overview .................................................................................................................10-2
l l
i
d a no
Practice 10-1: Quiz – Functions .....................................................................................................................10-2
a
o asb e ฺ
Solutions 10-1: Quiz – Functions ...................................................................................................................10-4
B i d
Solutions 10-2: Using Built-In, String,n d a Functions
rTemporal
Practice 10-2: Using Built-In, String, and Temporal
x ) h .......................................................................10-5
t G u
Practice 10-3: Using Numericlande jaControl dFlow
and
y m ............................................................................10-8
ฺFunctions e n
Functions .....................................................................10-6

0A andoControl d
tu ..........................................................................10-9
Solutions 10-3: Using2Numeric ฺ ua Flow s S
Functions
Practice 10-4:e
a l%Aggregate
Using
o r e hi
reFunctionst.....................................................................................................10-11
Y10-4: Using
Solutions
@ c uFunctions
Aggregate s ...................................................................................................10-12
a
ill 11: Exporting and Importing Data ..............................................................................11-1
d
Practices for Lesson
a
l ฺ ob for Lesson 11: Overview.................................................................................................................11-2
Practices
b
Practice 11-1: Quiz – Exporting and Importing Data ......................................................................................11-3

( yae Solutions 11-1: Quiz – Exporting and Importing Data ....................................................................................11-5


Practice 11-2: Exporting Files by Using a Query ............................................................................................11-6
Solutions 11-2: Exporting Files by Using a Query ..........................................................................................11-7
Practice 11-3: Importing Files from a Data File ..............................................................................................11-10
Solutions 11-3: Importing Files from a Data File ............................................................................................11-11
Practice 11-4: Backing Up Database Files with a Utility .................................................................................11-13
Solutions 11-4: Backing Up Database Files with a Utility ...............................................................................11-14
Practices for Lesson 12: Joining Tables ........................................................................................................12-1
Practices for Lesson 12: Overview .................................................................................................................12-2
Practice 12-1: Performing Inner and Outer Joins ...........................................................................................12-3
Solutions 12-1: Performing Inner and Outer Joins .........................................................................................12-4
Practice 12-2: Creating Queries Requiring Joins ...........................................................................................12-8
Solutions 12-2: Creating Queries Requiring Joins..........................................................................................12-9
Optional Practice 12-3: Additional Join Practice ............................................................................................12-15
Solutions 12-3: Additional Join Practice .........................................................................................................12-16

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

MySQL for Beginners


iv
Practices for Lesson 13: Table Subqueries ...................................................................................................13-1
Practices for Lesson 13: Overview .................................................................................................................13-2
Practice 13-1: Performing Different Types of Subqueries ..............................................................................13-3
Solutions 13-1: Performing Different Types of Subqueries ............................................................................13-4
Practice 13-2: Performing Advanced Subqueries...........................................................................................13-7
Solutions 13-2: Performing Several Advanced Subqueries ............................................................................13-8
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Practices for Lesson 14: MySQL Graphical User Interface Tools................................................................14-1


Practices for Lesson 14: Overview .................................................................................................................14-2
Practice 14-1: Creating a Data Model by Using MySQL Workbench .............................................................14-3
Practice 14-2: Creating a Server Instance by Using MySQL Workbench.......................................................14-6
Practice 14-3: Viewing MySQL Enterprise Monitor Demonstrations ..............................................................14-8
Optional Practice 14-4: Viewing the MySQL Workbench Demonstration .......................................................14-9
Optional Practice 14-5: Creating a Model for the Pets Database by Using MySQL Workbench ....................14-10
Practices for Lesson 15: Supplemental Information .....................................................................................15-1
Practices for Lesson 15: Overview .................................................................................................................15-2
Practice 15-1: Displaying Storage Engine Information ...................................................................................15-3
to
1n ense
Solutions 15-1: Displaying Storage Engine Information .................................................................................15-4
A
3% le lic
Practice 15-2: Displaying and Creating Views ...............................................................................................15-7
C
Solutions 15-2: Displaying and Creating Views ..............................................................................................15-8
l% erab
c
Practice 15-3: Obtaining Metadata .................................................................................................................15-10
n
0I ansf
Solutions 15-3: Obtaining Metadata ...............................................................................................................15-11
2
i l l a% on-tr
OPTIONAL Practice 15-4: Creating a Backup of MySQL Databases.............................................................15-15

bad s a n eฺ
OPTIONAL Practice 15-4: Create a Backup of MySQL Databases ...............................................................15-15
o
OPTIONAL Solutions 15-4: Creating a Backup of MySQL Databases ...........................................................15-16
B ha
d r a x ) G uid
OPTIONAL Solutions 15-4: Create a Backup of MySQL Databases..............................................................15-16
Practices for Lesson 16: Conclusion
j a ฺ m e n t
n.............................................................................................................16-1
e
Al ฺuad Stud y
Practices for Lesson 16..................................................................................................................................16-2
2 0
el%Terms:
Appendix A: Glossary of MySQL Terms
r r eo ............................................................................................................17-2
is
........................................................................................................17-1
t h
Glossary ofa
Y MySQL
@ co use Overview

Lesson a2: d
illa Solution Scripts...........................................................................................................18-1
Appendix B: Practice
MySQL Server and Client ..............................................................................................................18-2

l ฺ b ob 3: Database Basics............................................................................................................................18-4
Lesson

( yae Lesson 4: Database Design ...........................................................................................................................18-5


Lesson 5: Data Types ....................................................................................................................................18-6
Lesson 6: Database and Table Creation ........................................................................................................18-7
Lesson 7: Basic Queries ................................................................................................................................18-9
Lesson 8: Database and Table Maintenance .................................................................................................18-12
Lesson 9: Table Data Manipulation ................................................................................................................18-16
Lesson 10: Functions .....................................................................................................................................18-20
Lesson 11: Exporting and Importing Data ......................................................................................................18-22
Lesson 12: Joining Tables .............................................................................................................................18-24
Lesson 13: Table Subqueries ........................................................................................................................18-28
Lesson 14: MySQL GUIs ...............................................................................................................................18-31
Lesson 15: Supplemental Information ............................................................................................................18-32

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

MySQL for Beginners


v
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
Practices for n c l% era1:b
Lesson
2 0I ansf
Introduction
a% on-ttor MySQL
i l l
o ad 1a n ฺ
bChapter
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 ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction to MySQL


Chapter 1 - Page 1
Practices for Lesson 1: Overview
Practices Overview
This practice introduces you to online MySQL resources.

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

• A web browser is available for connection to the Internet.


• Your web browser allows connection to MySQL and Oracle websites.

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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction to MySQL


Chapter 1 - Page 2
Practice 1-1: Accessing MySQL Resources Online
Overview
In this practice, you review common web pages from the MySQL and Oracle websites that
contain information about MySQL products and services.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Duration
This practice takes approximately 15 minutes to complete.

Tasks
1. Open the MySQL website:
In your web browser, go to the following URL: www.mysql.com.
The MySQL home page appears.
2. Open the Products web page from the MySQL home page:
a. Click the Products tab located at the top of the page.
to
1n ense
b. Scroll down the page to review the product information provided.
A
3% le lic
A list of currently available products is presented (in the left navigation
C
menu) with links for further information.
n c l% erab
3.
0I ansf
Open the MySQL Enterprise Edition web page from the Products page:
2
a. Click the MySQL Enterprise Edition link.
i l l a% on-tr
bad s a n eฺ
b. Scroll down the page to review the details of MySQL Enterprise Edition.
o
Note the extended list of products (in the left navigation menu) with links for further
B ha
information.
d r a x ) G uid
j a n yฺm ent
c. Visit the links for Enterprise Monitor, Enterprise Backup, and Workbench to find out
l e
0A oฺuad s Stud
more about these MySQL Enterprise Edition tools.
2
el% corre e thi
4. Open the Services web page:
a
a. Click the Services tab located at the top of the page.
Y @
l l a us
b. Scroll down the page to review the service information provided, with links for further
b a di
information.
5.
l ฺb o Open the Training web page:
ya e a. Click the Learn More link below the MySQL Training title in the main window.
( A list of current training courses available appears.
b. Select your country from the pull-down menu and click the Go button to be taken to the
Oracle training website for your country.
c. Review the information on courses, learning paths, certification, and purchase options.
6. Open the Support web page:
a. Go back to the Training page and click the Support link in the left navigation menu.
b. Scroll down the page to review the support information provided, with links for further
information.
c. Note the Resources area, which links to Oracle website pages for additional
information and purchase.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction to MySQL


Chapter 1 - Page 3
7. Open the MySQL Developer Zone website:
In your web browser, go to the following URL: dev.mysql.com.
The MySQL Developer Zone (also known as the MySQL Community) home page
appears. This website contains many links to more information and access to a variety
of open communication forums. Notice the Downloads and Documentation tabs across
the top of the page.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

8. Open the News and Events page from MySQL Developer Zone:
a. Click the News and Events link located at the top of the page.
b. Use the left navigation menu to review the latest MySQL happenings, from news
stories to upcoming seminars.
9. Open the Oracle Products and Services: MySQL web page:
a. In your web browser, go to the following URL: www.oracle.com/us/products/mysql/.
b. Scroll down the page to review the MySQL product information provided.
A list of MySQL products and services appears, with links to further information.
10. Exit the web browser. 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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction to MySQL


Chapter 1 - Page 4
Solution 1-1: Accessing MySQL Resources Online
There are no solutions for this practice. See the practice tasks instructions.
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction to MySQL


Chapter 1 - Page 5
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction to MySQL


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

to
A 1n ense
C 3% le lic
Practices for n c l% era2:b
Lesson
2 0I ansf
MySQL a%Server- tr and Client
i l l
d 2a no n
b a
B
Chapter
o as i d eฺ
n d ra x) h t Gu
l e ja dyฺm den
2 0A oฺua s Stu
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: MySQL Server and Client


Chapter 2 - Page 1
Practices for Lesson 2: Overview
Practices Overview
These practices test your knowledge of the MySQL server and client installation. They target the
Windows operating system, provided in Oracle classrooms. For non-Oracle classrooms, you
may have to adjust file locations.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Assumptions
• The MySQL Installer file (mysql-installer-commercial-5.6.10.0.msi) for the
MySQL bundle (including the MySQL server) is in the D:\stage\MySQL directory.
• The Microsoft .NET Framework 4 Client Profile has been installed.
• MySQL Enterprise Backup 3.8 and MySQL Enterprise Monitor are installed.
• The world_innodb database file (world_innodb.sql) is in the D:\labs directory.

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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: MySQL Server and Client


Chapter 2 - Page 2
Practice 2-1: Installing and Starting the MySQL Server
Overview
In this practice, you use MySQL Installer to install and configure MySQL. It installs the following
components:
• MySQL Server 5.6.10 (Commercial/Enterprise Edition)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• MySQL Workbench SE 5.2.46


• MySQL Notifier 1.0.3
• MySQL Connector/ODBC 5.2.4
• MySQL Connector/C++ 1.1.2
• MySQL Connector/J 5.1.23
• MySQL Connector/NET 6.6.5
• MySQL Documentation 5.6.10
• MySQL Samples and Examples 5.6.10
n nse to
A 1
Duration
3 % e lice
This practice takes approximately 30 minutes to complete.
l % C bl
I n c f e ra
Tasks 20 tran s
1. Go to the D:\stage\MySQL directory by usingilWindows % n-
la oExplorer.
ba thed n
amysql-installer-commercial-
2. Execute the MySQL Installer by double-clicking
5.6.10.0.msi installation file. B o a s i d eฺ
d ra x) Welcome h Gu
3. When the installer has finished
j a n loading, the
ฺ m e n t window appears. Select Install
l e y
uad sselect tuthedcheck box to accept the terms, and then click
MySQL Products.
2 0A owindow,
4. In the License Agreement ฺ S
the Next e
a l% orre
button.
e t hi
5. In the YChoosing @ ca SetupuType
s window:
l l a
b a di Developer Default.
a. Select

l ฺ b ob. Enter (or confirm) the “Installation Path” as: D:\Program Files\MySQL\.
( yae c. Enter (or confirm) the “Data Path” as: D:\ProgramData\MySQL\MySQL Server
5.6\.
d. Click the Next button.
The Check Requirements window appears.
6. The Check Requirements window lists any dependencies on external software:
• Microsoft .NET Framework 4 (already installed)
• Microsoft Visual C++ 2010 32-bit run time
• Microsoft Excel 2007 or greater
• Visual Studio Tools for Office 2010 run time
7. The green check mark next to .NET Framework 4 shows it is already installed. You need to
install the other items in the list.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: MySQL Server and Client


Chapter 2 - Page 3
8. Click the Execute button to install Microsoft Visual C++ 2010 32-bit run time:
a. Select the check box to accept the license terms.
b. Click the Install button.
c. When the Installation is Complete window appears, click the Finish button.
9. There is now a blue arrow next to Microsoft Excel 2007 or greater in the Check
Requirements window.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

a. Click the Execute button.


MySQL Installer checks if Microsoft Excel or Visual Studio are installed. They are not,
so it refreshes the list of requirements to exclude these dependencies.
The required software (Microsoft .NET Framework 4 Client Profile and Microsoft Visual
C++ 2010 32-bit runtime) has now been installed and the MySQL installation can
proceed.
b. Click Next.
10. The Installation Progress window lists all MySQL products to be installed:
• MySQL Server 5.6.10 to
• MySQL Workbench SE 5.2.46 A 1n ense
• MySQL Notifier 1.0.3
C 3% le lic
• Connector/ODBC 5.2.4
n c l% erab
• Connector/C++ 1.1.2 2 0I ansf
• Connector/J 5.1.23
i l l a% on-tr
• Connector/NET 6.6.5
o bad s a n eฺ
• MySQL Documentation 5.6.10
r a B ha uid
• d
n yฺm ent
Samples and Examples 5.6.10. x ) G
l e j a
11.
0A oฺuad s Stud
Install the MySQL products:
2
el% corre e thi
a. Click the Execute button.
a
The installation process takes a few minutes. When complete, the Status column for all
Y @
a us
products shows “Install success”.
l l
a di
b. Click the Next button.
b
12.
l ฺ b o
Configure the software components in the Configuration Overview window:

( yae A green arrow points to MySQL Server 5.6.10. Click Next to configure MySQL Server
5.6.10.
13. In the MySQL Server Configuration (1/3) window:
a. Server Configuration Type: From the Config Type drop-down list, select Development
Machine.
b. Select (or confirm) Enable TCP/IP Networking and Port Number of 3306.
c. Select (or confirm) “Open Firewall port for network access”.
d. Click Next.
14. In the MySQL Server Configuration (2/3) window:
a. In Root Account Password, enter and confirm the password oracle.
b. Click the Next button.
15. In the MySQL Server Configuration (3/3) window:
a. Enter (or confirm) Windows Service Name is MySQL56.
b. Select (or confirm) “Start the MySQL Server at System Startup”.
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: MySQL Server and Client


Chapter 2 - Page 4
c. Select (or confirm) Run Windows Service as “Standard System Account”.
d. Click Next.
16. The Configuration Overview window appears and shows the configuration progress for the
MySQL server.
This takes a few moments. When complete, a green tick appears next to MySQL
Server 5.6.10 and the “Action to be performed” column reads “Configuration
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Complete”.
17. There is now a green arrow next to Samples and Examples, and the Action to be performed
column reads “Initial Configuration”.
a. Click Next to configure Samples and Examples.
b. Configuration takes a minute or two. When complete, click Next.
18. In the Installation complete window:
a. Deselect the Start MySQL Workbench after Setup check box.
b. Click the Finish button.
The final MySQL Installer window closes. You have installed and configured MySQL to
Server and the other tools required for this course.
A 1n ense
19. Confirm the installation:
C 3% le lic
n c l% erab
a. Click the Windows Start button (in the lower left corner of the Windows desktop).
b. Select All Programs.
2 0I ansf
i l l a% on-tr
c. Select MySQL. The folder includes the following programs:

bad s a n eฺ
• MySQL Workbench 5.2 SE
• MySQL Connector/Net 6.6.5 o
B ha
• d r a x ) G uid
MySQL Enterprise Backup 3.8 (pre-installed)
j a n yฺm ent
• l e
MySQL Enterprise Monitor (pre-installed)
• 2 0A oฺuad s Stud
MySQL Installer

a el% corre e thi
MySQL Notifier 1.0.3
Y @
• us
MySQL Server 5.6
l l a
b a di
Note: MySQL Enterprise Backup and MySQL Enterprise Monitor are pre-installed for you.
ฺbo
20. Attempt to start the mysql client from the Windows command prompt:
l
ya e a. Click the Start button (at the lower-left of the screen).
( b. Select Run.
c. In the Open field, enter cmd and press Enter.
A command-prompt window opens.
Note: You can also use the Command Prompt shortcut icon on the desktop.
The prompt shows the current working directory, for example:
D:\Users\Administrator>
Note: The practice steps use cmd> to refer to this prompt from now on. Do not attempt
to type the prompt, just enter the commands that appear in bold after it:
cmd> enter commands here
d. Enter the following at the command prompt:
cmd> mysql
e. Press Enter.
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: MySQL Server and Client


Chapter 2 - Page 5
Windows reports that it cannot find the mysql program:
cmd> mysql
’mysql’ is not recognized as an internal or external command,
operable program or batch file.
This is because Windows has not been told where to look for the mysql program. So
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

that Windows recognizes the mysql client program, you need to add it to the PATH
environment variable.
f. Type exit and then press Enter to close the command-prompt window.
21. Add the mysql client program to the PATH:
a. Click the Windows Start button.
b. Right-click the Computer link.
c. From the context menu that appears, select Properties.
d. Select Advanced System Settings.
e. Click the Advanced tab.
to
f. Click the “Environment variables” button.
A 1n ense
The Environment variables window opens.
C 3% le lic
n c l% erab
g. From the list of System variables at the bottom of this window, select Path.
h. Click Edit.
2 0I ansf
The Edit System Variable window opens.
i l l a% on-tr
bad s a n eฺ
i. Click somewhere in the Variable Value field and press the End button to move to the
end of the line. o
a
j. Type the following exactly as shown:
r B ha uid
d x
n yฺm Server ) G
t 5.6\bin;
j a
;D:\Program Files\MySQL\MySQL
l e e n
− Note: include
2 ฺ tudbeginning and end of the file path.
uad s atSthe
0Atheosemicolons
k. Click OK
a e reEdit System
l%to exitorthe
e t hi Variable window.
l. YClick OK to c s
exit the Environment Variables window.
a @ u
m. Click
a d illOK to exit the System Properties window.
l on.b Close the System Window.
ฺb Connect to the MySQL server by using the mysql client program:
ya e22.
( a. Click the Windows Start button.
b. Select Run.
c. In the Open field, enter cmd and press Enter.
A command-prompt window opens, with the prompt located at the current user’s
“home” directory.
d. Enter the following at the command prompt:
cmd> mysql -u root -p
Enter password: oracle

Welcome to the MySQL monitor. Commands end with ; or \g.


Your MySQL connection id is 3
Server version: 5.6.10-enterprise-commercial-advanced MySQL Enterprise
Server – Advanced Edition (Commercial)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: MySQL Server and Client


Chapter 2 - Page 6
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights
reserved.

Oracle is a registered trademark of Oracle Corporation and/or its


affiliates. Other names may be trademarks of their respective
owners.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Type 'help;' or '\h' for help. Type '\c' to clear the current input
statement.

mysql>
− In this course, the username is root and the password used is oracle. As you
type the password, it appears as ****** on your screen.
− The current version of the MySQL server is displayed.
− The “MySQL connection id” might differ on your machine.
− When the client is started, the standard command prompt is replaced by the
mysql> prompt. to
23. Exit the mysql client:
A 1n ense
Enter the following from the mysql> prompt:
C 3% le lic
mysql> EXIT
n c l% erab
The following message is displayed and the standard I
0command n s f is returned:
prompt
2
Bye
i l l a% on-tra
cmd>
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: MySQL Server and Client


Chapter 2 - Page 7
Solution 2-1: Installing and Starting the MySQL Server
There are no solutions for this practice. See the practice instructions.
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: MySQL Server and Client


Chapter 2 - Page 8
Practice 2-2: Using the Keyboard Editing and Tee Commands
Overview
In this practice, you set some sensible defaults for the command-line window and then use the
keyboard editing methods to work with the mysql client. You also create a tee file to document
all mysql session activities.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Duration
This practice takes approximately 5 minutes to complete.

Tasks
Note: Execute each command with the Enter or Return key, unless otherwise specified.
1. Change the default look and behavior of the Windows command prompt:
a. Right-click the command-prompt window’s title bar and select Defaults from the context
menu. The Console Windows Properties dialog box appears.
to
b. Select the Options tab and make the following change:
A 1n ense
− Edit Options: Select the QuickEdit Mode check box.
c. Select the Font tab and make the following changes: C 3% le lic
n c l% erab
− Font: Select Consolas.
2 0I ansf
− Size: Select 18.
i l l a% on-tr
bad s a n eฺ
d. Select the Layout tab and make the following changes:
o
− Screen Buffer Size: Width: 160, Height: 300
B ha
r a )
− Window Size: Width: 160, Height: 40
d x G uid
j a n yฺm ent
e. (Optional) Select the Colors tab.
l e
0A oฺuad s Stud
− Select the Screen Text radio button.
2
el% corre e thi
− Select a font color from the color palette.
a
Y @ us
− Select the Screen Background radio button.
l l a
b a di
− Select a background color from the color palette.

l ฺb o f. Click OK to close the “Console Windows Properties” window.

ya e g. Close the command-prompt window.


( 2. Re-open the command-prompt window to apply the changes you made:
a. Click the Windows Start button.
b. Select Run.
c. In the Open field, enter cmd and press Enter.
The new settings are applied.
3. Connect to the MySQL server by using the mysql client program.
Enter the following at the command prompt:
cmd> mysql -u root -p
Enter password: oracle
4. View help for the mysql client commands (non-SQL) by using the Help command (\h).
Execute the following statement:
mysql> \h

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: MySQL Server and Client


Chapter 2 - Page 9
It returns the following list of commands and their descriptions:
...
List of all MySQL commands:
Note that all text commands must be first on line and end with ';'
? (\?) Synonym for `help’.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

clear (\c) Clear the current input statement.


connect (\r) Reconnect to the server. Optional arguments are db and
host.
delimiter (\d) Set statement delimiter.
ego (\G) Send command to mysql server, display result
vertically.
exit (\q) Exit mysql. Same as quit.
go (\g) Send command to mysql server.
help (\h) Display this help.
notee (\t) Don't write into outfile.
to
1n ense
print (\p) Print current command.
prompt (\R) Change your mysql prompt. A
quit (\q) Quit mysql.
C 3% le lic
rehash (\#) Rebuild completion hash.
n c l% erab
source
0I ansf
(\.) Execute an SQL script file. Takes a file name as an
2
a% on-tr
argument.
i l l
bad s a n eฺ
status (\s) Get status information from the server.
tee
o
(\T) Set outfile [to_outfile]. Append everything into given
B ha
outfile.
d r a x ) G uid
use
n yฺm ent
(\u) Use another database. Takes database name as argument.
j a
l e
0A oฺuad s Stud
charset (\C) Switch to another charset. Might be needed for
processing binlog with multi-byte charsets.
2
el% corre e thi
warnings (\W) Show warnings after every statement.
a
Y @ us
nowarning (\w) Don't show warnings after every statement.
l l a
b a di server side help, type 'help contents'
For

l ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: MySQL Server and Client


Chapter 2 - Page 10
5. Create a tee file to log your mysql client session:
Execute the following statement at the prompt:
mysql> tee D:\labs\Lesson2_tee.txt
You get a message that confirms the creation of the tee file:
Logging to file 'D:\labs\Lesson2_tee.txt'
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

6. Use the keyboard to re-run an earlier command:


Retrieve the help command by pressing the up-arrow key ↑ twice and execute it
again.
This returns the command before the last command issued at the prompt which, in this
case, is the \h command.
7. Use the keyboard to return to the very last command entry:
Press the down-arrow key ↓ once to retrieve the tee command. Do not press Enter.
8. Use the keyboard to position the cursor within the command:
Press the left-arrow ← key four times to position the cursor on the dot “.” in the file to
name.
A 1n ense
3% le lic
This demonstrates the use of the arrow keys to complete command-line edits by
C
positioning the cursor for changes.
n c l% erab
9. Use a keyboard editing key to delete portions of a command:
2 0I ansf
i l a% on-tr
Using the Backspace key, delete the current Lesson2_tee part of the tee file name
l
and replace it with Test, leaving the rest of the line intact.
mysql> tee D:\labs\Test.txt o bad s a n eฺ
a B ha id
a. Press the End key to move d rthe cursor
x )to the endG ofuthe command.
j a n ythe ฺ m editede n t
b. Press the Enter key
l e to execute
d command.
10. Cancel the Test.txt
2 0A teeoฺfile: uad s Stu
Issueethe
a l%noteeo r e
rcommand:
e t hi
Y
mysql>@
c
notee us
ill a
It d
a returns the following to confirm the creation of the file:
l ฺ b ob Outfile disabled.
( yae11. Return to the first tee command by pressing the up-arrow key ↑ four times.
Re-execute the command to restart the tee file logging:
mysql> tee D:\labs\Lesson2_tee.txt
It returns the following to confirm the creation of the file:
Logging to file 'D:\labs\Lesson2_tee.txt'
12. Start to cancel the tee file, but use the mysql command, which aborts the command
execution:
Issue the notee command, and then add \c to abort:
mysql> notee \c
It returns the prompt without executing the command:
mysql>

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: MySQL Server and Client


Chapter 2 - Page 11
13. View the current Lesson2_tee.txt file:
a. Using Windows Explorer, go to the D:\labs directory.
Note: Windows hides file extensions by default. Follow these steps to display them:
− Press the Alt key to show the Windows Explorer menu bar.
− Select Tools > Folder options to display the Folder Options window and click the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

View tab.
− In the Advanced Settings area, deselect “Hide extensions for known file types”.
− Click the Apply to Folders button in the Folder views area.
− In the Folder Views dialog box, click Yes.
− Click OK to close the Folder Options window.
b. Double-click the Lesson2_tee.txt file. The file opens in Notepad and the contents
show all the commands and results from the current session.
The file shows the commands and results from the first execution of this tee file, then
starts again from when it was re-executed.
to
c. Close the Lesson2_tee.txt file.
A 1n ense
d. Close Windows Explorer.
C 3% le lic
n c l% erab
Note: Do not close the mysql client. You use it in the next practice.

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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: MySQL Server and Client


Chapter 2 - Page 12
Solution 2-2: Using the Keyboard Editing and Tee Commands
There no solutions for this practice. See the practice instructions.
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: MySQL Server and Client


Chapter 2 - Page 13
Practice 2-3: Creating the world_innodb Database

Overview
In this practice, you create and populate the world_innodb database, which you use in
practices throughout this course.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Duration
This practice takes approximately 5 minutes to complete.

Tasks
1. Create the world_innodb database within the mysql client:
Enter the following at the mysql prompt from the previous practice:
mysql> CREATE DATABASE world_innodb CHARACTER SET latin1;
It returns the following message to indicate that the database was created:
Query OK, 1 row affected (0.02 sec) n nse to
A 1
3 %
Note: Adding the latin1 character set to the above database creation statement ce it
makes
l i
compatible with the script you use to populate it below.
l % C ble
2. Now you have created the world_innodb database, tell the
I n c to fuse
client e rit:a
Execute the following statement at the mysql> prompt:20 tran s
%
lla non-
mysql> USE world_innodb d i
− Note: You do not need a semicolon
B obaat the
a s a of a USE
end
i d eฺ statement.
It returns the following message
n d x ) h thatt G
ra to indicate theudatabase selection changed:
Database changed
l e ja dyฺm den
3. 2 0A oฺuadatabase
Populate the world_innodb S tu data:
with
Execute rre statement
el%thecfollowing s
thi at the mysql> prompt:
Y a o e
mysql>
l l a @ us
SOURCE D:\labs\world_innodb.sql
i
− dNote: Do not include a semicolon at the end of the SOURCE statement
a
o b
e l ฺb MySQL displays multiple instances of the following message while populating
( ya world_innodb. The process takes several minutes.
Query OK, 0 rows affected (0.00 sec)
When the script has finished executing, you are returned to the mysql> prompt.
Note: Do not attempt to review the database contents yet. You do this in a later practice.
4. Exit the mysql client:
Enter the following at the mysql> prompt:
mysql> EXIT
The following message appears and control returns to the standard command prompt:
Bye
cmd>

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: MySQL Server and Client


Chapter 2 - Page 14
Solutions 2-3: Creating the world_innodb Database
There are no solutions for this practice. See the practice instructions.
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: MySQL Server and Client


Chapter 2 - Page 15
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: MySQL Server and Client


Chapter 2 - Page 16
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
Practices for n c l% era3:b
Lesson
2 0I ansf
MySQL a%Database
- tr Basics
i l l
d 3a no n
b a
B
Chapter
o as i d eฺ
n d ra x) h t Gu
l e ja dyฺm den
2 0A oฺua s Stu
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: MySQL Database Basics


Chapter 3 - Page 1
Practices for Lesson 3: Overview
Practices Overview
These practices test your knowledge of database basics. They target the Windows operating
system, provided in Oracle classrooms. For non-Oracle classrooms, you might need to adjust
file locations.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Assumptions
• You have installed and configured MySQL Server.
• You have created and populated the world_innodb database.
• You can access the mysql client from a command-line prompt.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm 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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: MySQL Database Basics


Chapter 3 - Page 2
Practice 3-1: Quiz – Database Basics
Overview
In this quiz, you answer questions about database basics.

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

This practice takes approximately 15 minutes to complete.

Quiz Questions
Choose the best answer from those provided.
1. What does RDBMS stand for?
a. Relative Database Basic Manipulation System
b. Relative Data Basic Management System
c. Relational Database Management System
d. None of the above to
2. An RDBMS organizes and stores data in tables.
A 1n ense
a. True
C 3% le lic
b. False
n c l% erab
0I ansf
3. An association between database entities is called a ____________ and different
2
categories of these exist.
i l l a% on-tr
bad s a n eฺ
a. Relationship
b. Line o
B ha
c. System d r a x ) G uid
d. All of the above j a n yฺm ent
l e
0A oฺuad s Stud
4. An RDBMS is presented as two-dimensional tables that consist of columns and
2
el% corre e thi
____________.
a
Y @
a. Schemas
us
l l a
b. Sets
b a di
c. Values
l ฺbo
ya e d. None of the above
( 5. A one-to-one relationship exists when you associate a single entity with another single
entity.
a. True
b. False
6. A row in a database table contains a value for each ____________ in the table.
a. Row
b. Column
c. Relationship
7. The SQL acronym stands for Structural Queries Linked.
a. True
b. False

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: MySQL Database Basics


Chapter 3 - Page 3
8. The set of SQL statements that modify data is called ____________ ____________
____________.
a. Data manipulation language
b. Data definition language
c. Database modification language
9. CREATE DATABASE is a SQL data ____________ language statement.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

a. Manipulation
b. Definition
c. Modification
d. None of the above
10. Identify the benefits of using MySQL:
a. Runs on multiple operating systems
b. Is highly customizable
c. Can be open source or with commercial licenses
to
d. Supports very large databases
A 1n ense
e. All of the above
C 3% le lic
n c l% erab
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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: MySQL Database Basics


Chapter 3 - Page 4
Solutions 3-1: Quiz – Database Basics
Quiz Solutions
1. c. Relational Database Management System
2. a. True
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

3. a. Relationship
4. d. None of the above. The correct answer is rows.
5. a. True
6. b. Column.
7. b. False. The correct answer is Structured Query Language.
8. a. Data manipulation language
9. b. Definition
10. e. All of the above

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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: MySQL Database Basics


Chapter 3 - Page 5
Practice 3-2: Identifying the Structure of a Table
Overview
In this practice, you identify the relational characteristics of a table.

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

This practice takes approximately 10 minutes to complete.

Tasks
The following is a partial list of the contents of the City table from the world_innodb
database. Refer to this for the questions that follow.
+----+----------------+-------------+---------------+------------+
| ID | Name | CountryCode | District | Population |
+----+----------------+-------------+---------------+------------+
| 1 | Kabul | AFG | Kabol | 1780000 |
| 2 | Qandahar | AFG | Qandahar | 237500 | to
| 3 | Herat | AFG | Herat |
A 1n ense
186800 |

3% le lic
| 4 | Mazar-e-Sharif | AFG | Balkh | 127800 |
| 5 | Amsterdam | NLD | Noord-Holland |C
l% erab
731200 |
| 6 | Rotterdam | NLD
c
| Zuid-Holland |
n
593321 |
| 7 | Den Haag | NLD
0I ansf
| Zuid-Holland |
2
440900 |

a% on-tr
| 8 | Utrecht | NLD | Utrecht | 234323 |
... i l l
1. How many columns does this table contain?
o bad s a n eฺ
2. List the names of the columns. a B ha Guid
d r
n partial x ) t
3. How many rows appear inathe
e j y ฺ m
list?
e n
4. Al ฺinuthe
Is the city with Amsterdam
2 0 adNameScolumn tud in the same District as Kabul?
5. What is thel%
e r r
Populationeoof thethcityisof Utrecht?
6. a the crows
Ydelete
If you o (fromsethis list) with a CountryCode of AFG, what are the ID values
l l
of the deleted
i a rows? u
@
7.
oCanbathed city of Den Haag belong to more than one District in the table structure shown?
e l
8. ฺb Can the District of Zuid-Holland contain more than one city?
( ya

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: MySQL Database Basics


Chapter 3 - Page 6
Solutions 3-2: Identifying the Structure of a Table
Tasks
1. 5
2. ID, Name, CountryCode, District, Population
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

3. 8
4. No. Amsterdam is in the district of Noord-Holland.
5. 234323
6. 1, 2, 3, and 4
7. No. This would result in two values for the District column. Only one is possible in the
table structure shown.
You could have two rows with the same Name and different values in the District
column. However, you would need a different way to uniquely identify a city, because ID
would not work in this instance.
to
1n ense
8. Yes. Zuid-Holland appears in the Rotterdam and Den Haag rows because both these cities
are contained with it. A
C 3% le lic
n c l% erab
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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: MySQL Database Basics


Chapter 3 - Page 7
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: MySQL Database Basics


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

to
A 1n ense
C 3% le lic
Practices for n c l% era4:b
Lesson
2 0I ansf
Database a% oDesign
-tr
i l l n
o ad 4a n ฺ
bChapter
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 ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Database Design


Chapter 4 - Page 1
Practices for Lesson 4: Overview
Practices Overview
These practices test your knowledge of database design. They target the Windows operating
system, provided in Oracle classrooms. For non-Oracle classrooms, you might need to adjust
file locations.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Assumptions
• You have installed and configured MySQL Server.
• You have created and populated the world_innodb database.
• You can access the mysql client from a command-line prompt.

Note: In this practice the first letters of table names are in uppercase. Windows is not case-
sensitive but some operating systems are, so it is good practice to use proper capitalization.
The SQL statements are all in uppercase for clarity, but this is not required. 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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Database Design


Chapter 4 - Page 2
Practice 4-1: Quiz – Database Design
Overview
In this quiz, you answer questions about database design.

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

This practice takes approximately 10 minutes to complete.

Quiz Questions
Choose the best answer from those provided for each multiple choice or True/False question.
1. The ____________ ____________ is a candidate key that best defines exactly one
unique row.
a. Unique key
b. Foreign key
c. Relationship key
to
d. Primary key
A 1n ense
3% le lic
2. The ____________ ____________ ____________ is a high-level, graphical depiction of
C
a data model. It assists in database design.
n c l% erab
a. Entity relationship model
2 0I ansf
a% on-tr
b. Database modeling process
c. Entity relationship diagram i l l
o bad s a n eฺ
3. You use the SHOW DATABASES SQL statement to list the available databases.
r a B ha uid
a. True
d
n yฺm ent x ) G
b. False
l e j a
0A oฺuad s Stud
4. Which statement shows a list of table column names and settings?
2
el% corre e thi
a. SHOW TABLE COLUMNS
a
Y @
b. DESCRIBE <table_name>
us
l l a
5. b
The
di
c. SELECT * FROM <table_name>
a
following statement retrieves all the records from the CountryLanguage table:
l ฺb o
ya e mysql> SELECT * FROM CountryLanguage;
( a. True
b. False

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Database Design


Chapter 4 - Page 3
6. The following statement displays the City table columns and settings. Based on the
output, which column is the primary key?
mysql> DESCRIBE City;
+-------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+----------+------+-----+---------+----------------+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| ID | int(11) | NO | PRI | NULL | auto_increment |


| Name | char(35) | NO | | | |
| CountryCode | char(3) | NO | MUL | | |
| District | char(20) | NO | | | |
| Population | int(11) | NO | | 0 | |
+-------------+----------+------+-----+---------+----------------+
5 rows in set (0.30 sec)
a. CountryCode
b. Name
c. ID
d. None of the above to
7. 1n ense
Using the output from the DESCRIBE City statement, which column is a nonunique index
A
that is part of a multiple-column primary key?
C 3% le lic
a. Population
n c l% erab
b. Name
2 0I ansf
c. ID
i l l a% on-tr
bad s a n eฺ
d. None of the above
8. o
B ha
Identify the statement that gives the following output (assume a USE world_innodb
r a
statement has already been issued).
d x ) G uid
j a n yฺm ent
l e
0A oฺuad s| Stud
+------------------------+
| Tables_in_world_innodb
2
l% orre hi |
+------------------------+
a e
| city
| country c e t
Y @ u s |
i ll a
| countrylanguage |
d
oba3 rows in set (0.19 sec)
+------------------------+

e l ฺb a.
( ya SHOW TABLES;
b. SHOW world_innodb;
c. DESCRIBE TABLES;
d. SHOW DATABASE TABLES;
9. Poorly designed table structures result in duplicate data, redundant data, and difficulty
using the data.
a. True
b. False

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Database Design


Chapter 4 - Page 4
10. The normalization process ensures database integrity. The first three levels, or
____________ ____________ are adequate for most databases.
a. Normalization levels
b. Normal forms
c. Normalization forms
d. None of the above
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

11. Third normal form is the highest level of normalization that you can achieve within a
database.
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 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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Database Design


Chapter 4 - Page 5
Solutions 4-1: Quiz – Database Design
Quiz Solutions
1. d. Primary key
2. c. Entity relationship diagram
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

3. a. True
4. b. DESCRIBE <table_name>;
5. a. True
6. c. ID
7. d. None of the above. The correct answer is CountryCode, which is indicated by MUL
under the Key attribute.
8. a. SHOW TABLES;
9. a. True
10. b. Normal forms
to
11. 1n ense
b. False. There are several normal forms above third, although it is rarely necessary for you
A
to go beyond the first three.
C 3% le lic
n c l% erab
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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Database Design


Chapter 4 - Page 6
Practice 4-2: Evaluating a Database
Overview
In this practice, you view and evaluate the contents of the world_innodb database, using the
mysql client.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Note: The data contained in the world_innodb database (with regard to continent,
country, and city details) is not accurate. It is used only as a teaching tool.

Duration
This practice takes approximately 15 minutes to complete.

Tasks
1. Start the mysql client.
2. List all the databases available in the current mysql session.
3. Change the current database to world_innodb. to
4. List all the tables in the world_innodb database.
A 1n ense
5. Show the structure of the City table.
C 3% le lic
6. List the contents of the City table.
n c l% erab
7. Show the structure of the Country table. 2 0I ansf
8. List the contents of the Country table.
i l l a% on-tr
9. Show the structure of the CountryLanguage
o badtable. a n ฺ
a B htable.
10. List the contents of the CountryLanguage
r ) as uide
Note: Keep your mysql session a d form
nopen n G
thexnext practice.
t
j
le ady tude ฺ
2 0 A ฺu is S
% e o
el rr th
Ya @co use
d i lla
b o ba
a e lฺ
( y

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Database Design


Chapter 4 - Page 7
Solutions 4-2: Evaluating a Database
Tasks
1. Start the mysql client:
Enter the following at the command prompt to log in to the MySQL server and receive
the welcome message shown below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

cmd> mysql -u root -p


Enter password: oracle

Welcome to the MySQL monitor. Commands end with ; or \g.


Your MySQL connection id is 4
Server version: 5.6.10-enterprise-commercial-advanced MySQL Enterprise
Server – Advanced Edition (Commercial)

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights
reserved.
to
Oracle is a registered trademark of Oracle Corporation and/or its
A 1n ense
affiliates. Other names may be trademarks of their respective
C 3% le lic
l% erab
owners.

Type 'help;' or '\h' for help. Type '\c' to0Iclear the n c fcurrent input
2 n s
a% on-tra
statement.
i l l
mysql>
o bad s a n eฺ
2. List all the databases available inatheBcurrenthmysql
a session: uid
d r x
n and yresults ) G
tshown below:
Compare your statement
l e j a ฺ m to those
e n
0 oฺuad s Stud
mysql> SHOWADATABASES;
2
a e l% orre |thi
+--------------------+
| Database
Y @ c use
+--------------------+
i lla
| information_schema
|d
|

oba| performance_schema |
mysql |

e l ฺb | sakila |
( ya | test
| world
|
|
| world_innodb |
+--------------------+
7 rows in set (0.00 sec)
− There are other databases in addition to world_innodb. MySQL Installer installed
these databases.
3. Change the current database to world_innodb:
Compare your statement and results to those shown below:
mysql> USE world_innodb
Database changed

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Database Design


Chapter 4 - Page 8
4. List all the tables in the world_innodb database:
Compare your statement and results to those shown below:
mysql> SHOW TABLES;
+------------------------+
| Tables_in_world_innodb |
+------------------------+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| city |
| country |
| countrylanguage |
+------------------------+
3 rows in set (0.13 sec)
5. Show the structure of the City table:
Compare your statement and results to those shown below::
mysql> DESCRIBE City;
+-------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
to
1n ense
+-------------+----------+------+-----+---------+----------------+
| ID | int(11) | NO | PRI | NULL | auto_increment |
A
| Name | char(35) | NO
| CountryCode | char(3) | NO
| |
| MUL |
|
|
|
C
| 3% le lic
| District | char(20) | NO | | |
n c l% erab
|
| Population | int(11) | NO | | 0 |
2 0I ansf |

a% on-tr
+-------------+----------+------+-----+---------+----------------+
5 rows in set (0.06 sec)
i l l
bad s about
The DESCRIBE statement provides information
o a n the columns
e ฺ in the City table:
− Field: Column name r B
a x) ha Guid
− Type: Data type jan
d m n t
l e y ฺ e
d values
− Null: Whether
2 ฺ uadaccepts
0A theocolumn S tunull
− Key:e l % r
Whetherrtheecolumnthisispart of a key/index
a
−YDefault:
o value
cDefault se of the column
@ u
lla Any additional settings for the column
− d i
oba
Extra:

e
6.
l ฺb List the contents of the City table:

( ya Compare your statement and results to those shown below:


mysql> SELECT * FROM City;
+------+----------------+-------------+--------------+------------+
| ID | Name | CountryCode | District | Population |
+------+----------------+-------------+--------------+------------+
| 1 | Kabul | AFG | Kabol | 1780000 |
| 2 | Qandahar | AFG | Qandahar | 237500 |
| 3 | Herat | AFG | Herat | 186800 |
| 4 | Mazar-e-Sharif | AFG | Balkh | 127800 |
| 5 | Amsterdam | NLD | Noord-Holland| 731200 |
...
| 4077 | Jabaliya | PSE | North Gaza | 113901 |
| 4078 | Nablus | PSE | Nablus | 100231 |
| 4079 | Rafah | PSE | Rafah | 92020 |
+------+----------------+-------------+--------------+------------+
4079 rows in set (0.01 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Database Design


Chapter 4 - Page 9
7. Show the structure of the Country table:
Compare your statement and results to those shown below:
mysql> DESCRIBE Country;
+----------------+--------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------------+------+-----+---------+-------+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| Code | char(3) | NO | PRI | | |


| Name | char(52) | NO | | | |
| Continent | enum('Asia', | | | | |
| | 'Europe', | | | | |
| | 'North America' | | | | |
| | 'Africa' | | | | |
| | 'Oceania', | | | | |
| | 'Antarctica', | | | | |
| | 'South America') | NO | | Asia | |
| Region | char(26) | NO | | | |
| SurfaceArea | float(10,2) | NO | | 0.00 | |
| IndepYear | smallint(6) | YES | | NULL | |
| Population | int(11) | NO | | 0 | |
| LifeExpectancy | float(3,1) | YES | | NULL | | to
| GNP | float(10,2) | YES | | NULL | |
A 1n ense
3% le lic
| GNPOld | float(10,2) | YES | | NULL | |
| LocalName | char(45) | NO | | | |
| GovernmentForm | char(45) | NO | | | C
l% erab
|
| HeadOfState | char(60) | YES | | NULL
n c
| |
| Capital | int(11) | YES |
0I ansf
| NULL
2 | |

a% on-tr
| Code2 | char(2) | NO | | | |
i l l
+----------------+--------------------+------+-----+---------+-------+
15 rows in set (0.06 sec)
o b ad a n ฺ
8. List the contents of the Country table:
r a B has uide
The statement shown below
a n d usesmthex)\G terminator,
n t G which displays table contents
j the
lterminatoroutputฺ
e adisycase-sensitive
vertically. This makes more
de andwhen
readable there are a large number of
columns. The0\G
2 A ฺ u sS t u must always be in uppercase.
l%SELECT o i
re* FROMthCountry\G
a e
mysql>
o
c usr e
Y
***************************
@ 1. row ***************************
ill a Code: ABW

b a d Name: Aruba

l ฺb o Continent: North America

ya e Region: Caribbean
( SurfaceArea: 193.00
IndepYear: NULL
Population: 103000
LifeExpectancy: 78.4
GNP: 828.00
GNPOld: 793.00
LocalName: Aruba
GovernmentForm: Nonmetropolitan Territory of The Netherlands
HeadOfState: Beatrix
Capital: 129
Code2: AW
...
*************************** 238. row ***************************
Code: ZMB
Name: Zambia
Continent: Africa
Region: Eastern Africa
SurfaceArea: 752618.00

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Database Design


Chapter 4 - Page 10
IndepYear: 1964
Population: 9169000
LifeExpectancy: 37.2
GNP: 3377.00
GNPOld: 3922.00
LocalName: Zambia
GovernmentForm: Republic
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

HeadOfState: Frederick Chiluba


Capital: 3162
Code2: ZM
*************************** 239. row ***************************
Code: ZWE
Name: Zimbabwe
Continent: Africa
Region: Eastern Africa
SurfaceArea: 390757.00
IndepYear: 1980
Population: 11669000
LifeExpectancy: 37.8
to
GNP: 5951.00
GNPOld: 8670.00 A 1n ense
LocalName: Zimbabwe
C 3% le lic
GovernmentForm: Republic
n c l% erab
0I ansf
HeadOfState: Robert G. Mugabe
Capital: 4068
2
Code2: ZW
i l l a% on-tr
badtable:
239 rows in set (0.00 sec)
a n ฺ
9. o
Show the structure of the CountryLanguage
B to h as uibelow: de
Compare your statement d r
andaresults ) those shown
j a n yฺmx ent G
mysql> DESCRIBE
A le adCountryLanguage;
t ud
2 0 ฺ u S
+-------------+---------------+------+-----+---------+-------+
o his | Null | Key | Default | Extra |
| Field
e l % rr|eType t
a o | char(3)e
+-------------+---------------+------+-----+---------+-------+
Y c s
ll a @
| CountryCode
u | NO | PRI | | |

d i
| Language | char(30) | NO | PRI | | |

oba| Percentage | float(4,1) | NO | | 0.0 |


| IsOfficial | enum('T','F') | NO | | F | |

e l ฺb +-------------+---------------+------+-----+---------+-------+
|

( ya 4 rows in set (0.11 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Database Design


Chapter 4 - Page 11
10. List the contents of the CountryLanguage table:
Compare your statement and results to those shown below:
mysql> SELECT * FROM CountryLanguage;
+-------------+------------+------------+------------+
| CountryCode | Language | IsOfficial | Percentage |
+-------------+------------+------------+------------+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| ABW | Dutch | T | 5.3 |


| ABW | English | F | 9.5 |
| ABW | Papiamento | F | 76.7 |
...
| ZWE | English | T | 2.2 |
| ZWE | Ndebele | F | 16.2 |
| ZWE | Nyanja | F | 2.2 |
| ZWE | Shona | F | 72.1 |
+-------------+------------+------------+------------+
984 rows in set (0.01 sec)
Note: Keep your mysql session open for the next practice.
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Database Design


Chapter 4 - Page 12
Practice 4-3: Creating a Structure Diagram
Overview
In this practice, you use SQL DESCRIBE statements and an entity relationship diagram to
evaluate the design of the world_innodb database. Use your open mysql session to issue
any statements you feel will help you better understand world_innodb.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Duration
This practice takes approximately 25 minutes to complete.

Tasks
1. Explain the purpose of the world_innodb database, using the output from the DESCRIBE
statements in the previous practice.
2. In the world_innodb database, language information for countries is stored in a
dedicated table. Based on the structure of the CountryLanguage table, what do users
to
3.
need to know about country languages?
A 1n ense
Create a structure diagram for the world_innodb tables by filling in the column names for
C 3% le lic
each of its tables. Use the following diagram as a starting point:

n c l% erab
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 ฺb o
ya e
(

4. Which columns in each table can uniquely identify a record? Indicate these on the table.
These are the candidate keys.
5. Cities and countries have their own tables. Continents do not. Why?
6. Why is CountryLanguage a separate table? Why not store language information in the
Country table?
7. Indicate on the diagram which column(s) in each table is/are the primary key.
8. Explain why the CountryLanguage table has a composite primary key.
9. Exit the mysql client.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Database Design


Chapter 4 - Page 13
Note: The world_innodb database is not fully normalized. If you choose to, you can note
the improvements necessary to get the database to third normal form.
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Database Design


Chapter 4 - Page 14
Solution 4-3: Creating a Structure Diagram
Tasks
1. Explain the purpose of the world_innodb database, using the output from the DESCRIBE
statements in the previous practice. The answer is as follows:

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

The database is being used to store, retrieve and otherwise manipulate information
about countries, including continent, language and city data.
2. In the world_innodb database, language information for countries is stored in a
dedicated table. Based on the structure of the CountryLanguage table, what do users
need to know about country languages? The answer is as follows:
• The language spoken
• The official language
• The percentage of the population that speaks the language
• The country the information relates to
to
1n ense
3. Create a structure diagram for the world_innodb tables by filling in the column names for
each of its tables. The completed diagram is as follows: A
C 3% le lic
n c l% erab
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 ฺb o
ya e
(

4. Which columns in each table can uniquely identify a record? Indicate these on the table.
These are the candidate keys. The answer is as follows:
a. Country: Code or Code2
b. City: ID
c. CountryLanguage: CountryCode and Language

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Database Design


Chapter 4 - Page 15
5. Cities and countries have their own tables. Continents do not. Why? The answer is as
follows:
• The primary tables are Country and City. Continents do not need a table of their
own because all the information required is at the country and city level.
6. Why is CountryLanguage a separate table? Why not store language information in the
Country table? The answer is as follows:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Some countries have more than one national language. If each of these were stored in
the Country table it would result in redundant rows.
7. Indicate on the diagram which column(s) in each table is/are the primary key. The answer is
as follows:
• Country: Code
• City: ID
• Country: CountryCode and Language – a composite key.
8. Explain why the CountryLanguage table has a composite primary key.
to

1n ense
The CountryLanguage table requires both the CountryCode and Language columns
to uniquely identify each row. A
9. Exit the mysql client: C 3% le lic
Enter the following at the mysql> prompt: n c l% erab
2 0I ansf
mysql> EXIT
MySQL displays an exit message and the i l l
command n -tr returns to the standard
a% owindow
prompt:
o bad s a n eฺ
r a B ha uid
Bye
d
n yฺm entx ) G
cmd>
l e j a
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Database Design


Chapter 4 - Page 16
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
Practices for n c l% era5:b Table
Lesson
2 0I ansf
DataaTypes% n-tr
i l l
d 5a no
b a
B
Chapter
o as i d eฺ
n d ra x) h t Gu
l e ja dyฺm den
2 0A oฺua s Stu
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Table Data Types


Chapter 5 - Page 1
Practices for Lesson 5: Overview
Practices Overview
These practices test your knowledge of table data types. They target the Windows operating
system, provided in Oracle classrooms. For non-Oracle classrooms, you might need to adjust
file locations.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Assumptions
• You have installed and configured the MySQL server.
• You have created and populated the world_innodb database.
• You can access the mysql client from a command-line prompt.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm 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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Table Data Types


Chapter 5 - Page 2
Practice 5-1: Quiz – Data Types
Overview
In this quiz, you answer questions about MySQL data types.

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

This practice takes approximately 10 minutes to complete.

Quiz Questions
Choose the best answer from those provided.
1. Data types belong to four different categories: Numeric, Character, Binary, and Temporal.
a. True
b. False
2. Numeric data types are suitable only for whole numbers.
a. True to
b. False
A 1n ense
3% le lic
3. The ____________ data type represents approximate-value numbers that have an integer
C
part, a fractional part, or both.
n c l% erab
a. FLOAT
2 0I ansf
b. INTEGER
i l l a% on-tr
bad s a n eฺ
c. FIXED
d. None of the above o
B ha
r a )
4. These data types are included in the Temporal category:
d x G uid
a. TIME j a n yฺm ent
l e
b. DATE 2 0A oฺuad s Stud
el% corre e thi
c. DATETIME
a
d. Y @ us
TIMESTAMP
l l a
i the above
e. Alldof
b a
oThe following statement displays the CountryLanguage table columns and settings. The
e
5.
l ฺb output shows that the data type of the Language column is CHAR. The ____________ data
( ya type is also suitable for this column, and allows for variations in the number of characters.
mysql> DESC CountryLanguage;
+-------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+-------+
| CountryCode | char(3) | NO | PRI | | |
| Language | char(30) | NO | PRI | | |
| IsOfficial | enum('T','F') | NO | | F | |
| Percentage | float(4,1) | NO | | 0.0 | |
+-------------+---------------+------+-----+---------+-------+
4 rows in set (0.05 sec)
a. TINYINT
b. VARCHAR
c. BIGCHAR

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Table Data Types


Chapter 5 - Page 3
6. The data type of the IsOfficial column is ENUM. You can see this in the output from the
DESCRIBE CountryLanguage statement in question number 5. ENUM is used to restrict
the value of column entries to a fixed, enumerated string. The only values allowed are T
(true) or F (false).
a. True
b. False
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

7. ____________ ____________ data types (like BLOB) store values that represent binary
data, such as video and audio files.
a. Character string
b. Fixed-point
c. Integer class
d. Binary string
8. ____________ is a SQL keyword used to define data types that permit missing values.
a. UNKNOWN
to
1n ense
b. DEFAULT
c. NULL A
C 3% le lic
n c l% erab
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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Table Data Types


Chapter 5 - Page 4
Solutions 5-1: Quiz – Data Types
Quiz Solutions
1. a. True
2. b. False. Numeric data types can be whole, fractional or exact-value numbers, as well as
BIT-field values.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

3. a. FLOAT
4. e. All of the above
5. b. VARCHAR
6. a. True
7. d. Binary string
8. c. NULL

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm 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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Table Data Types


Chapter 5 - Page 5
Practice 5-2: Explaining the Use of Data Types
Overview
In this practice, you explain the use of data types in a given table example.

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

This practice takes approximately 15 minutes to complete.

Tasks
The following is the data structure of the Country table (including the column data types), from
the world_innodb database. Refer to this chart to answer the questions below.
+----------------+--------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------------+------+-----+---------+-------+
| Code | char(3) | NO | PRI | | |

to
| Name | char(52) | NO | | | |

1n ense
| Continent | enum('Asia', | | | | |
| | 'Europe', | | | | |
A
3% le lic
| | 'North America' | | | | |
|
|
| 'Africa'
| 'Oceania',
|
|
|
|
|
|
|
| C
|
l% erab
|
n c
0I ansf
| | 'Antarctica', | | | | |
| | 'South America') | NO |
2
| Asia | |
| Region | char(26) | NO |
i l
|
l a% on-tr
| |

bad s a n eฺ
| SurfaceArea | float(10,2) | NO | | 0.00 | |
| IndepYear | smallint(6) | YES | | NULL | |
o
B ha uid
| Population | int(11) | NO | | 0 | |
| LifeExpectancy | float(3,1)
d r a | YES |
x ) | NULL
G
| |
| GNP | float(10,2)
j a n yฺm ent
| YES | | NULL | |
| GNPOld
l e
| float(10,2) | YES | | NULL | |
| LocalName
2 0A oฺuad s Stud
| char(45)
| GovernmentForm | char(45)
| NO
| NO
|
|
|
|
|
|
|
|
| HeadOfState
a el% corre e thi
| char(60) | YES | | NULL | |
| Capital
| Code2 Y @ | int(11)
| char(2)us
| YES |
| NO |
| NULL
|
|
|
|
|
l l a
1. b
The
di country codes all contain three characters. Does it make sense that the Code
+----------------+--------------------+------+-----+---------+-------+
a
primary
l o
ฺb column is CHAR(3) or should it be expanded to allow for more characters?
ya e
( 2. What other data type could the Name column use? Why?
3. Could the Continent column use a different data type besides ENUM? Why?
4. Which continent is used if none is specified in a query?
5. Is SMALLINT(6) the best setting for the IndepYear column? If not, what is?
6. Why is FLOAT(10,2) used for the GNP column? What do the 10 and 2 integers mean?
7. Would you ever change the maximum value in the FLOAT data type used for the GNP
column?
8. Why is the HeadOfState column set to CHAR(60)?
9. Does it make sense that the Capital column is set to accept NULL values? Why?

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Table Data Types


Chapter 5 - Page 6
Solutions 5-2: Explaining the Use of Data Types
Tasks
1. The primary country codes all contain three characters. Does it make sense that the Code
column is CHAR(3) or should it be expanded to allow for more characters? Why? The
answers are as follows:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Yes. The number of characters does not change. Therefore, this is the most efficient
data type setting.
2. What other data type could the Name column use? Why? The answers are as follows:
• It could also use VARCHAR(52). This uses less storage space for smaller strings. The
storage requirement for a VARCHAR depends on the character set and the number of
characters in the string (including trailing spaces, which a VARCHAR retains.)
3. Could the Continent column use a different data type besides ENUM? Why? The answers
are as follows:
• No. Values are restricted to one selection from a list of strings. ENUM is the only data to
type that suits this purpose.
A 1n ense
4. 3% le lic
Which continent is used if none is specified in a query? The answer is as follows:
C
• Asia, which is set as the DEFAULT value.
n c l% erab
5. Is SMALLINT(6) the best setting for the IndepYear column? 0I If not,n s f is? The answers
what
2
are as follows:
i l l a% on-tra
• No. SMALLINT(4) is better because this adcolumn
obaffect a n toฺ display only four characters.
needs
Note that the display width doesB not
ahows actual
the
i d e value is stored, so no data
will be lost. a
drthe GNP x ) h u
G do the 10 and 2 integers mean?
j a n ฺ m n t
6. Why is FLOAT(10,2) used
The answers are asA le ady tude
follows:
for column? What

2 0 o ฺu thatishasSan integer and fractional part. DECIMAL could be a


% e
aelchoicecbecause
orr sitestores
• It expresses financial data
th exact values (FLOAT stores only approximate values).
Ybetter
u
• l a@
Theilfirst integer is the maximum number of decimal digits that can be stored. The
d
l
7.
obasecond integer is the number of digits after the decimal point.
ฺb Would you ever change the maximum value in the FLOAT data type used for the GNP
ya e column? The answer is as follows:
(
• Yes, if the maximum value for any country’s GNP were to rise to $100,000,000.00.
8. Why is the HeadOfState column set to CHAR(60)? The answer is as follows:
• At least one record in the table could be up to 60 characters long.
9. Does it make sense that the Capital column is set to accept NULL values? Why?
• Yes, because not all countries have a capital specified.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Table Data Types


Chapter 5 - Page 7
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Table Data Types


Chapter 5 - Page 8
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
Practices for n c l% era6:b
Lesson
2 0I ansf
Database a% oand-tr Table Creation
i l l n
o ad 6a n ฺ
bChapter
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 ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Database and Table Creation


Chapter 6 - Page 1
Practices for Lesson 6: Overview
Practices Overview
These practices test your knowledge of database and table creation. They target the Windows
operating system, provided in Oracle classrooms. For non-Oracle classrooms, you might need
to adjust file locations.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Assumptions
• You have installed and configured MySQL Server.
• You have created and populated the world_innodb database.
• You can access the mysql client from a command-line prompt.
Note: In this practice, the first letters of table names are in uppercase. Windows is not case-
sensitive but some operating systems are, so it is good practice to use proper capitalization.
The SQL statements are all in uppercase for clarity, but this is not required.
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Database and Table Creation


Chapter 6 - Page 2
Practice 6-1: Displaying Table Creation Information
Overview
In this practice, you:
• Show the SQL statement syntax required to create a specific table
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Create a new table


• Show indexes for a table

Duration
This practice takes approximately 15 minutes to complete.

Tasks
1. Start the mysql client and set the current database to world_innodb.
2. Execute SHOW CREATE TABLE to display the statement used to create the Country table.
3. Use the results of the SHOW CREATE TABLE statement to create a new table called to
A
Country2 with the same attributes, but do not specify the ENGINE or CHARSET. 1n ense
4. Execute the SHOW TABLES statement to confirm that the new table now
% e lic
3exists.
l % C bl table.
5. Use the SHOW INDEXES statement to display the primary key c for r a
the Country2
6. Identify the indexes in the City table. 2 0In ansfe
7. Exit the mysql client. i l l a% on-tr
bad s a database
Note: The changes you make to the world_innodb
o
n ฺ in these lessons are
cumulative. Do not attempt to undo
r a B changes
any
) h a you make
u idtoe the database in this or future
practices.
j a nd yฺmx ent G
A le ad tud
2 0 ฺ u S
e l % rreo this
Ya @co use
d i lla
l ฺb oba
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Database and Table Creation


Chapter 6 - Page 3
Solutions 6-1: Displaying Table Creation Information
Tasks
1. Start the mysql client and set the current database to world_innodb:
Compare your statement and results to those shown below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

cmd> mysql -u root -p


Enter password: oracle
...

mysql> USE world_innodb


Database changed
2. Execute SHOW CREATE TABLE to display the statement used to create the Country table.
Compare your statement and results to those shown below:
mysql> SHOW CREATE TABLE Country\G
*************************** 1. row ***************************
to
Table: Country
A 1n ense
3% le lic
Create Table: CREATE TABLE `country` (
`Code` char(3) NOT NULL DEFAULT '',
`Name` char(52) NOT NULL DEFAULT '', C
l% erab
n c
0I ansf
`Continent` enum('Asia','Europe','North America','Africa',
2
'Oceania','Antarctica','South America')
NOT NULL DEFAULT 'Asia',
i l l a% on-tr
bad s a n eฺ
`Region` char(26) NOT NULL DEFAULT '',
o
`SurfaceArea` float(10,2) NOT NULL DEFAULT '0.00',
B ha
`IndepYear` smallint(6) DEFAULT NULL,
d r a x ) G uid
`Population` int(11) NOT NULL DEFAULT '0',
j a n yฺm ent
`LifeExpectancy` float(3,1) DEFAULT NULL,
l e
0A oฺuad s Stud
`GNP` float(10,2) DEFAULT NULL,
2
`GNPOld` float(10,2) DEFAULT NULL,

a el% corre e thi


`LocalName` char(45) NOT NULL DEFAULT '',
Y @ us
`GovernmentForm` char(45) NOT NULL DEFAULT '',
l a
`HeadOfState` char(60) DEFAULT NULL,
l
b a di`Capital` int(11) DEFAULT NULL,

l ฺb o `Code2` char(2) NOT NULL DEFAULT '',


PRIMARY KEY (`Code`)
ya e ) ENGINE=InnoDB DEFAULT CHARSET=latin1
( 1 row in set (0.00 sec)
3. Use the results of the SHOW CREATE TABLE statement to create a new table called
Country2 with the same attributes, but do not specify the ENGINE or CHARSET.
Compare your statement and results to those shown below:
mysql> CREATE TABLE `Country2` (
-> `Code` char(3) NOT NULL DEFAULT '',
-> `Name` char(52) NOT NULL DEFAULT '',
-> `Continent` enum('Asia','Europe','North
America','Africa', 'Oceania','Antarctica','South America')
NOT NULL DEFAULT 'Asia',
-> `Region` char(26) NOT NULL DEFAULT '',
-> `SurfaceArea` float(10,2) NOT NULL DEFAULT '0.00',
-> `IndepYear` smallint(6) DEFAULT NULL,
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Database and Table Creation


Chapter 6 - Page 4
-> `Population` int(11) NOT NULL DEFAULT '0',
-> `LifeExpectancy` float(3,1) DEFAULT NULL,
-> `GNP` float(10,2) DEFAULT NULL,
-> `GNPOld` float(10,2) DEFAULT NULL,
-> `LocalName` char(45) NOT NULL DEFAULT '',
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-> `GovernmentForm` char(45) NOT NULL DEFAULT '',


-> `HeadOfState` char(60) DEFAULT NULL,
-> `Capital` int(11) DEFAULT NULL,
-> `Code2` char(2) NOT NULL DEFAULT '',
-> PRIMARY KEY (`Code`)
-> );
Query OK, 0 rows affected (0.14 sec)
− The quotes used around table and column names (``) are known as backticks. They
are not necessary, but can aid clarity and allow you to include special characters
and reserved words in the names. to
A 1n ense
− Consider using MySQL Workbench to enter this long and complex statement.
4. C 3% le lic
Execute the SHOW TABLES statement to confirm that the new table now exists:
Compare your statement and results to those shown below:
n c l% erab
2 0I ansf
mysql> SHOW TABLES;
l l a % n-tr
+------------------------+
| Tables_in_world_innodb | i
ad a no ฺ
+------------------------+ ob
| city
r a |B
) h as uide
| country
j a nd y||ฺmx ent G
| country2
A le ad | tud
0
| countrylanguage
2 o ฺu is S
% e
+------------------------+

Y ael in cset
4 rows
orr(0.16sesec)
th
5. Use the SHOW
i l l a@INDEXESustatement to determine the primary key for the Country2 table:
d
oba
Compare your statement and results to those shown below:

e l ฺb mysql> SHOW INDEX FROM Country2\G

( ya ****************** 1. row ********************


Table: country2
Non_unique: 0
Key_name: PRIMARY
Seq_in_index: 1
Column_name: Code
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:
1 row in set (0.00 sec)
− The result shows only one index. It is the primary key on the Code column.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Database and Table Creation


Chapter 6 - Page 5
6. Identify the indexes in the City table.
Compare your statement and results to those shown below:
mysql> SHOW INDEX FROM City\G
***************** 1. row ********************
Table: city
Non_unique: 0
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Key_name: PRIMARY
Seq_in_index: 1
Column_name: ID
Collation: A
Cardinality: 4051
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:
***************** 2. row ********************
to
Table: city
Non_unique: 1 A 1n ense
Key_name: CountryCode
C 3% le lic
Seq_in_index: 1
n c l% erab
0I ansf
Column_name: CountryCode
Collation: A
2
Cardinality: 368
i l l a% on-tr
bad s a n eฺ
Sub_part: NULL
Packed: NULL
o
B ha uid
Null:
Index_type: BTREE
d r a x ) G
Comment:
j a n yฺm ent
l e
0A oฺuad s Stud
Index_comment:
2
2 rows in set (0.00 sec)
− The
a el% r
result shows
o e hi a primary key on the ID column and a second index
re two indexes:
t
c us column.
Y on the@CountryCode
a
ill that the cardinality values can vary from those shown.
− dNote
7.
a
oExitb the mysql client:
e l ฺb
( ya Enter the following at the mysql> prompt:
mysql> EXIT
MySQL displays an exit message and the command window returns to the standard
prompt:
Bye
cmd>

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Database and Table Creation


Chapter 6 - Page 6
Practice 6-2: Creating a Database
Overview
In this practice, you create a new database and its tables. This database is for a veterinary clinic
and consists of information about pets and their owners. You will start with a spreadsheet and
go through some initial design steps before creating the database and populating its tables.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Although this is a small database, keep in mind that it must leave room for growth.
Important Note: Save your work and ensure that the database remains in a consistent
state so that it you can build on it in future practices.

Duration
This practice takes approximately 60 minutes to complete.
The following is a spreadsheet containing details of pets and their owners. You will use this
information to create the database:
Pet Name Owner Phone Type Category Gender Birth date Death date
to
Fluffy Harold 15554159855 Cat Mammal
A 1n ense
F 2003-02-04
Claws Gwen 15551234567 Cat Mammal M
C 3% le lic
2004-03-17
Buffy Harold 15554159855 Dog Mammal F
n c l% 1999-05-13
f e r ab
Mammal 0IM n s2000-08-27
Fang Benny 15553456789 Dog
2 r a
Bowser Diane 15554567890 Dog i l l a% onM-t 1989-08-31 2009-07-29
Mammal
Chirpy Gwen 15551234567 bad Bird
Parrot
o a n F ฺ 2008-09-11
Whistler Gwen 15551234567 r a )
s
BCanary haBird u ide 2007-12-09
n d x t G
Slim Benny
l e ja dyฺm
15553456789 Snake en
d Reptile M 2006-04-29
Puffball 2
Diane A a
0 15554567890
ฺu is Hamster
S t u Mammal F 2009-03-30
% e o
Opus
Y ael Caryncor15554444444
r
e th Ferret Mammal M
Rocky
l l aChris us
@ 15556666666 Dog Mammal M 2008-04-04 2013-02-11
Koko d
i
oba
Benny 15553456789 Dog Mammal M 1997-02-08

e l ฺb Scruffy Gwen 15551234567 Cat Mammal M 2008-04-17


( ya Note: Not all the information is available for every pet. Therefore, some of the columns
must allow null values.

Tasks
1. Start the database design process by answering the following questions:
a. What is the primary purpose of the database?
b. Considering its purpose, what is a good name for this database?
c. Does any owner have more than one pet?
d. Does any pet have more than one owner?
e. Can more than one pet have the same name?
f. Can you assign the same pet type to more than one pet?
g. Can a pet have more than one pet type?
h. Can you assign the same pet type to more than one category?

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Database and Table Creation


Chapter 6 - Page 7
i. Can a category have more than one pet type?
j. Can a pet have more than one gender?
k. Would any table(s) from this database benefit from an extra column to uniquely identify
each record?
2. Draw a structure diagram (like you did for the world_innodb database in an earlier
practice) to show the tables and columns required. Use the diagram below as a starting
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

point. The structure is partially normalized for you.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
d a ncan reference each other by using
soathat tables
Note: Each table has a unique identifier b
foreign keys, where applicable. B o a s i d eฺ
d h tables.
ra in thex)following G u Review these tables. You will
n
3. The normalization process resulted
ฺm den
ja database: t
use them to create thele Pets
d y
a. pet_info2 0A oฺua s Stu
table:
pID* ae pName
l% orre pGender
e t hi pBday pDday oID** tID***
Y @c us
1
d i llaFluffy F 2003-02-04 NULL 1 1
2 ba Claws M 2004-03-17 NULL 2 1
l ฺ b o
e 3 Buffy F 1999-05-13 NULL 1 2
(ya 4 Fang M 2000-08-27 NULL 3 2
5 Bowser M 1989-08-31 2009-07-29 4 2
6 Chirpy F 2008-09-11 NULL 2 3
7 Whistler NULL 2007-12-09 NULL 2 4
8 Slim M 2006-04-29 NULL 3 5
9 Puffball F 2009-03-30 NULL 4 1
10 Opus M NULL NULL 5 1
11 Rocky M 1998-04-04 2013-02-11 6 1
12 Koko M 1997-02-08 NULL 3 1
13 Scruffy M 2008-04-17 NULL 2 1

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Database and Table Creation


Chapter 6 - Page 8
* = Primary key, ** = Foreign key, references the owners table (oID), ***= Foreign key,
references the pet_types table (tID)
b. owners table:
oID* oName oPhone
1 Harold 15554159855
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

2 Gwen 15551234567
3 Benny 15553456789
4 Diane 15554567890
5 Caryn 15554444444
6 Chris 15556666666
* = Primary key
c. pet_types table:
to
1n ense
tID* pType pCategory
1 Cat Mammal A
% e lic
C 3
2 Dog
% rabl
Mammal
c l
3 Parrot
2 0In Birdansfe
4 Canary
l l a% on-tBird r
i
5 Snake
o bad s a n eฺReptile
6 B ha
Hamster
r a uid Mammal
d
n Ferret x ) t G
7
l e j a y ฺ m e n Mammal
* = Primary key 0A
2 ฺ u ad Stud
4. Decide on the
e l eo typesthand
%columnrrdata is other desired attributes by answering the following
Ya for@
questions cocolumn:
each
u s e
a row need to be unique, or are duplicates allowed?
a. Doeslleach
i
b.ba d
Which (if any) of the column options must you use? For example: NOT NULL.
b o
elฺ c. Which category of data type is relevant for the column? For example: Numeric or
(ya character string?
d. Which is the most appropriate data type within that category? For example: INT or
CHAR(20).
Note: Remember that although you have sample data already, your design needs to
accommodate more being added later on. For example, ensure that the data type for the
pet name is large enough to support a relatively long name, not just the longest name in the
current data set.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Database and Table Creation


Chapter 6 - Page 9
pet_info table (use the first column as an example):
Attributes pID* pName pGender pBday pDday oID** tID***
Unique? Yes
Options? NOT NULL,
AUTO_INCREMENT
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Category? Integer
Data type? INT

Note: You do not need to provide a specific value for the INT data type (unlike, for
example, CHAR(30)).
owners table:
Attributes oID* oName oPhone
Unique?
Options? to
Category? A 1n ense
Data type? C 3% le lic
n c l% erab
pet_types table:
2 0I ansf
Attributes tID* pType pCategory
i l l a% on-tr
Unique?
o bad s a n eฺ
Options?
r a B ha uid
Category? d
n yฺm ent x ) G
l e j a
Data type?
2 0A oฺuad s Stud
e % cdatabase
5. Create the lPets
a o hi client session.
rre inea tmysql
6. ConfirmY that @ us is in the list of available databases.
the Pets database
l l a
7. Change
b a dithe current database to Pets.
8. o Use your plan to create the empty tables, including their primary keys.
l ฺ b
e Note: Do not create the foreign keys yet. You do this in a later lesson.
(ya 9. Confirm that the tables are available.
10. View the table structure for each table. Use the DESCRIBE <table name> statement for
this.
11. Exit the mysql client.
Note: You now have a database with three empty tables. You populate them with data in a
later practice.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Database and Table Creation


Chapter 6 - Page 10
Solutions 6-2: Creating a Database
Tasks
1. Start the database design process by answering the following questions:
a. What is the primary purpose of this database? This database is for a veterinary
clinic and consists of information about pets and their owners.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

b. Considering its purpose, what is a good name for this database? “Pets”
c. Does any owner have more than one pet? Yes
d. Does any pet have more than one owner? No. Not for the purpose of this practice.
e. Can more than one pet have the same name? Yes
f. Can you assign the same pet type to more than one pet? Yes
g. Can a pet have more than one pet type? No
h. Can you assign the same pet type to more than one category? No
i. Can a category have more than one pet type? Yes
to
j. Can a pet have more than one gender? No
A 1n ense
3% le lic
k. Would any table(s) from this database benefit from an extra column to uniquely identify
C
each record? Yes, all of them could benefit from an identifier to ensure that each
l% erab
row is unique.
n c
2. 0I ansf
Draw a structure diagram (like you did for the world_innodb database in an earlier
2
i l l a% on-tr
practice) to show the tables and columns required. Use the diagram below as a starting

bad s a n eฺ
point, which has been partially normalized for you.
o
B ha
d r a x ) G uid
j a n yฺm ent
l e
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺb o
ya e
(

3. Review the final table design shown in task 3.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Database and Table Creation


Chapter 6 - Page 11
4. Decide on the column data types and other desired attributes by answering the following
questions for each column:
pet_info table (use the first column as an example):
Attributes pID* pName pGender pBday pDday oID** tID***
Unique? Yes No No No No No No
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Options? NOT NULL, NOT DEFAULT DEFAULT DEFAULT NOT NOT


AUTO_INCREMENT NULL NULL NULL NULL NULL NULL
Category? Integer String String Temporal Temporal Integer Integer

Data type? INT VARCHAR ENUM DATE DATE INT INT


(20) (‘M‘,‘F‘)
owners table:
Attributes oID* oName oPhone
Unique? Yes No No
to
Options? NOT NULL, NOT NULL NOT NULL
A 1n ense
AUTO_INCREMENT
3 % e lic
Category? Integer String String/Number
l C
% rabl
c
Data type? INT VARCHAR(20) CHAR(11)
2 0In ansfe
pet_types table:
i l l a% on-tr
Attributes tID* pType ba
d pCategory
a n ฺ
o
B hasNo uide
Unique? Yes r a
Yes
d NOT m x ) GNULL
j a n ฺ n t
Options? NOT
le ady tude
NULL,
A
NULL NOT
0
2 eoฺu String
AUTO_INCREMENT
s S
Category? l% Integer
e INT cor r h i
t VARCHAR(20) String
a
Y @ s e
Data type?
a u VARCHAR(20)

5. Createdthe
a ill Pets database in a mysql client session:
l ฺ b oa.b Log in to the mysql client program:
e
(ya cmd> mysql -u root -p
Enter password: oracle
...
b. Compare your statement and results to those shown below:
mysql> CREATE DATABASE Pets;
Query OK, 1 row affected (0.05 sec)
6. Confirm that the Pets database is in the list of available databases:
Compare your statement and results to those shown below:
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Database and Table Creation


Chapter 6 - Page 12
| performance_schema |
| pets |
| sakila |
| test |
| world |
| world_innodb |
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

+--------------------+
8 rows in set (0.00 sec)
7. Change the current database to Pets:
Compare your statement and results to those shown below:
mysql> USE Pets
Database changed
8. Use your plan to create the empty tables, including their primary keys.
Compare your statement and results to those shown below:
to
mysql> CREATE TABLE pet_info (
A 1n ense
3% le lic
-> pID INT NOT NULL AUTO_INCREMENT,
-> pName VARCHAR(20) NOT NULL, C
l% erab
n c
0I ansf
-> pGender ENUM('M', 'F') DEFAULT NULL,
2
a% on-tr
-> pBday DATE DEFAULT NULL,
-> pDday DATE DEFAULT NULL, i l l
-> oID INT NOT NULL,
o bad s a n eฺ
->
r a
tID INT NOT NULL, B ha uid
d
n yฺm ent x ) G
->
j a
PRIMARY KEY (pID)
e
-> );Al affected
Query OK,200 rows o ฺ uad s(0.03
S tudsec)
a el% corre e thi
Y
mysql>@ us owners (
CREATE TABLE
l l a
b a di -> oID INT NOT NULL AUTO_INCREMENT,
l ฺb o -> oName VARCHAR(20) NOT NULL,

ya e -> oPhone CHAR(11) NOT NULL,


( -> PRIMARY KEY (oID)
-> );
Query OK, 0 rows affected (0.09 sec)

mysql> CREATE TABLE pet_types (


-> tID INT NOT NULL AUTO_INCREMENT,
-> pType VARCHAR(20) NOT NULL,
-> pCategory VARCHAR(20) NOT NULL,
-> PRIMARY KEY (tID)
-> );
Query OK, 0 rows affected (0.05 sec)
Note: Do not create the foreign keys yet. You do this in a later lesson.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Database and Table Creation


Chapter 6 - Page 13
9. Confirm that the tables are available:
Compare your statement and results to those shown below:
mysql> SHOW TABLES;
+----------------+
| Tables_in_pets |
+----------------+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| owners |
| pet_info |
| pet_types |
+----------------+
3 rows in set (0.00 sec)
10. View the table structure for each table. Use the DESCRIBE <table name> statement for
this.
Compare your statement and results to those shown below:
mysql> DESC pet_info;
+---------+---------------+------+-----+---------+----------------+
to
1n ense
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+----------------+
A
| pID
| pName
| int(11)
| varchar(20)
| NO
| NO
| PRI | NULL
| | NULL | 3% le lic
| auto_increment |
C |
| pGender | enum('M','F') | YES | | NULL |
n c l% erab
|
| pBday | date | YES | | NULL |
2 0I ansf |

a% on-tr
| pDday | date | YES | | NULL | |
| oID | int(11) | NO |
i
| NULLl l | |
| tID | int(11) | NO |
o bad s a n eฺ
| NULL | |

r a B ha
+---------+---------------+------+-----+---------+----------------+
uid
7 rows in set (0.09 sec)
d
n yฺm ent x ) G
l e j a
0 oฺuad s Stud
mysql> DESCAowners;
2 | i Null | Key | Default | Extra
+--------+-------------+------+-----+---------+----------------+

a e
| Field l% | Type
o r re t h |
Y c e
us | NO | PRI | NULL | auto_increment |
+--------+-------------+------+-----+---------+----------------+
| oIDa@| int(11)
|d i l l
o b a
|
oName
oPhone
| varchar(20) | NO
| char(11) | NO
|
|
| NULL
| NULL
|
|
|
|
e l ฺb +--------+-------------+------+-----+---------+----------------+
( ya 3 rows in set (0.08 sec)

mysql> DESC pet_types;


+-----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+----------------+
| tID | int(11) | NO | PRI | NULL | auto_increment |
| pType | varchar(20) | NO | | NULL | |
| pCategory | varchar(20) | NO | | NULL | |
+-----------+-------------+------+-----+---------+----------------+
3 rows in set (0.09 sec)
− DESC is a shortened version of the DESCRIBE statement.
− Note that the INT data type defaults to a display width value of 11. This does not
affect the size of the value that can be stored.
Note: You now have a database with three empty tables. You populate them with data in a
later practice.
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Database and Table Creation


Chapter 6 - Page 14
11. Exit the mysql client:
Enter the following at the mysql> prompt:
mysql> EXIT
The following message appears and Control returns to the standard command prompt:
Bye
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

cmd>

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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Database and Table Creation


Chapter 6 - Page 15
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Database and Table Creation


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

to
A 1n ense
C 3% le lic
Practices for n c l% era7:b Basic
Lesson
2 0I ansf
Queries a% on-tr
i l l
o ad 7a n ฺ
bChapter
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 ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 1
Practices for Lesson 7: Overview
Practices Overview
These practices test your knowledge of basic queries. They target the Windows operating
system, provided in Oracle classrooms. For non-Oracle classrooms, you might need to adjust
file locations.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Assumptions
• You have installed the MySQL server.
• You have created and populated the world_innodb database.
• You can access the mysql client from a command-line prompt.
• You have created the Pets database and defined its tables.
• You can access MySQL Workbench if you choose to complete the practices using this
tool.
to
A 1n ense
Note: In this practice, the first letters of table names are in uppercase. Windows is not case-
sensitive but some operating systems are, so it is good practice to use proper capitalization.
3% le lic
The SQL statements are all in uppercase for clarity, but this is not required.
C
n c l% erab
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 2
Practice 7-1: Performing Basic Queries
Overview
In this practice, you query the world_innodb database using the mysql client.

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

This practice takes approximately 20 minutes to complete.

Tasks
1. Start the mysql client and set the current database to world_innodb.
2. Use a DESCRIBE statement to see which columns are available for querying in the
Country table.
3. Execute a SELECT statement that retrieves the Continent column data from the Country
table.
4. Change the preceding SELECT statement to include the Name column from the Country to
table.
A 1n ense
5. 3% le lic
Execute a SELECT statement that retrieves all the Region column data from the Country
C
table.
n c l% erab
6. 0I ansf
Change the preceding SELECT statement to retrieve only the distinct Region column data
2
from the Country table.
l l a % n-tr
7. Execute a SELECT statement that retrieves all
a i
dcolumns o the City table where the
nfrom
identification number is 3875. b
o as a eฺ
B
rathat you h all G i d
u data.
Hint: Use the * symbol to indicate
n d x ) want t
column
8. Execute a SELECT statement
l e ฺm dnames
ja thatdyretrieves e n and population figures from the
0A theopopulation
Country table where
2 ฺ ua s isSless tu than 1000.
9. Execute a SELECT
e r re that
l% ostatement t h iretrieves the names of all cities from the City table in
a
Y Name
descending corder.us e
a @
a d ill
10. Use a DESCRIBE statement to see which columns are available for querying in the

b b
CountryLanguage
o table.

a e lฺ Execute a SELECT statement that retrieves the country code and language from the
11.
( y CountryLanguage table where the language is Swedish, in descending order of
CountryCode.
12. Execute a SELECT statement that retrieves the name of the cities from the City table in
ascending alphabetical order, and limit the number of rows to 10.
13. Execute a SELECT statement that retrieves the country code and language from the
CountryLanguage table where the language is Chinese, in descending order of country
code. Limit the result to two rows.
14. Execute a SELECT statement that retrieves all columns for countries where the GNP is
greater than the old GNP, in order of country name. Limit the result to three rows.
Hint: Use the \G terminator to get a more readable result.
15. Exit the mysql client.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 3
Solutions 7-1: Performing Basic Queries
Tasks
1. Start the mysql client and set the current database to world_innodb:
Enter the following at the command prompt, and receive the results shown below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

cmd> mysql -u root -p


Enter password: oracle
...

mysql> USE world_innodb


Database changed
2. Use a DESCRIBE statement to see which columns are available for querying in the
Country table.
Compare your statement and results to those shown below:
mysql> DESC Country; to
1n ense
+----------------+--------------------------+------+-----+---------+-------+
A
3% le lic
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------------------+------+-----+---------+-------+
| Code | char(3) | NO C
l% erab
| PRI | | |
n c
0I ansf
| Name | char(52) | NO | | | |
| Continent | enum('Asia',
2
a% on-tr
'Europe',
i l l
'North America',

bad s a n eฺ
'Africa',
o
'Oceania',
B ha
d a
'Antarctica',
r x ) G uid
| Region
j a n yฺm ent
'South America')
| char(26)
| NO
| NO
|
|
| Asia
|
|
|
|
|
l e
0A oฺuad s Stud
| SurfaceArea | float(10,2) | NO | | 0.00 | |
2
| IndepYear | smallint(6) | YES | | NULL | |

el% corre e thi


| Population | int(11) | NO | | 0 | |
a
| LifeExpectancy | float(3,1)
Y @
| YES | | NULL | |
| GNP
l l a us
| float(10,2) | YES | | NULL | |

di
| GNPOld | float(10,2) | YES | | NULL | |

o b a | LocalName | char(45)
| GovernmentForm | char(45)
| NO
| NO
|
|
|
|
|
|
|
|

e l ฺb | HeadOfState | char(60) | YES | | NULL | |

( ya | Capital
| Code2
| int(11)
| char(2)
| YES |
| NO |
| NULL
|
|
|
|
|
+----------------+--------------------------+------+-----+---------+-------+
15 rows in set (0.02 sec)

3. Execute a SELECT statement that retrieves the Continent column data from the Country
table:
Compare your statement and results to those shown below:
mysql> SELECT Continent FROM Country;
+---------------+
| Continent |
+---------------+
| North America |
| Asia |
| Africa |
| North America |
| Europe |
| Europe |

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 4
| North America |
| Asia |
| South America |
| Asia |
| Oceania |
| Antarctica |
| Antarctica |
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| North America |
| Oceania |
| Europe |
| Asia |
...
| South America |
| North America |
| North America |
| Asia |
| Oceania |
| Oceania |
| Oceania |
to
| Asia
| Europe
|
| A 1n ense
| Africa |
C 3% le lic
| Africa |
n c l% erab
0I ansf
| Africa |
+---------------+
2
239 rows in set (0.45 sec)
i l l a% on-tr
4. Change the preceding SELECT statement to
o badinclude a nNameฺcolumn from the Country
the
table.
r B has uide
aresults
Compare your statement d
n and x ) thosetshown
to G below:
j a
mysql> SELECTleContinent, m
yฺ Name n
e Country;
A
0 |oName a d t u dFROM

% 2 e ฺu is S
+---------------+----------------------------------------------+

e l
| Continent
r r t h |

Y a America co u| sAruba
e
+---------------+----------------------------------------------+
| North@ |
i l
| Asia l a | Afghanistan |
a|d
ob | North America | Anguilla
Africa | Angola |

e l ฺb |

ya
| Europe | Albania |
( | Europe
| North America
|
|
Andorra
Netherlands Antilles
|
|
| Asia | United Arab Emirates |
| South America | Argentina |
| Asia | Armenia |
| Oceania | American Samoa |
| Antarctica | Antarctica |
| Antarctica | French Southern territories |
| North America | Antigua and Barbuda |
| Oceania | Australia |
| Europe | Austria |
| Asia | Azerbaijan |
...
| South America | Venezuela |
| North America | Virgin Islands, British |
| North America | Virgin Islands, U.S. |
| Asia | Vietnam |
| Oceania | Vanuatu |
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 5
| Oceania | Wallis and Futuna |
| Oceania | Samoa |
| Asia | Yemen |
| Europe | Yugoslavia |
| Africa | South Africa |
| Africa | Zambia |
| Africa | Zimbabwe |
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

+---------------+----------------------------------------------+
239 rows in set (0.01 sec)
5. Execute a SELECT statement that retrieves all the Region column data from the Country
table.
Compare your statement and results to those shown below:
mysql> SELECT Region FROM Country;
+---------------------------+
| Region |
+---------------------------+

to
| Caribbean |

1n ense
| Southern and Central Asia |
| Central Africa |
A
| Caribbean |
C 3% le lic
l% erab
| Southern Europe |
| Southern Europe |
n c
| Caribbean |
2 0I ansf
a% on-tr
| Middle East |
| South America | i l l
| Middle East |
o bad s a n eฺ
| Polynesia
r a B ha
|
uid
| Antarctica
d |
n yฺm entx ) G
| Antarctica
l e j a |

0A oฺuad s Stud
...
| South America |
2
el% corre e thi
| Caribbean |
a
| Caribbean
Y @
|
| Southeast Asia
l l a us |

b a di
| Melanesia
| Polynesia
|
|

l ฺb o | Polynesia |

ya e | Middle East |
( | Southern Europe
| Southern Africa
|
|
| Eastern Africa |
| Eastern Africa |
+---------------------------+
239 rows in set (0.00 sec)
6. Change the preceding SELECT statement to retrieve only the distinct Region column data
from the Country table.
Compare your statement and results to those shown below:
mysql> SELECT DISTINCT Region FROM Country;
+---------------------------+
| Region |
+---------------------------+
| Caribbean |
| Southern and Central Asia |
| Central Africa |

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 6
| Southern Europe |
| Middle East |
| South America |
| Polynesia |
| Antarctica |
| Australia and New Zealand |
| Western Europe |
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| Eastern Africa |
| Western Africa |
| Eastern Europe |
| Central America |
| North America |
| Southeast Asia |
| Southern Africa |
| Eastern Asia |
| Nordic Countries |
| Northern Africa |
| Baltic Countries |
| Melanesia |
to
| Micronesia
| British Islands
|
| A 1n ense
| Micronesia/Caribbean |
C 3% le lic
+---------------------------+
n c l% erab
0I aCity sftable where the
25 rows in set (0.16 sec)
7. Execute a SELECT statement that retrieves all columns2from the n
identification number is 3875. i l l a% on-tr
d a n below:
Compare your statement and resultsbtoathose shown
B o s d e ฺ
mysql> SELECT * a
ra x) h t Gu i
n d
-> FROM Citya
l e j = 3875;
d y ฺm den
-> WHERE
2 0A oฺua s Stu
ID

| IDel% hi
| Namerre | CountryCode
+------+---------+-------------+-----------+------------+
a c o e t | District | Population |
Y s
| Madisonu| USA
@
+------+---------+-------------+-----------+------------+
i
| 3875
l l a | Wisconsin | 208054 |
d
oba1 row in set (0.09 sec)
+------+---------+-------------+-----------+------------+

e l ฺb Execute a SELECT statement that retrieves names and population figures from the
( ya 8.
Country table where the population is less than 1000.
Compare your statement and results to those shown below:
mysql> SELECT Name, Population
-> FROM Country
-> WHERE Population < 1000;
+----------------------------------------------+------------+
| Name | Population |
+----------------------------------------------+------------+
| Antarctica | 0 |
| French Southern territories | 0 |
| Bouvet Island | 0 |
| Cocos (Keeling) Islands | 600 |
| Heard Island and McDonald Islands | 0 |
| British Indian Ocean Territory | 0 |
| Pitcairn | 50 |
| South Georgia and the South Sandwich Islands | 0 |

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 7
| United States Minor Outlying Islands | 0 |
+----------------------------------------------+------------+
9 rows in set (0.00 sec)
9. Execute a SELECT statement that retrieves the names of all cities from the City table in
descending Name order.
Compare your statement and results to those shown below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT Name


-> FROM City
-> ORDER BY Name DESC;
+-----------------------------------+
| Name |
+-----------------------------------+
| ´s-Hertogenbosch |
| Šumen |
| Štšolkovo |
| Šostka |
| Šiauliai | to
| Šahty |
A 1n ense
3% le lic
| Öskemen |
| Örebro
| [San Cristóbal de] la Laguna
|
| C
l% erab
n c
| Århus
| Zytomyr
|
| 2 0I ansf
| Zürich
i l
|
l a% on-tr
bad s a n eฺ
| Zwolle |
| Zwickau
o
B ha
|
...
d r a x ) G uid
| Abilene
j a n yฺm ent |
| Abiko
l e |
| Abidjan
| Abha 2 0A oฺuad s Stud |
|

a el% corre e thi


| Aberdeen |
Y @
| Abeokuta
us |
l l a
| Abbotsford |

b a di
| Abakan |

l ฺb o | Abaetetuba |

ya e | Abadan |
( | Aba
| Aalborg
|
|
| Aachen |
| A Coruña (La Coruña) |
+-----------------------------------+
4079 rows in set (0.03 sec)
10. Use a DESCRIBE statement to see which columns are available for querying in the
Country table.
Compare your statement and results to those shown below:
mysql> DESC CountryLanguage;
+-------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+-------+
| CountryCode | char(3) | NO | PRI | | |
| Language | char(30) | NO | PRI | | |
| IsOfficial | enum('T','F') | NO | | F | |
| Percentage | float(4,1) | NO | | 0.0 | |
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 8
+-------------+---------------+------+-----+---------+-------+
4 rows in set (0.02 sec)
11. Execute a SELECT statement that retrieves the country code and language from the
CountryLanguage table where the language is Swedish, in descending order of
CountryCode.
Compare your statement and results to those shown below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT CountryCode, Language


-> FROM CountryLanguage
-> WHERE Language = 'Swedish'
-> ORDER BY CountryCode DESC;
+-------------+----------+
| CountryCode | Language |
+-------------+----------+
| SWE | Swedish |
| NOR | Swedish |
| FIN | Swedish |
to
| DNK | Swedish |
A 1n ense
3% le lic
+-------------+----------+
4 rows in set (0.05 sec)
C
l%from the b table in
12. Execute a SELECT statement that retrieves the name of the cities
n c f e r aCity
0Ito 10.ans
ascending alphabetical order, and limit the number of rows
2
Compare your statement and results to thoseashown
i l l % below:
n - tr
mysql> SELECT Name
b a d a no
-> FROM City B o as i d eฺ
-> ORDER BY Name
n d raASC x) h t Gu
e
-> LIMIT l10;ja dyฺm den
2 0 A ฺua Stu
+----------------------+
| Namel%
e r r eo th|is
a o Coruña)
c(La se |
+----------------------+
Y
lla
| A Coruña@ u
a d i
| Aachen |

b o b | Aba
| Aalborg |

e l ฺ |

( ya | Abadan
| Abaetetuba |
|

| Abakan |
| Abbotsford |
| Abeokuta |
| Aberdeen |
+----------------------+
10 rows in set (0.02 sec)
13. Execute a SELECT statement that retrieves the country code and language from the
CountryLanguage table where the language is Chinese, in descending order of country
code. Limit the result to two rows.
Compare your statement and results to those shown below:
mysql> SELECT CountryCode, Language
-> FROM CountryLanguage
-> WHERE Language = 'Chinese'
-> ORDER BY CountryCode DESC
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 9
-> LIMIT 2;
+-------------+----------+
| CountryCode | Language |
+-------------+----------+
| VNM | Chinese |
| USA | Chinese |
+-------------+----------+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

2 rows in set (0.00 sec)


14. Execute a SELECT statement that retrieves all columns for countries where the GNP is
greater than the old GNP, in order of country name. Limit the result to three rows.
Compare your statement and results to those shown below:
mysql> SELECT *
-> FROM Country
-> WHERE GNP > GNPOld
-> ORDER BY Name
-> LIMIT 3\G to
1n ense
*************************** 1. row ***************************
A
3% le lic
Code: ALB
Name: Albania
Continent: Europe C
l% erab
n c
Region: Southern Europe
SurfaceArea: 28748.00 2 0I ansf
IndepYear: 1912
i l l a% on-tr
bad s a n eฺ
Population: 3401200
LifeExpectancy: 71.6
o
B ha
GNP: 3205.00
d r a x ) G uid
j a n yฺm ent
GNPOld: 2500.00
e
LocalName: Shqipëria
l
2 0A oฺuad s Stud
GovernmentForm: Republic
HeadOfState: Rexhep Mejdani

a el% corre e thi


Capital: 34
Y @ us
Code2: AL
l l a
*************************** 2. row ***************************

b a di Code: DZA

l ฺbo Name: Algeria

ya e Continent: Africa
( Region: Northern Africa
SurfaceArea: 2381741.00
IndepYear: 1962
Population: 31471000
LifeExpectancy: 69.7
GNP: 49982.00
GNPOld: 46966.00
LocalName: Al-Jaza’ir/Algérie
GovernmentForm: Republic
HeadOfState: Abdelaziz Bouteflika
Capital: 35
Code2: DZ
*************************** 3. row ***************************
Code: ATG
Name: Antigua and Barbuda
Continent: North America
Region: Caribbean
SurfaceArea: 442.00

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 10
IndepYear: 1981
Population: 68000
LifeExpectancy: 70.5
GNP: 612.00
GNPOld: 584.00
LocalName: Antigua and Barbuda
GovernmentForm: Constitutional Monarchy
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

HeadOfState: Elisabeth II
Capital: 63
Code2: AG
3 rows in set (0.00 sec)
15. Exit the mysql client:
Enter the following at the mysql> prompt:
mysql> EXIT
The following message appears and Control returns to the standard command prompt:
Bye
to
cmd>
A 1n ense
C 3% le lic
n c l% erab
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 11
Practice 7-2: Perform Basic Queries Using MySQL Workbench
Overview
In this practice, you use the MySQL Workbench GUI to perform basic SELECT statements. You
run the SQL Development module, and set the options to connect to the MySQL server.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Duration
This practice takes approximately 15 minutes to complete.

Tasks
1. Open MySQL Workbench by selecting it from the MySQL programs:
a. Select the Windows Start menu.
b. Select the All Programs menu.
c. Select MySQL.
d. Select MySQL Workbench 5.2 SE. to
1n ense
The MySQL Workbench window appears and displays the primary function modules:
A
3% le lic
SQL Development, Data Modeling, and Server Administration.
C
2. To use the SQL Development module for queries:
n c l% erab
0I ansf
Click the Open Connection to Start Querying link. The Connect to Database window
2
appears.
i l l a% on-tr
bad s a n eฺ
3. Enter the server connection information in the Connect to Database window:
o
a. Stored Connection: leave unselected
B ha
r a )
b. Connection Method: Standard (TCP/IP)
d x G uid
j a n yฺm ent
c. Hostname: localhost (or local system IP address)
l e
d. Port: 3306
2 0A oฺuad s Stud
el% corre e thi
e. Username: root
a
Y @ us
f. Password: Click the Store in Vault button. Enter ‘oracle’ as the password and click OK.
l l a
b a di
g. Default Schema: world_innodb

l ฺb o h. Click OK.

ya e i. The SQL Editor tab opens, with world_innodb selected in the list of schemas. A new
( query tab (Query 1) opens within the SQL Editor.
4. Execute this SELECT...FROM statement (from the previous practice) using the SQL Editor:
a. Enter this statement in the Query 1 tab:
SELECT Continent, Name FROM Country
− Note that the semicolon (;) terminator is not required within the SQL Editor.
b. Click the first button with the gold lightning bolt icon (Execute) at the top of the Query 1
tab to execute the query.
c. A new results tab (Country 1) appears below the Query 1 tab and contains the results
of your query. Confirm that they are identical to the results from the same query in the
previous practice.
− Use the scroll bars to scroll both horizontally and vertically, if needed.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 12
5. Execute this SELECT ...DISTINCT statement (from the previous practice) using the SQL
Editor:
a. Delete the previous statement and enter this one:
SELECT DISTINCT Region FROM Country
b. Click the Execute button (or press CTRL + ENTER).
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

6. Execute this SELECT ...WHERE statement (from the previous practice) using the SQL
Editor:
a. Delete the previous statement and enter this one:
SELECT Name FROM Country
WHERE Population < 1000
b. Click the Execute button (or press CTRL + ENTER).
7. Execute this SELECT ... ORDER BY statement (from the previous practice) using the SQL
Editor:
a. Delete the previous statement and enter this one:
to
SELECT CountryCode, Language FROM CountryLanguage
A 1n ense
WHERE Language = 'Swedish'
C 3% le lic
ORDER BY CountryCode DESC
n c l% erab
8. Execute this SELECT ... LIMIT statement (from the previous n s f using the SQL
0I practice)
2
Editor:
i l l a% on-tra
a. Delete the previous statement and enter
b a dthis one:a n ฺ
SELECT Name FROM City B o as uide
ORDER BY Name ASC dra ) h
j a n yฺmx ent G
LIMIT 10
A le ad tud
9. Close the SQL Editor2 0 ando ฺ
the uMySQLs Workbench:
S
a. From a l%File omenu,
ethe r e hi
re selecttExit.
b. Y @
The Workbench
c windowus closes.
l l a
b a di
l ฺ b o
e
(ya

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 13
Solution 7-2: Perform Basic Queries Using MySQL Workbench
There are no solutions for this practice. See the practice task instructions.
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 14
Practice 7-3: Perform Basic Queries on the Pets Database
Overview
In this practice, you query the Pets database you created in lesson 6. Because currently there
is no data in the database, you start by inserting a few rows into the pet_info table. Use either
the command-line client or the SQL Editor to write and execute the SQL statements. See
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

practice 7-2 for instructions for working with MySQL Workbench.


Note: The course covers the INSERT statement in detail in a later lesson.

Duration
This practice takes approximately 35 minutes to complete.

Tasks
1. Start the mysql client or MySQL Workbench and set the database to Pets.
2. Use a DESCRIBE statement to show the structure of the pet_info table.
to
3. Enter the following statement to add three rows of data to the table:
A 1n ense
INSERT INTO pet_info (pName, pGender, pBday, pDday,%oID, tID)
3 e l ic
VALUES ('Fluffy', 'F', '2003-02-04', NULL, 1,%1),
l C bl
c r a
('Claws', 'M', '2004-03-17', NULL, 2, 1),
2 0 In nsfe
('Buffy', 'F', '1999-05-13', NULL, % 1, 2); tra
− Now that you have some data in the pet_info d i l l a
n o n-you are ready to query the
table,
Pets database and answer questions
B oba about
a s athe data.eฺ
id
4. r
Show all tables in the Pets database.
d a Confirm
x ) h that the G upet_info table exists.
j a n ฺ m n t
5. Show all the data in theepet_info
0 A l a d ytable.
t u de
6. 2 eoฺ
Show only the first row in u
the pet_info
s S table.
l % r h i
7. Who owns
aeownercIDoris thesonly
YThe
Fluffy?
e t
Note:
l l a @ u information you have available at this time.
8. What d
a i the names of the cats (pet type ID of 1) born after January 1, 1993?
are
9. b
oList the distinct genders of all pets.
e l ฺb What is the name of the animal which is not a cat (pet type ID not equal to 1)?
( ya 10.
11. List the pet IDs and names for Claws and Buffy.
12. List all pet IDs and names for the owner (ID 1) of pets of type 2 or 3.
13. List all pets and their birthdays in ascending order of birth date.
14. List all pet IDs, names, and their birthdays, in descending order of birth date.
15. Exit the mysql client or MySQL Workbench.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 15
Solution 7-3: Perform Basic Queries on the Pets Database
Tasks
Note: The solutions use the mysql client, but you can also use MySQL Workbench. The
results are the same regardless of which tool you use. See practice 7-2 for instructions for
working with MySQL Workbench.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

1. Start the mysql client or MySQL Workbench and set the database to Pets.
a. Enter the following at the command prompt, and receive the results shown below:
cmd> mysql -u root -p
Enter password: oracle
...

mysql> USE Pets


Database changed
2. Use a DESCRIBE statement to show the structure of the pet_info table.
to
a. Compare your statement and results to those shown below:
A 1n ense
mysql> DESC pet_info;
C 3% le lic
| Extrarab
+---------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default
n c l% e |
0 I s f
|nauto_increment |
+---------+---------------+------+-----+---------+----------------+
| PRI | 2NULL ra
| pID | int(11) | NO
%
| illa | NULL - t
| pName | varchar(20)
| pGender | enum('M','F') | YESad
| NO
|n on || |

|o b | s a| NULLeฺ |
| NULL |
| pBday
| pDday
| date
| date a B YES
h
r | NOx) | t G
| YES |a | u i
NULL d |
|
|
| int(11)nd
| oID
l e j a yฺ m e n | NULL | |
| tID | int(11)
0 A a d | NO
t u d| | NULL | |

in2set (0.02
u
oฺ sec)his S
+---------+---------------+------+-----+---------+----------------+
7 rows%
l r r e t
3. aefollowing
Ythe
Enter c ostatements eto add three rows of data to the table:
l l u and results to those shown below:
a@your statement
i
a. Compare
d
l ฺb obamysql> INSERT INTO pet_info (pName, pGender, pBday, pDday, oID,
ya e tID)
( -> VALUES ('Fluffy', 'F', '2003-02-04', NULL, 1, 1),
-> ('Claws', 'M', '2004-03-17', NULL, 2, 1),
-> ('Buffy', 'F', '1999-05-13', NULL, 1, 2);
Query OK, 3 rows affected (0.06 sec)
Records: 3 Duplicates: 0 Warnings: 0
4. Show all tables in the Pets database. Confirm that the pet_info table exists.
a. Compare your statement and results to those shown below:
mysql> SHOW TABLES;
+----------------+
| Tables_in_pets |
+----------------+
| owners |
| pet_info |
| pet_types |
+----------------+

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 16
3 rows in set (0.00 sec)
5. Show all the data in the pet_info table.
a. Compare your statement and results to those shown below:
mysql> SELECT * FROM pet_info;
+-----+--------+---------+------------+-------+-----+-----+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| pID | pName | pGender | pBday | pDday | oID | tID |


+-----+--------+---------+------------+-------+-----+-----+
| 1 | Fluffy | F | 2003-02-04 | NULL | 1 | 1 |
| 2 | Claws | M | 2004-03-17 | NULL | 2 | 1 |
| 3 | Buffy | F | 1999-05-13 | NULL | 1 | 2 |
+-----+--------+---------+------------+-------+-----+-----+
3 rows in set (0.05 sec)
6. Show only the first row contained in the pet_info table.
a. Compare your statement and results to those shown below:
mysql> SELECT * FROM pet_info LIMIT 1;
+-----+--------+---------+------------+-------+-----+-----+
to
| pID | pName | pGender | pBday | pDday | oID | tID |
A 1n ense
3% le lic
+-----+--------+---------+------------+-------+-----+-----+
| 1 | Fluffy | F | 2003-02-04 | NULL | 1 | 1 |
+-----+--------+---------+------------+-------+-----+-----+ C
l% erab
1 row in set (0.05 sec)
I n c f
2 0 n s
7. Who owns Fluffy?
l l % n-tra
ashown
a. Compare your statement and results to those
a d i n obelow:
mysql> SELECT oID FROM pet_info
B ob aWHERE s a pName
i d e ฺ = 'Fluffy';
+-----+
n d ra x) h t Gu
ja dyฺm den
| oID |
+-----+
l e
| 1 |
+-----+ 2
0A oฺua s Stu
a el% o r re sec)thi
1 row
Y @
in set (0.08
c of the u e
scats
8. What are the
i l l a names (pet type ID of 1) born after January 1, 2003?
d
oba
a. Compare your statement and results to those shown below:

e l ฺb mysql> SELECT pName FROM pet_info


( ya -> WHERE tID = 1 AND pBday > '2003-01-01';
+--------+
| pName |
+--------+
| Fluffy |
| Claws |
+--------+
2 rows in set (0.02 sec)
9. List the distinct genders of all pets.
a. Compare your statement and results to those shown below:
mysql> SELECT DISTINCT pGender FROM pet_info;
+---------+
| pGender |
+---------+
| F |
| M |
+---------+
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 17
2 rows in set (0.05 sec)
10. What is the name and type (ID) of the animal which is not a cat (pet type ID not equal to 1)?
a. Compare your statement and results to those shown below:
mysql> SELECT pName, tID FROM pet_info WHERE tID != 1;
+-------+-----+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| pName | tID |
+-------+-----+
| Buffy | 2 |
+-------+-----+
1 row in set (0.01 sec)
11. List the pet IDs and names for Claws and Buffy.
a. Compare your statement and results to those shown below:
mysql> SELECT pID, pName FROM pet_info
-> WHERE pName IN ('Claws', 'Buffy');
+-----+-------+
| pId | pName | to
+-----+-------+
A 1n ense
3% le lic
| 2 | Claws |
| 3 | Buffy |
C
l% erab
+-----+-------+
I n c f
2 rows in set (0.09 sec)
2 0 a3.n s
12. List all pet IDs and names for the owner (ID 1) of pets %of type 2tror
i l l a n -
a. Compare your statement and results to those
b a d shown a nobelow:
mysql> SELECT pID, pNameBfrom o pet_info
a s i d eฺ
-> WHERE oID = d
n 1ra x ) h t Gu
-> AND (tID
l e ja= 2 OR
d y ฺm den
tID=3);
0A| oฺua s Stu
+-----+-------+
2
a e l% orre
| pID | pName
+-----+-------+
e t hi
Y
|
@ c | us
3 | Buffy
ill a
+-----+-------+
a1d
oListb all pets and their birthdays in ascending order of birth date.
row in set (0.00 sec)

l ฺ
13. b
( yae a. Compare your statement and results to those shown below:
mysql> SELECT pName, pBday FROM pet_info
-> ORDER BY pBday ASC;
+--------+------------+
| pName | pBday |
+--------+------------+
| Buffy | 1999-05-13 |
| Fluffy | 2003-02-04 |
| Claws | 2004-03-17 |
+--------+------------+
3 rows in set (0.03 sec)
14. List all pet IDs, names, and their birthdays in descending order of birth date.
a. Compare your statement and results to those shown below:
mysql> SELECT pID, pName, pBday FROM pet_info
-> ORDER BY pBday DESC;

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 18
+-----+--------+------------+
| pID | pName | pBday |
+-----+--------+------------+
| 2 | Claws | 2004-03-17 |
| 1 | Fluffy | 2003-02-04 |
| 3 | Buffy | 1999-05-13 |
+-----+--------+------------+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

3 rows in set (0.01 sec)


15. Exit the mysql client or MySQL 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 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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 19
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Basic Queries


Chapter 7 - Page 20
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
Practices for n c l% era8:b
Lesson
2 0I ansf
Database a% oand-tr Table
i l l n
o ad a n ฺ
bMaintenance
r a ) as 8 uide
B Chapter
h
j a nd yฺmx ent G
A le ad tud
2 0 ฺ u S
e l % rreo this
Ya @co use
d i lla
l ฺboba
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 1
Practices for Lesson 8: Overview
Practices Overview
These practices test your knowledge of database and table maintenance. They target the
Windows operating system, provided in Oracle classrooms. For non-Oracle classrooms, you
might need to adjust file locations.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Assumptions
• You have installed and configured the MySQL server.
• You have created and populated the world_innodb database.
• You can access the mysql client from a command-line prompt.
• You can access MySQL Workbench if you choose to complete the practices using this
tool.

to
A 1n ense
C 3% le lic
n c l% erab
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm 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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 2
Practice 8-1: Removing a Database
Overview
In this practice, you create a new database and then drop it.

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

This practice takes approximately 10 minutes to complete.

Tasks
1. Create a new database called db1.
2. Show the list of current databases and confirm that the new database is there.
3. Issue a DROP DATABASE statement to remove the entire db1 database.
4. Show the list of current databases and confirm that the database is gone.
Note: Keep your mysql session open for the next practice.
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 3
Solutions 8-1: Removing a Database
Tasks
1. Create a new database called db1.
Log in to the mysql client program and execute the CREATE DATABASE statement
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

shown below:
cmd> mysql -uroot -poracle
...

mysql> CREATE DATABASE db1;


Query OK, 1 row affected (0.14 sec)
2. Show the list of current databases and confirm that the new database is there.
Compare your statement and results to those shown below:
mysql> SHOW DATABASES;
to
+--------------------+
| Database | A 1n ense
+--------------------+
C 3% le lic
| information_schema |
n c l% erab
0I ansf
| db1 |
| mysql |
2
| performance_schema |
i l l a% on-tr
bad s a n eฺ
| pets |
| sakila |
o
B ha uid
| test |
| world |
d r a x ) G
| world_innodb
j|a n yฺm ent
l e
0A oฺuad s Stud
+--------------------+
2
9 rows in set (0.00 sec)
3. el%DATABASE
Issue a DROP
a o r re statement
e t hi to remove the entire db1 database.
Y
Compare @ c us and results to those shown below:
your statement
a
ill DROP DATABASE db1;
a d
mysql>

l ฺb ob Query OK, 0 rows affected (0.19 sec)


e
ya 4. Show the list of current databases and confirm that the database has gone.
( Compare your statement and results to those shown below:
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| pets |
| sakila |
| test |
| world |
| world_innodb |
+--------------------+
8 rows in set (0.00 sec)
Note: Keep your mysql session for the next practice.
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 4
Practice 8-2: Creating a New Table and Removing a Table
Overview
In this practice, you create a new table containing records from an existing table. Later, you
remove the table and its data.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Duration
This practice takes approximately 15 minutes to complete.

Tasks
1. View the CREATE TABLE statement for the City table from the world_innodb database.
2. Issue a CREATE TABLE...SELECT statement to create a new table called
GelderlandDist with the Name, District, and CountryCode values from the City
table, for all cities in the Gelderland district.
Hint: The new table name does not require quotation marks, but the District name
to
does.
A 1n ense
3% le licthe
3. Show the list of tables. Confirm that the GelderlandDist table is now on the list.
4. Select all the rows from the GelderlandDist table. Confirm that the C
l% erabtable contains
columns specified and four rows of corresponding data. n c
5. Issue a CREATE TABLE...LIKE statement to create a2new sf
0I tableancalled
GelderlandDist2 with the same structure asilthe l a% n - tr
GelderlandDist table. Execute the
d n o
oba as a idetable
appropriate statements to confirm that the structure is the same.
6. Show the list of tables. Confirm that B the GelderlandDist2
ฺ is now on the list.
d rato delete
x h Gu
) the
7. Issue the DROP TABLE statement n ฺmdid not
ja if thedtable e n t GelderlandDist2 table. Suppress
entire
e
any errors that would lresult y
tud
exist.
0A Confirm
8. Show the list of2tables. ฺ u
o his
athat theSGelderlandDist2 table is gone.
l % r e
Note: Keepayour
Y @
e mysql corsession
u s e t to use in the next practice.
open

i l l a
o b ad
e l ฺb
( ya

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 5
Solutions 8-2: Creating a New Table and Removing a Table
Tasks
1. View the CREATE TABLE statement for the City table from the world_innodb database.
Compare your statement and results to those shown below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> USE world_innodb


Database changed

mysql> SHOW CREATE TABLE City\G


*************************** 1. row ***************************
Table: City
Create Table: CREATE TABLE `city` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` char(35) NOT NULL DEFAULT '',
`CountryCode` char(3) NOT NULL DEFAULT '',
`District` char(20) NOT NULL DEFAULT '',
to
`Population` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`), A 1n ense
KEY `CountryCode` (`CountryCode`),
C 3% le lic
CONSTRAINT `city_ibfk_1` FOREIGN KEY (`CountryCode`)
n c l% erab
0I ansf
REFERENCES `country` (`Code`)
) ENGINE=InnoDB AUTO_INCREMENT=4080 DEFAULT CHARSET=latin1
2
% n-tr
1 row in set (0.00 sec)
i l l a o
− Returns the CREATE TABLE statement
b a d usedafornCity.
2. Issue a CREATE TABLE...SELECTB o atoscreate iadnew
statement eฺ table called
GelderlandDist with the Name,
n d raDistrict,
x ) h andt CountryCode
G u values from the City
a ฺ
lej aanddyresults
table, for all cities in the Gelderland m
district.
e n
Compare your 0 Astatement t tod
u those shown below:
2 u S
oฺ GelderlandDist
s
l %CREATEre
e-> cSELECT
mysql>
r Name,
TABLE h i
t District, CountryCode AS
Y @ a o s e
l l a uCity
b a di -> WHERE District = 'Gelderland';
-> FROM

l ฺb o
ya e Query OK, 4 rows affected (0.22 sec)
( Records: 4 Duplicates: 0 Warnings: 0
3. Show the list of tables. Confirm that the GelderlandDist table is now on the list.
Compare your statement and results to those shown below:
mysql> SHOW TABLES;
+------------------------+
| Tables_in_world_innodb |
+------------------------+
| city |
| country |
| country2 |
| countrylanguage |
| gelderlanddist |
+------------------------+
5 rows in set (0.22 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 6
4. Select all the rows from the GelderlandDist table. Confirm that the table contains the
columns specified and four rows of corresponding data.
Compare your statement and results to those shown below:
mysql> SELECT * FROM GelderlandDist;
+-----------+------------+-------------+
| Name | District | CountryCode |
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

+-----------+------------+-------------+
| Apeldoorn | Gelderland | NLD |
| Nijmegen | Gelderland | NLD |
| Arnhem | Gelderland | NLD |
| Ede | Gelderland | NLD |
+-----------+------------+-------------+
4 rows in set (0.00 sec)
5. Issue a CREATE TABLE...LIKE statement to create a new table called
GelderlandDist2 with the same structure as the GelderlandDist table. Execute the
appropriate statements to confirm that the structure is the same.
a. Create the new table: to
mysql> CREATE TABLE GelderlandDist2 LIKE GelderlandDist; A 1n ense
Query OK, 0 rows affected (0.01 sec)
C 3% le lic
b. Confirm that the structure is the same as the GelderlandDist
n c l% table:
f e r ab
2 0I ans
a% on-tr
mysql> DESC GelderlandDist2;
i l l
+--------------+----------+------+-----+---------+-------+
| Field | Type
o bad| Key
| Null
s a|nDefault | Extra |
eฺ |
| Name
r
| char(20) B
+--------------+----------+------+-----+---------+-------+
| NO |a
a | NOx) h| G PRI | u i d |
| District n d
| char(20) t
char(3)yฺ|m
| | |
| CountryCode e | ja |en |
A l a d NO
t u d | |
0 oฺusec) s S
+--------------+----------+------+-----+---------+-------+
3 rows in2set (0.05
a
%
o r e hi the GelderlandDist2 table is now on the list.
reConfirmtthat
elistl of tables.
6. Y @c us
Show the

d i lla your statement and results to those shown below:


Compare

l ฺb obamysql> SHOW TABLES;


+------------------------+
ya e | Tables_in_world_innodb |
( +------------------------+
| city |
| country |
| country2 |
| countrylanguage |
| gelderlanddist |
| gelderlanddist2 |
+------------------------+
6 rows in set (0.22 sec)
7. Issue the DROP TABLE statement to delete the entire GelderlandDist2 table. Suppress
any errors that would result if the table did not exist.
Compare your statement and results to those shown below:
mysql> DROP TABLE IF EXISTS GelderlandDist2;
Query OK, 0 rows affected (0.03 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 7
8. Show the list of tables. Confirm that the GelderlandDist2 table is gone.
Compare your statement and results to those shown below:
mysql> SHOW TABLES;
+------------------------+
| Tables_in_world_innodb |
+------------------------+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| city |
| country |
| country2 |
| countrylanguage |
| gelderlanddist |
+------------------------+
5 rows in set (0.33 sec)
− GelderlandDist2 is no longer on the list.

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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 8
Practice 8-3: Altering Table Columns
Overview
In this practice, you modify the data type of a column and add a new column to a table.

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

This practice takes approximately 15 minutes to complete.

Tasks
1. Use the DESCRIBE statement to view the structure of the GelderlandDist table.
2. Use an ALTER TABLE statement to modify the Name column in the GelderlandDist
table to have a character data type with a length of 20.
3. View the table structure to confirm the change.
4. Use an ALTER TABLE statement to add a new column called Inauguration, which holds
date information and does not allow NULL values. to
5. Confirm the addition of the new column.
A 1n ense
3% le lic
6. List all the row data in the table to inspect the new column’s values.
C
n c l% erab
Note: Keep your mysql session open to use in the next practice.

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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 9
Solutions 8-3: Altering Table Columns
Tasks
1. Use the DESCRIBE statement to view the structure of the GelderlandDist table.
Compare your statement and results to those shown below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> DESCRIBE GelderlandDist;


+-------------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+----------+------+-----+---------+-------+
| Name | char(35) | NO | | | |
| District | char(20) | NO | | | |
| CountryCode | char(3) | NO | | | |
+-------------+----------+------+-----+---------+-------+
3 rows in set (0.38 sec)
− The output shows the current attributes for each column in the table.
2. Use an ALTER TABLE statement to modify the Name column in the GelderlandDist
table to have a character data type with a length of 20. n nse to
A 1
Compare your statement and results to those shown below:
3 % e lice
mysql> ALTER TABLE GelderlandDist
l % C bl
I n c f e ra
-> MODIFY Name char(20);
20 tran s
Query OK, 4 rows affected (0.14 sec)
%
lla0 non-
Records: 4 Duplicates: 0 Warnings:
d i
3.
oba as a ideฺ
View the table structure to confirm the change.
B
Compare your statement and
d h shown
raresultsxto) those G u below:
mysql> DESCRIBEja n ฺm den
GelderlandDist; t
l e d y
A ฺua | Null tu | Key | Default | Extra |
+-------------+----------+------+-----+---------+-------+
| Field 20 | Type S
o s
el% corr|echar(20) thi | YES | | NULL |
+-------------+----------+------+-----+---------+-------+
| a e
Y Name
@ u s |

|d i lla
| District | char(20) | NO | | | |

o b a CountryCode | char(3) | NO | |
+-------------+----------+------+-----+---------+-------+
| |

e l ฺb 3 rows in set (0.00 sec)

( ya − Note that the Null column value for the Name field is now YES, indicating that the
column allows null values. Columns allow null values by default when you do not
specify NOT NULL.
4. Use an ALTER TABLE statement to add a new column called Inauguration, which holds
date information and does not allow NULL values.
Compare your statement and results to those shown below:
mysql> ALTER TABLE GelderlandDist
-> ADD Inauguration DATE NOT NULL;
Query OK, 4 rows affected (0.01 sec)
Records: 4 Duplicates: 0 Warnings: 0
Note: If the NO_ZERO_IN_DATE or NO_ZERO_DATE SQL modes are set, you get an error.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 10
5. Confirm the addition of the new column.
Compare your statement and results to those shown below:
mysql> DESCRIBE GelderlandDist;
+--------------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+----------+------+-----+---------+-------+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| Name | char(20) | YES | | NULL | |


| District | char(20) | NO | | | |
| CountryCode | char(3) | NO | | | |
| Inauguration | date | NO | | NULL | |
+--------------+----------+------+-----+---------+-------+
4 rows in set (0.03 sec)
6. List all the row data in the table to inspect the new column’s values.
Compare your statement and results to those shown below::
mysql> SELECT * FROM GelderlandDist;
+-----------+------------+-------------+--------------+
| Name | District | CountryCode | Inauguration | to
+-----------+------------+-------------+--------------+
A 1n ense
3% le lic
| Apeldoorn | Gelderland | NLD | 0000-00-00 |
| Nijmegen | Gelderland | NLD | 0000-00-00 |
C
l% erab
| Arnhem | Gelderland | NLD | 0000-00-00
n c|
| Ede | Gelderland | NLD
0I ansf
| 0000-00-00
2
|

a% on-tr
+-----------+------------+-------------+--------------+
4 rows in set (0.00 sec)
i l l
o badvalues
− Note that the Inauguration column
a n beenฺ set to an “empty date”.
have

r a ) as uide
Note: Keep your mysql session open forBthe next practice.
h
j a nd yฺmx ent G
A le ad tud
2 0 ฺ u S
e l % rreo this
Ya @co use
d i lla
b o ba
a e lฺ
( y

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 11
Practice 8-4: Modifying Table Indexes and Constraints
Overview
In this practice, you modify the table index and constraints.

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

This practice takes approximately 15 minutes to complete.

Tasks
1. Show the CREATE TABLE statement for the City table.
2. Issue an ALTER TABLE statement to add an index to the Name column in the City table.
Call the index CityName.
3. Show the CREATE TABLE statement for the City table. Examine the part of the statement
that adds the CityName index.
4. Use an ALTER TABLE statement to drop the CityName key/index from the City table. to
5. Confirm that the index has gone.
A 1n ense
6. 3% le lic
Show the GelderlandDist table structure. You are going to alter this table structure, so
C
review it first.
n c l% erab
7. 0I ansf
Issue an ALTER TABLE statement to add a primary key to the Name column in the
2
GelderlandDist table.
i l l a% on-tr
bad s a n eฺ
8. Confirm the existence of the primary key.
o
Note: Keep your mysql session open for the next practice.
Important: The changes you d r aB
make x
to the ) ha Guiddatabase in these lessons are
world_innodb
cumulative. Do not attemptj a nto undoyany
ฺ m e
changes n t make to the database in this or future
you
l e
practices.
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 12
Solutions 8-4: Modifying Table Indexes and Constraints
Tasks
1. Show the CREATE TABLE statement for the City table.
Compare your statement and results to those shown below::
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SHOW CREATE TABLE City\G


*********************** 1. row ***********************
Table: City
Create Table: CREATE TABLE `city` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` char(35) NOT NULL DEFAULT '',
`CountryCode` char(3) NOT NULL DEFAULT '',
`District` char(20) NOT NULL DEFAULT '',
`Population` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`),
KEY `CountryCode` (`CountryCode`), to
CONSTRAINT `city_ibfk_1` FOREIGN KEY (`CountryCode`)
A 1n ense
REFERENCES `country` (`Code`)
C 3% le lic
) ENGINE=InnoDB AUTO_INCREMENT=4080 DEFAULT CHARSET=latin1
n c l% erab
1 row in set (0.08 sec)
I
0Name n s f
2. Issue an ALTER TABLE statement to add an index to the
% 2 t r a in the City table.
column
Call the index CityName. l a
il non -
a d
B obto those
Compare your statement and results
a s a below:
shown
i d e ฺ
mysql> ALTER TABLE City
n d ra x) h t Gu
-> ADD INDEX
lejaaffected ฺm den
CityName(Name);
d y
Query OK, 0 A
2 0 rows
ฺ u a (0.16
S tu sec)
l
Records:
e r r eo th0is Warnings: 0
% 0 Duplicates:
3. Show a CREATEcoTABLEsstatement
Ythe e for the City table. Examine the part of the statement
a
that addsllthe@ u
CityName index.
b a di your statement and results to those shown below:
Compare
l ฺb o
ya e mysql> SHOW CREATE TABLE City\G
( *************************** 1. row ***************************
Table: City
Create Table: CREATE TABLE `city` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` char(35) NOT NULL DEFAULT '',
`CountryCode` char(3) NOT NULL DEFAULT '',
`District` char(20) NOT NULL DEFAULT '',
`Population` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`),
KEY `CountryCode` (`CountryCode`),
KEY `CityName` (`Name`),
CONSTRAINT `city_ibfk_1` FOREIGN KEY (`CountryCode`)
REFERENCES `country` (`Code`)
) ENGINE=InnoDB AUTO_INCREMENT=4080 DEFAULT CHARSET=latin1

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 13
1 row in set (0.00 sec)
4. Use an ALTER TABLE statement to drop the CityName key/index from the City table.
Compare your statement and results to those shown below:
mysql> ALTER TABLE City
-> DROP INDEX CityName;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Query OK, 0 rows affected (0.01 sec)


Records: 0 Duplicates: 0 Warnings: 0
5. Confirm that the index has gone.
Compare your statement and results to those shown below::
mysql> SHOW CREATE TABLE City\G
*********************** 1. row ***********************
Table: City
Create Table: CREATE TABLE `city` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
to
`Name` char(35) NOT NULL DEFAULT '',
A 1n ense
`CountryCode` char(3) NOT NULL DEFAULT '',
C 3% le lic
`District` char(20) NOT NULL DEFAULT '',
n c l% erab
0I ansf
`Population` int(11) NOT NULL DEFAULT '0',
2
a% on-tr
PRIMARY KEY (`ID`),
KEY `CountryCode` (`CountryCode`),
i l l
bad s a n eฺ
CONSTRAINT `city_ibfk_1` FOREIGN KEY (`CountryCode`)
o
REFERENCES `country` (`Code`)
r a B ha uid
d
n yฺm ent x ) G
) ENGINE=InnoDB AUTO_INCREMENT=4080 DEFAULT CHARSET=latin1
l e j a
tud in the statement.
adlongerSappears
1 row in set (0.08 sec)
2 0A index
− The CityName ฺ uno
6. Show the e l % rreo table t h s
istructure.
Y a
Compare @ co useand results to those shown below:
GelderlandDist
your statement
d i lla DESCRIBE GelderlandDist;
b o ba+--------------+----------+------+-----+---------+-------+
mysql>

elฺ
(ya
| Field | Type | Null | Key | Default | Extra |
+--------------+----------+------+-----+---------+-------+
| Name | char(20) | YES | | NULL | |
| District | char(20) | NO | | | |
| CountryCode | char(3) | NO | | | |
| Inauguration | date | NO | | NULL | |
+--------------+----------+------+-----+---------+-------+
4 rows in set (0.02 sec)
− The DESCRIBE statement also shows information about a table’s structure.
7. Issue an ALTER TABLE statement to add a primary key to the Name column in the
GelderlandDist table.
Compare your statement and results to those shown below:
mysql> ALTER TABLE GelderlandDist
-> ADD PRIMARY KEY(Name);

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 14
Query OK, 4 rows affected (0.03 sec)
Records: 4 Duplicates: 0 Warnings: 0
8. Confirm the existence of the primary key.
Compare your statement and results to those shown below::
mysql> DESC GelderlandDist;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

+--------------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+----------+------+-----+---------+-------+
| Name | char(20) | NO | PRI | | |
| District | char(20) | NO | | | |
| CountryCode | char(3) | NO | | | |
| Inauguration | date | NO | | NULL | |
+--------------+----------+------+-----+---------+-------+
4 rows in set (0.05 sec)
− The PRI indicator in the KEY field shows that the Name is now the primary key. Note to
1n ense
that the Name column does not allow null values now that it is the primary key.
A
Note: Keep your mysql session open for the next practice.
C 3% le lic
Important: The changes you make to the world_innodb database
n c f ablessons are
l% in ethese
r
0Ito theadatabase
cumulative. Do not attempt to undo any changes you make
2 n s in this or future
practices.
l l a% on-t r
i
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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 15
Practice 8-5: Further Practice
Overview
In this practice, you reinforce your knowledge of database and table maintenance with these
additional tasks:
• Creating a new table
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Adding, modifying, and removing column indexes and constraints


• Dropping a table

Duration
This practice takes approximately 20 minutes to complete.

Tasks
1. Show the CREATE TABLE statement for the City table. You are going to use City as the
basis of a new table, so review its structure first.
to
2. Add a new table to world_innodb called Big_Cities using a SELECT on the City
A 1n ense
table. Create Big_Cities so it contains the ID, Name, and Population columns for all
C 3% le lic
cities with a population greater than eight million. Confirm the addition of the table.
n c l% erab
3.
0I ansf
Examine the table structure to confirm that the specified columns are included and their
data types match. 2
4. Display all the records in the Big_Cities table. i l l a% on-tr
ad city was
beach a nestablished.
5. Add a Founded column to store the date
B o a s i d eฺ Allow NULL values.
View the table structure to confirm.
n d ra table x ) hand confirm
t G u
6. View the contents of the Big_Cities
l e j a y ฺ m e n that the new column exists. Note
that all its values are nulls.
2 0A column. ฺ u d
aView S ud
tstructure
7. Remove the Founded
l % r e o his the to confirm its deletion.
8. Change
Y athe c or sosthat
e ID column e itt accepts null values. View the table structure to confirm.
9. Make the lID a@column theu primary key. Confirm the change.
d i l
b o ba an indexand(called
10. Create Pop) on the Population column. Examine the structure of

e l ฺ Big_Cities its CREATE TABLE statement to confirm the change.


( ya 11. Remove the index on the Population column. Confirm the change.
12. Remove the Big_Cities table. View the list of tables in the world_innodb database to
confirm that it has gone.
13. Exit the mysql client.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 16
Solutions 8-5: Further Practice
Tasks
1. Show the CREATE TABLE statement for the City table.
Compare your statement and results to those shown below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SHOW CREATE TABLE City\G


*************************** 1. row ***************************
Table: city
Create Table: CREATE TABLE `city` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` char(35) NOT NULL DEFAULT '',
`CountryCode` char(3) NOT NULL DEFAULT '',
`District` char(20) NOT NULL DEFAULT '',
`Population` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`), to
KEY `CountryCode` (`CountryCode`),
A 1n ense
CONSTRAINT `city_ibfk_1` FOREIGN KEY (`CountryCode`) REFERENCES
C 3% le lic
`country` (`Code`)
n c l% erab
0I ansf
) ENGINE=InnoDB AUTO_INCREMENT=4080 DEFAULT CHARSET=latin1
2
1 row in set (0.00 sec)
l l a % n-tr
2. Create a new table called Big_Cities by using
a i
d Population no onฺcolumns
a SELECT the City table.
Big_Cities should contain the ID, Name, b
o theand
s a ethe table. for all cities with a
B a
h Gu
raresultsxto) those
population greater than eight million. Confirm additioni d
of
a. Compare your statement a n dand m n tshown below:
e j y ฺ e
mysql> CREATE
2 0 Al TABLE ฺ u d
aBig_Cities
S tud
->%SELECT e
l r o name,
id,
h is population from City
e
a -> WHERE r
co population e t
Y @ u s
QuerylaOK, 10 rows affected (0.03 sec)
> 8000000;

a d il 10 Duplicates: 0 Warnings: 0
Records:

l ฺb obb. Confirm the addition of the table:


ya e
( mysql> SHOW TABLES;
+------------------------+
| Tables_in_world_innodb |
+------------------------+
| big_cities |
| city |
| country |
| country2 |
| countrylanguage |
| gelderlanddist |
+------------------------+
6 rows in set (0.01 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 17
3. Examine the table structure to confirm that the specified columns are included and their
data types match.
Compare your statement and results to those shown below:
mysql> DESCRIBE Big_Cities;
+------------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

+------------+----------+------+-----+---------+-------+
| id | int(11) | NO | | 0 | |
| name | char(35) | NO | | | |
| population | int(11) | NO | | 0 | |
+------------+----------+------+-----+---------+-------+
3 rows in set (0.02 sec)
− The three specified columns are present with the same attributes as those in the
City table.
4. Display all the records in the Big_Cities table.
Compare your statement and results to those shown below:
to
mysql> SELECT * FROM Big_Cities;
+------+------------------+------------+ A 1n ense
| id | name | population | 3 % e lic
+------+------------------+------------+
l C
% rabl
| 206 | São Paulo | 9968485 |
n c fe
9604900 | 0I s
| 939 | Jakarta |
2 n
| 1024 | Mumbai (Bombay) | 10500000%
i l l a || on-tra
| 1890 | Shanghai |
| ba
d
9696300
9981619a| n
eฺ
| 2331 | Seoul
| 2515 | Ciudad de México B | o a
8591309s |
i d
h G
ra || x)9269265 | u
| 3357 | Istanbuland
| 2822 | Karachi
j ฺ m n
8787958
e t |
A l e y d
d | tu8008278
York ฺua
| 3580 | Moscow | 8389200 |
| 3793 | New
2 0 o s S |
el % e i
orr (0.00 th
+------+------------------+------------+
10arows incset
Y e
@ columnutosstore the date each city was established. Allow NULL values.
sec)
l l a
5.
b
Viewa di table structure to confirm.
Add a Founded
the
l o
ฺb a. Compare your statement and results to those shown below:
ya e
( mysql> ALTER TABLE Big_Cities ADD COLUMN Founded DATE NULL;
Query OK, 0 rows affected (0.32 sec)
Records: 0 Duplicates: 0 Warnings: 0
b. View the structure to confirm:
mysql> DESC Big_Cities;
+------------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+-------+
| id | int(11) | NO | | 0 | |
| name | char(35) | NO | | | |
| population | int(11) | NO | | 0 | |
| Founded | date | YES | | NULL | |
+------------+----------+------+-----+---------+-------+
4 rows in set (0.03 sec)
− The new column has been added and allows null values.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 18
6. View the contents of the Big_Cities table and confirm that the new column exists.
Compare your statement and results to those shown below:
mysql> SELECT * FROM Big_Cities;
+------+------------------+------------+---------+
| id | name | population | Founded |
+------+------------------+------------+---------+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| 206 | Sπo Paulo | 9968485 | NULL |


| 939 | Jakarta | 9604900 | NULL |
| 1024 | Mumbai (Bombay) | 10500000 | NULL |
| 1890 | Shanghai | 9696300 | NULL |
| 2331 | Seoul | 9981619 | NULL |
| 2515 | Ciudad de MΘxico | 8591309 | NULL |
| 2822 | Karachi | 9269265 | NULL |
| 3357 | Istanbul | 8787958 | NULL |
| 3580 | Moscow | 8389200 | NULL |
| 3793 | New York | 8008278 | NULL |
+------+------------------+------------+---------+
10 rows in set (0.00 sec)
to
− The new column defaults to null values.
A 1n ense
7. Remove the Founded column.
C 3% le lic
a. Compare your statement and results to those shown below:
n c l% erab
mysql> ALTER TABLE Big_Cities DROP Founded; 0 I n s f
2
Query OK, 0 rows affected (0.32 sec) %
i l l a0 on-tra
bad s a n eฺ
Records: 0 Duplicates: 0 Warnings:
o
b. View the structure to confirm its deletion:
B ha
mysql> DESC Big_Cities;
d r a x ) G uid
j a n yฺm ent
+------------+----------+------+-----+---------+-------+
e
|l Type
0A oฺuad s Stud
| Field | Null | Key | Default | Extra |
2
+------------+----------+------+-----+---------+-------+

| a e cor||reint(11)
| id l%
e th||i NO | | 0 | |
Y name
@ u s | NO | | 0
char(35) NO | | | |

i l l a
| population | int(11) | |
d
+------------+----------+------+-----+---------+-------+

l oba3 rows in set (0.02 sec)


ฺb Change the ID column so that it accepts null values. View the table structure to confirm.
ya e8.
( a. Compare your statement and results to those shown below:
mysql> ALTER TABLE Big_Cities MODIFY ID INT(11) NULL;
Query OK, 0 rows affected (0.32 sec)
Records: 0 Duplicates: 0 Warnings: 0
b. View the structure to confirm:
mysql> DESC Big_Cities;
+------------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+-------+
| ID | int(11) | YES | | NULL | |
| name | char(35) | NO | | | |
| population | int(11) | NO | | 0 | |
+------------+----------+------+-----+---------+-------+
3 rows in set (0.02 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 19
9. Make the ID column the primary key. Confirm the change.
a. Compare your statement and results to those shown below:
mysql> ALTER TABLE Big_Cities ADD PRIMARY KEY (ID);
Query OK, 0 rows affected (0.57 sec)
Records: 0 Duplicates: 0 Warnings: 0
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

b. Confirm the change:


mysql> DESC Big_Cities;
+------------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | | |
| name | char(35) | NO | | | |
| population | int(11) | NO | | 0 | |
+------------+----------+------+-----+---------+-------+
3 rows in set (0.02 sec)
10. Create an index (called Pop) on the Population column.
to
a. Compare your statement and results to those shown below:
A 1n ense
mysql> ALTER TABLE Big_Cities ADD INDEX Pop (Population); 3 % e lic
Query OK, 0 rows affected (0.17 sec)
l C
% rabl
Records: 0 Duplicates: 0 Warnings: 0 c
In nsfe
2 0
b. Examine the structure of Big_Cities:
l l a % n-tra
mysql> DESC Big_Cities;
a i
d a no
b
o as| Default
+------------+----------+------+-----+---------+-------+
eฺ| Extra |
|B i d
| Field | Type
n d ra x) h t Gu
Null | Key
+------------+----------+------+-----+---------+-------+
| ID
e ja d||yฺNO
| int(11)
l m | PRI e n| | |
0A| int(11) d
a | NOStu| MUL | 0
| name
| population 2
|
ฺ u
char(35)
o his
NO | | |
|
|
|
l % r e
e set or (0.02sesec)t
+------------+----------+------+-----+---------+-------+
3 a
Y rows in c
l l aMUL u field of the population column indicates that it participates in
@ in the Key
i
− The
d
l oba a multi-column index.
ฺb c. View the CREATE TABLE statement for Big_Cities:
ya e
( mysql> SHOW CREATE TABLE Big_Cities\G
*************************** 1. row **********************
Table: Big_Cities
Create Table: CREATE TABLE `big_cities` (
`ID` int(11) NOT NULL DEFAULT '0',
`name` char(35) NOT NULL DEFAULT '',
`population` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`),
KEY `Pop` (`population`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.03 sec)
11. Remove the index on the Population column.
a. Compare your statement and results to those shown below:
mysql> ALTER TABLE Big_Cities DROP INDEX Pop;
Query OK, 0 rows affected (0.16 sec)
Records: 0 Duplicates: 0 Warnings: 0
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 20
b. Confirm the change:
mysql> DESC Big_Cities;
+------------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | | |
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| name | char(35) | NO | | | |
| population | int(11) | NO | | 0 | |
+------------+----------+------+-----+---------+-------+
3 rows in set (0.02 sec)
− The Key attribute for the population column is empty.
c. Display the CREATE TABLE statement for Big_Cities:
mysql> SHOW CREATE TABLE Big_Cities\G
*************************** 1. row **********************
Table: Big_Cities
Create Table: CREATE TABLE `big_cities` (
`ID` int(11) NOT NULL DEFAULT '0',
to
`name` char(35) NOT NULL DEFAULT '',
`population` int(11) NOT NULL DEFAULT '0', A 1n ense
PRIMARY KEY (`ID`),
C 3% le lic
) ENGINE=InnoDB DEFAULT CHARSET=latin1
n c l% erab
0I ansf
1 row in set (0.03 sec)
− The Pop key index has gone. 2
12. Remove the Big_Cities table. i l l a% on-tr
d shown
btoathose a n below:
a. Compare your statement and results
B o s d e ฺ
mysql> DROP TABLE Big_Cities; ra (0.13 a
h Gu
) sec) i
a n d m x n t
l e j
Query OK, 0 rows affected
y ฺ e
b. View the list of A
2 S tud database to confirm:
0 tablesoinฺutheadworld_innodb
mysql>
e l % r r e
SHOW TABLES;
t h is
Y a co use |
+------------------------+
@
lla
| Tables_in_world_innodb
d i
+------------------------+

b o ba|| city |

e l ฺ country |

( ya | country2
| countrylanguage |
|

| gelderlanddist |
+------------------------+
5 rows in set (0.01 sec)
− The Big_Cities table has gone.
13. Exit the mysql client.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 21
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Database and Table Maintenance


Chapter 8 - Page 22
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
Practices for n c l% era9:b Table
Lesson
2 0I ansf
DataaManipulation
% n-tr
i l l
d 9a no
b a
B
Chapter
o as i d eฺ
n d ra x) h t Gu
l e ja dyฺm den
2 0A oฺua s Stu
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 1
Practices for Lesson 9: Overview
Practices Overview
These practices test your knowledge of table data manipulation. They target the Windows
operating system, provided in Oracle classrooms. For non-Oracle classrooms, you may need to
adjust file locations.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Assumptions
• You have installed and configured MySQL Server.
• You have created and populated the world_innodb database.
• You can access the mysql client from a command-line prompt.
Note: In this practice the first letters of table names are in uppercase. Windows is not case-
sensitive but some operating systems are, so it is good practice to use proper capitalization.
The SQL statements are all in uppercase for clarity, but this is not required.
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 2
Practice 9-1: Inserting and Replacing Table Row Data
Overview
In this practice, you add new records to a table and replace existing records.

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

This practice takes approximately 15 minutes to complete.

Tasks
1. Use an INSERT INTO statement to add a single row to the GelderlandDist table. The
new row includes the city name Sakila, with a district of Gelderland, country code of SQL,
and an inauguration date of July 01, 2001.
Hint: Use the date format: YYYY-MM-DD. Enclose column values within single quotation
marks.
2. List the contents of the GelderlandDist table to confirm that the new row is in the table.
to
3. Insert two more rows into the GelderlandDist table:
A 1n ense
− Row 1: The city name MySQLland, with a country code of MYS,3and % inauguration
e l ic
date of August 04, 1984
l C
% rabl
c e
− Row 2: The city name Fantasia, with country code of
January 1, 1950 2 0InFNT,anandsfinauguration date of

Both cities are in the Gelderland district. i l l a% on-tr


d to confirm
batable a n thatฺ the new rows are there.
4. List the contents of the GelderlandDist o
B htheasMySQLland iderecord, so that it is in the same
5. Use a REPLACE INTO statement r ato replace ) u
country as Sakila.
j a nd yฺmx ent G
Hint: Save yourselfA le typing.
some adUse S thetu d key (↑) to retrieve the last INSERT
up-arrow
2 0 ฺ u
INTO statement.
e l % Change
r r eoINSERT t h itos REPLACE and provide the new values.
List theacontentscofothe GelderlandDist
6.
Y @ u se table to verify the change.
Note: Keep
d i llayour mysql session open for the next practice.
l ฺb oba
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 3
Solutions 9-1: Inserting and Replacing Table Row Data
Tasks
1. Use an INSERT INTO statement to add a single row to the GelderlandDist table. The
new row includes the city name Sakila, with a district of Gelderland, country code of SQL,
and an inauguration date of July 01, 2001.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

a. Log in to the mysql client program:


cmd> mysql -u root -p
Enter password: oracle
...
b. Compare your statements and results to those shown below:
mysql> USE world_innodb
Database changed

to
mysql> INSERT INTO GelderlandDist (Name, District, CountryCode,
Inauguration) A 1n ense
-> VALUES ('Sakila', 'Gelderland', 'SQL', '2001-07-01'); C 3% le lic
Query OK, 1 row affected (0.09 sec)
n c l% erab
0I ansf
− The result shows that the operation affects a single row.
2
i l l a% on-tr
2. List the contents of the GelderlandDist table to confirm that the new row is in the table:

bad s a n eฺ
Compare your statement and results to those shown below:
o
a B ha
mysql> SELECT * FROM GelderlandDist;
r uid
d
n y|ฺm x ) G
t | Inauguration |
+-----------+------------+-------------+--------------+
| Name
e j a
| District
l e n
CountryCode

2 0A ฺ u ad | NLD
S tud
+-----------+------------+-------------+--------------+
| Apeldoorn
l % r e o his| NLD
| Gelderland | 0000-00-00 |

| a
e co|r Gelderland
| Arnhem | Gelderland
e t | NLD | 0000-00-00 |
Y Ede
@ u s | 0000-00-00 |

|d i ll a
| Nijmegen | Gelderland | NLD | 0000-00-00 |

o b a Sakila | Gelderland | SQL | 2001-07-01


+-----------+------------+-------------+--------------+
|

e l ฺb 5 rows in set (0.00 sec)


( ya − Returns a list of all rows and columns in the table including the new record
3. Insert two more rows into the GelderlandDist table:
− Row 1: The city name MySQLland, with a country code of MYS, and inauguration
date of August 04, 1984
− Row 2: The city name Fantasia, with country code of FNT, and inauguration date of
January 1, 1950
Compare your statement and results to those shown below:
mysql> INSERT INTO GelderlandDist (Name, District, CountryCode,
Inauguration)
-> VALUES ('MySQLland', 'Gelderland', 'MYS', '1984-08-04'),
-> ('Fantasia', 'Gelderland', 'FNT', '1950-01-01');
Query OK, 2 rows affected (0.02 sec)
Records: 2 Duplicates: 0 Warnings: 0

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 4
4. List the contents of the GelderlandDist table to confirm that the new rows are there.
Compare your statement and results to those shown below:
mysql> SELECT * FROM GelderlandDist;
+-----------+------------+-------------+--------------+
| Name | District | CountryCode | Inauguration |
+-----------+------------+-------------+--------------+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| Apeldoorn | Gelderland | NLD | 0000-00-00 |


| Arnhem | Gelderland | NLD | 0000-00-00 |
| Ede | Gelderland | NLD | 0000-00-00 |
| Fantasia | Gelderland | FNT | 1950-01-01 |
| MySQLland | Gelderland | MYS | 1984-08-04 |
| Nijmegen | Gelderland | NLD | 0000-00-00 |
| Sakila | Gelderland | SQL | 2001-07-01 |
+-----------+------------+-------------+--------------+
7 rows in set (0.30 sec)
− Returns a list of all rows and columns in the table including the new records
5. Use a REPLACE INTO statement to replace the MySQLland record, so that it is in the same
to
country as Sakila.
Compare your statement and results to those shown below: A 1n ense
mysql> REPLACE INTO GelderlandDist (Name, District, C 3% le lic
l% erab
CountryCode,
Inauguration)
n c
-> VALUES ('MySQLland', 'Gelderland', 'SQL',
2 n sf
0I a'1984-08-04');
Query OK, 2 rows affected (0.08 sec) %
i l l a n - tr
b a d aevennothose that are unchanged.
− You need to provide values for all columns,
6. List the contents of the GelderlandDist B o tableasto verify ithe
d ฺ
echange.
Compare your statement d and h shown
raresultsxto) those G u below:
mysql> SELECTle*ja
n ฺm den t
d y
FROM GelderlandDist;
0A oฺua s| CountryCodeS tu
| Name%2 | District
+-----------+------------+-------------+--------------+

e l r r e t h i | Inauguration |
a
| Apeldoorn @ co| Gelderland
u se | NLD
+-----------+------------+-------------+--------------+
Y | 0000-00-00 |
i l l a
|d
| Arnhem | Gelderland | NLD | 0000-00-00 |
a
ob | Fantasia | Gelderland | FNT
Ede | Gelderland | NLD | 0000-00-00 |

e l ฺb | 1950-01-01 |

ya
| MySQLland | Gelderland | SQL | 1984-08-04 |
( | Nijmegen | Gelderland | NLD
| Sakila | Gelderland | SQL
| 0000-00-00
| 2001-07-01
|
|
+-----------+------------+-------------+--------------+
7 rows in set (0.30 sec)
− Returns a list of all rows and columns in the table and shows MySQLland in the
country “SQL”
Note: Keep your mysql session open to use in the next practice.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 5
Practice 9-2: Modifying and Deleting Table Row Data
Overview
In this practice, you modify and delete records from the GelderlandDist table.

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

This practice takes approximately 15 minutes to complete.

Tasks
1. Use an UPDATE statement on the GelderlandDist table to set the inauguration date for
the city named Ede to May 17, 1880.
Hint: Use the date format: YYYY-MM-DD. Enclose column values within single quotation
marks.
2. List the contents of the GelderlandDist table to verify the change.
3. Update the GelderlandDist table so that the first two cities with a country code of NLD
to
(when ordered alphabetically by Name) use the code FOO instead.
A 1n ense
4. List the contents of the GelderlandDist table to verify the change.
C 3% le lic
5. Issue a DELETE statement to remove a single row from the GelderlandDist
c l % r a b table, with a
country code of FOO.
2 0 In nsfe
6. List the contents of the GelderlandDist table to verify
i l l a tra
% then-change.
7. d codeaFOO.
List all cities in the City table with the country
b a no ฺ
8. Try to delete one row from the City table
B o withathes countryidcode
e FOO.
a
dr mx) nt G h u
a n
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
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 6
Solutions 9-2: Modifying and Deleting Table Row Data
Tasks
1. Use an UPDATE statement on the GelderlandDist table to set the inauguration date for
the city named Ede to May 17, 1880.
Compare your statement and results to those shown below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> UPDATE GelderlandDist


-> SET Inauguration = '1880-05-17'
-> WHERE Name = 'Ede';
Query OK, 1 row affected (0.14 sec)
Rows matched: 1 Changed: 1 Warnings: 0
2. List the contents of the GelderlandDist table to verify the change.
Compare your statement and results to those shown below:
mysql> SELECT * FROM GelderlandDist;
to
1n ense
+-----------+------------+-------------+--------------+
| Name | District | CountryCode | Inauguration |
A
+-----------+------------+-------------+--------------+
C 3% le lic
l% erab
| Apeldoorn | Gelderland | NLD | 0000-00-00 |
| Arnhem | Gelderland | NLD | 0000-00-00
n
| c
| Ede | Gelderland | NLD 0I ansf
| 1880-05-17
2 |
| Fantasia | Gelderland | FNT
| MySQLland | Gelderland | SQL i l a% on-tr
| 1950-01-01
l
| 1984-08-04
|
|
| Nijmegen | Gelderland | NLD
o bad s a n eฺ
| 0000-00-00 |
| Sakila
r a B ha
| Gelderland | SQL
uid
| 2001-07-01 |

d
n yฺm ent x ) G
+-----------+------------+-------------+--------------+

e j a
7 rows in set (0.00 sec)
3. Al ฺuatable
Update the GelderlandDist
2 0 d so that
S t udthe first two cities with a country code of NLD
% rreo bythName)
(when ordered alphabetically
e l is use the code FOO instead.
Y a your
Compare
@ costatement
u s eand results to those shown below:
i lla UPDATE GelderlandDist
mysql>
d
l ฺb oba -> SET CountryCode = 'FOO'
-> WHERE CountryCode = 'NLD'
ya e
( -> ORDER BY Name
-> LIMIT 2;
Query OK, 2 rows affected (0.06 sec)
Rows matched: 2 Changed: 2 Warnings: 0

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 7
4. List the contents of the GelderlandDist table to verify the change.
Compare your statement and results to those shown below:
mysql> SELECT * FROM GelderlandDist;
+-----------+------------+-------------+--------------+
| Name | District | CountryCode | Inauguration |
+-----------+------------+-------------+--------------+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| Apeldoorn | Gelderland | FOO | 0000-00-00 |


| Arnhem | Gelderland | FOO | 0000-00-00 |
| Ede | Gelderland | NLD | 1880-05-17 |
| Fantasia | Gelderland | FNT | 1950-01-01 |
| MySQLland | Gelderland | SQL | 1984-08-04 |
| Nijmegen | Gelderland | NLD | 0000-00-00 |
| Sakila | Gelderland | SQL | 2001-07-01 |
+-----------+------------+-------------+--------------+
7 rows in set (0.00 sec)
− The updated rows are at the top of the table, due to the default alphabetical
ordering.
to
5.
1n ense
Issue a DELETE statement to remove a single row from the GelderlandDist table, with a
country code of FOO. A
Compare your statement and results to those shown below: C 3% le lic
mysql> DELETE FROM GelderlandDist
n c l% erab
-> WHERE CountryCode = 'FOO' 2 0I ansf
-> LIMIT 1; i l l a% on-tr
Query OK, 1 row affected (0.02
o badsec) a n ฺ
6. a
List the contents of the GelderlandDist
r B table h dechange.
asto verifyuithe
ndand yresults )
xto those t G
Compare your statementj a ฺ m n shown below:
0 A t de
le* FROMadGelderlandDist;
u
mysql> SELECT
2 eoฺ u s S
l % i
+-----------+------------+-------------+--------------+
r h
ae co|r District
| Name
Y s e t | CountryCode | Inauguration |
u
a@ | Gelderland
+-----------+------------+-------------+--------------+
l l
d i
| Arnhem | FOO | 0000-00-00 |

oba| Fantasia | Gelderland | FNT


| Ede | Gelderland | NLD | 1880-05-17 |

e l ฺb | 1950-01-01 |

ya
| MySQLland | Gelderland | SQL | 1984-08-04 |
( | Nijmegen | Gelderland | NLD
| Sakila | Gelderland | SQL
| 0000-00-00
| 2001-07-01
|
|
+-----------+------------+-------------+--------------+
6 rows in set (0.00 sec)
− The first record (Apeldoorn) has been deleted.
7. List all cities in the City table with the country code FOO.
Compare your statement and results to those shown below:
mysql> SELECT * FROM City WHERE CountryCode = 'FOO';
Empty set (0.05 sec)
− There are no rows in the City table with a country code of FOO.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 8
8. Try to delete one row from the City table with the country code FOO.
Compare your statement and results to those shown below:
mysql> DELETE FROM City
-> WHERE CountryCode = 'FOO'
-> LIMIT 1;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Query OK, 0 rows affected (0.02 sec)


− There are no records with a country code of FOO, so the DELETE does not affect
any 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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 9
Practice 9-3: Manipulating Table Row Data in the Pets Database

Overview
In this practice, you make the following changes to the data in the Pets database:
• Add table row data.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

• Replace current table row data.


• Modify table row data.
• Delete table rows.

Duration
This practice takes approximately 40 minutes to complete.

Tasks
1. Change the current database to Pets.
to
2.
3.
List all records in the pet_info table.
Using the pet information chart below: A 1n ense
a. Insert the ten remaining records into the pet_info table C 3% le lic
n c l% erab
− Use the correct column name and order.
0 I n s f
− Not every pet (row) has values for all columns. 2
%UsenNULLtrafor these columns.
i l l a -
data for Fang in the fourth row.oba a no ฺ practice. Start with the
− You added data for Fluffy, Claws, anddBuffy in a previous

r a B pBday
) h as pDday u ide
pID* pName
a n d mx nt G
pGender oID** tID***
1 Fluffy
A lej F adyฺ 2003-02-04
t u de NULL 1 1
2 Claws0 u
2 eoฺM is S2004-03-17 NULL 2 1
l %
e cor Fe t r h
3 Ya Buffy @ u s 1999-05-13 NULL 1 2
4
d i llaFang M 2000-08-27 NULL 3 2
5ob
a Bowser M 1989-08-31 2009-07-29 4 2
e l ฺ b
(ya 6 Chirpy F 2008-09-11 NULL 2 3
7 Whistler NULL 2007-12-09 NULL 2 4
8 Slim M 2006-04-29 NULL 3 5
9 Puffball F 2009-03-30 NULL 4 1
10 Opus M NULL NULL 5 1
11 Rocky M 1998-04-04 2013-02-11 6 1
12 Koko M 1997-02-08 NULL 3 1
13 Scruffy M 2008-04-17 NULL 2 1
b. List the contents of the pet_info table to confirm the changes.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 10
4. Using the owner information chart below:
a. Insert the records into the owners table
oID* oName oPhone
1 Harold 15554159855
2 Gwen 15551234567
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

3 Benny 15553456789
4 Diane 15554567890
5 Caryn 15554444444
6 Chris 15556666666
b. List the contents of the owners table to confirm the changes.
5. Using the pet type information chart below:
a. Insert the rows into the pet_types table
to
tID* pType
A 1n ense pCategory
1 Cat % e lic
3Mammal
l C
% Mammal bl
2 Dog c r a
2 0In ansfe
3 Parrot
l a % - t r Bird
4 Canary
a d il non Bird
b
oSnake as a ฺ
5
r a B
) h u ide Reptile
6
a x nt G
nd yฺmHamster Mammal
l e j e
7
2 0A oฺuad s SFerret tud Mammal
b. List thel%
a e contents
o r e t hi table to confirm the changes
rofethe pet_types
6. Update
@ c detailsuinsthe pet_info table:
Y Whistler’s
a
ll gender to male.
ithe
d
a. Set
a
l ob.b Review the table data to confirm the change.
ฺb Benny’s snake, Slim, is actually an iguana. You must correct this. The update affects two
ya e7.
( tables: pet_info and pet_types:
a. Add an Iguana record to the pet_types table, which belongs to the Reptile category.
Note: Do not attempt to include foreign keys at this time. You add foreign keys to the
Pets database in a later lesson.
b. Modify the pet_info table to use Slim’s new tID.
c. Confirm the changes to both tables.
8. Harold has given Buffy the dog to Benny. Make the necessary changes to the database.
a. Update the pet_info table to assign Buffy to Benny.
Hint: Check the owners table first to confirm the owner IDs.
b. Confirm the change.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 11
9. Two of the owners, Caryn and Chris, marry and share a new phone number: 16163429988.
a. Update Chris and Caryn’s records in the owners table with the new number.
Hint: Use a WHERE...IN statement to include both owner names in the update.
b. Confirm the changes.
10. All the animals born before 2000 are no longer patients. Remove them from the database.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

a. Delete all the animals from the pet_info table that were born before 2000.
b. Confirm the change.
11. After removing the pets in the previous step, there is an owner without any pets.
a. Determine who the owner is and delete that person’s record from the owners table.
b. Confirm the change.
12. Diane has moved and is not bringing her hamster Puffball to the clinic anymore. The clinic
wants to reuse her ID number for a new client. Make the necessary changes to the
database.
a. Use REPLACE INTO to delete Puffball’s record and replace it with the new pet’s
to
details:
− The new pet is a female hamster named Chewy, owned by Olga. A 1n ense
− Specify Puffball’s ID in the statement. C 3% le lic
− Use the next available number for the owner ID. n c l% erab
0I table.n s f
2
a% on-tra
− Get the correct type ID for this pet from the pet_types
i l l
badHersphone
b. Confirm the change.
13. Add the new owner Olga to the ownersotable. a n numberฺ is 18563330000. You
B a i d e
must specify the owner ID.
n d ra x) h t Gu
14. Exit the mysql client.
l e ja dyฺm den
0A odatabase
Note: You use the Pets
2 ฺ ua sin future
S tu practices, so do not make any further changes
el% corre e thi
to the tables.
Y @a
l l a us
b a di
l ฺ b o
( yae

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 12
Solutions Practice 9-3: Manipulating Table Row Data in the Pets
Database
Tasks
1. Change the current database to Pets.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Compare your statement and results to those shown below:


mysql> USE pets
Database changed
2. List all the records in the pet_info table. Compare your statement and results to those
shown below:
mysql> SELECT * FROM pet_info;
+-----+--------+---------+------------+-------+-----+-----+
| pID | pName | pGender | pBday | pDday | oID | tID |
o
n nse t
+-----+--------+---------+------------+-------+-----+-----+
1
%A e lice
| 1 | Fluffy | F | 2003-02-04 | NULL | 1 | 1 |
| 2 | Claws | M | 2004-03-17 | NULL | 2 |3
C bl 1 |
| 3 | Buffy | F | 1999-05-13 | NULL |
c l %1 |
ra 2 |
I n s f e
20 tran
+-----+--------+---------+------------+-------+-----+-----+
%
3 rows in set (0.09 sec)
d i lla non-
obthea pet_info
3. Using the pet information chart:
a. Insert the ten remaining recordsB s a table.eฺCompare your statement
into
a x) h Gu
rbelow: a i d
n d
and results to those shown
m (pName, n t pGender, pBday, pDday, oID, tID)
mysql> INSERTle ja pet_infoy ฺ e
0A oฺuad s Stud
INTO
2
-> VALUES

a o r re
e t hi
e->l%('Fang','M','2000-08-27',NULL,3,2),
Y ->@ c us
('Bowser','M','1989-08-31','2009-07-29',4,2),
a
ill-> ('Chirpy','F','2008-09-11',NULL,2,3),
a d
l ฺb ob -> ('Whistler',NULL,'2007-12-09',NULL,2,4),
ya e -> ('Slim','M','2006-04-29',NULL,3,5),
( -> ('Puffball','F','2009-03-30',NULL,4,1),
-> ('Opus','F',NULL,NULL,5,1),
-> ('Rocky','M','1998-04-04','2013-02-11',6,1),
-> ('Koko','M','1997-02-08',NULL,3,1),
-> ('Scruffy','M','2008-04-17',NULL,2,1);
Query OK, 10 rows affected (0.09 sec)
Records: 10 Duplicates: 0 Warnings: 0
− Note that AUTO_INCREMENT assigns the pID automatically.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 13
b. List the contents of the pet_info table to confirm the changes. Compare your
statement and results to those shown below:
mysql> SELECT * FROM pet_info;
+-----+----------+---------+------------+------------+-----+-----+
| pID | pName | pGender | pBday | pDday | oID | tID |
+-----+----------+---------+------------+------------+-----+-----+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| 1 | Fluffy | F | 2003-02-04 | NULL | 1 | 1 |


| 2 | Claws | M | 2004-03-17 | NULL | 2 | 1 |
| 3 | Buffy | F | 1999-05-13 | NULL | 1 | 2 |
| 4 | Fang | M | 2000-08-27 | NULL | 3 | 2 |
| 5 | Bowser | M | 1989-08-31 | 2009-07-29 | 4 | 2 |
| 6 | Chirpy | F | 2008-09-11 | NULL | 2 | 3 |
| 7 | Whistler | NULL | 2007-12-09 | NULL | 2 | 4 |
| 8 | Slim | M | 2006-04-29 | NULL | 3 | 5 |
| 9 | Puffball | F | 2009-03-30 | NULL | 4 | 1 |
| 10 | Opus | F | NULL | NULL | 5 | 1 |
| 11 | Rocky | M | 1998-04-04 | 2013-02-11 | 6 | 1 |

to
| 12 | Koko | M | 1997-02-08 | NULL | 3 | 1 |

1n ense
| 13 | Scruffy | M | 2008-04-17 | NULL | 2 | 1 |
+-----+----------+---------+------------+------------+-----+-----+
A
13 rows in set (0.00 sec)
C 3% le lic
4. Using the owner information chart:
n c l% erab
a. Insert the records into the owners table. Compare your0 I statement
n s fand results to those
shown below: 2
% n-tra
i l l a
mysql> INSERT INTO owners (oName,
b a d oPhone)
a no ฺ
-> VALUES
B o as ide
r a ) h u
nd yฺmx ent G
-> ('Harold', '15554159855'),
-> ('Gwen',ja
A le '15553456789'),
'15551234567'),
ad Stud
2 0
-> ('Benny', ฺ u
e l
-> %('Diane',
r r eo '15554567890'),
t h is
Ya ->@ co us'15554444444'),
('Caryn', e
i a ('Chris', '15556666666');
ll->
d
l ฺb obaQuery OK, 6 rows affected (0.02 sec)
ya e Records: 6 Duplicates: 0 Warnings: 0
( b. List the contents of the owners table to confirm the changes. Compare your statement
and results to those shown below:
mysql> SELECT * FROM owners;
+-----+--------+-------------+
| oID | oName | oPhone |
+-----+--------+-------------+
| 1 | Harold | 15554159855 |
| 2 | Gwen | 15551234567 |
| 3 | Benny | 15553456789 |
| 4 | Diane | 15554567890 |
| 5 | Caryn | 15554444444 |
| 6 | Chris | 15556666666 |
+-----+--------+-------------+
6 rows in set (0.00 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 14
5. Using the pet type information chart:
a. Insert the rows into the pet_types table. Compare your statement and results to
those shown below:
mysql> INSERT INTO pet_types (pType, pCategory)
-> VALUES
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-> ('Cat', 'Mammal'),


-> ('Dog', 'Mammal'),
-> ('Parrot', 'Bird'),
-> ('Canary', 'Bird'),
-> ('Snake', 'Reptile'),
-> ('Hamster', 'Mammal'),
-> ('Ferret', 'Mammal');
Query OK, 7 rows affected (0.01 sec)
Records: 7 Duplicates: 0 Warnings:
to
b.
1n ense
List the contents of the pet_types table to confirm the changes. Compare your
statement and results to those shown below: A
C 3% le lic
l% erab
mysql> SELECT * FROM pet_types;
+-----+---------+-----------+
I n c f
| tID | pType | pCategory |
2 0 n s
+-----+---------+-----------+
i l l a% on-tra
| ad
| 1 | Cat | Mammal |
| 2 | Dog | Mammal
o b s a n eฺ
| 3 | Parrot | Bird
4 | Canary | Birdra
B | ha
|
uid
|
d
n yฺm| ent x ) G
|
|
5 | Snake
6 | Hamster e j a
| Reptile
l | Mammal
| d || tud
Mammal
| 0 A
2 eoฺ
7 | Ferret u a S
l % r
+-----+---------+-----------+
h i s
7 a
Y rowse in cset or (0.00sesec)
t
6. l a@ detailsuin the pet_info table:
Update Whistler’s
i l
d
l ฺb oa.baSet the gender to male. Compare your statement and results to those shown below:
ya e mysql> UPDATE pet_info
( -> SET pGender = 'M'
-> WHERE pName = 'Whistler';
Query OK, 1 row affected (0.06 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 15
b. Review the table data to confirm the change. Compare your statement and results to
those shown below:
mysql> SELECT * FROM pet_info;
+-----+----------+---------+------------+------------+-----+-----+
| pID | pName | pGender | pBday | pDday | oID | tID |
+-----+----------+---------+------------+------------+-----+-----+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| 1 | Fluffy | F | 2003-02-04 | NULL | 1 | 1 |


| 2 | Claws | M | 2004-03-17 | NULL | 2 | 1 |
| 3 | Buffy | F | 1999-05-13 | NULL | 1 | 2 |
| 4 | Fang | M | 2000-08-27 | NULL | 3 | 2 |
| 5 | Bowser | M | 1989-08-31 | 2009-07-29 | 4 | 2 |
| 6 | Chirpy | F | 2008-09-11 | NULL | 2 | 3 |
| 7 | Whistler | M | 2007-12-09 | NULL | 2 | 4 |
| 8 | Slim | M | 2006-04-29 | NULL | 3 | 5 |

to
| 9 | Puffball | F | 2009-03-30 | NULL | 4 | 1 |
| 10 | Opus | F | NULL | NULL | 5 | 1 |
A 1n ense
3% le lic
| 11 | Rocky | M | 1998-04-04 | 2013-02-11 | 6 | 1 |
| 12 | Koko | M | 1997-02-08 | NULL | 3 | 1 | C
l% erab
| 13 | Scruffy | M | 2008-04-17 | NULL | 2 |
n
1 | c
2 0I ansf
+-----+----------+---------+------------+------------+-----+-----+
13 rows in set (0.00 sec)
i l l a% on-tr
7. Benny’s snake, Slim, is actually an iguana. b d musta correct
aYou n this. The update affects two
tables: pet_info and pet_types.B o s e ฺ
a. Add an Iguana record to d
ther apet_types
x ) a
htable, G uidbelongs to the Reptile category.
which
j a n and yresults
ฺ m e n tshown below:
l e
Compare your statement
d to those
tud(pType, pCategory)
2
mysql> INSERT 0A INTO ฺ u apet_types
o his 'Reptile');S
e l %VALUESrre('Iguana', t
Y a ->
c orow affected
s e
Query OK,
l l a @ 1 u (0.03 sec)

b a di database
Note:
Pets
Do not attempt to include foreign keys at this time. You add foreign keys to the
in a later lesson.
l o
ฺb b.
ya e Modify the pet_info table to use Slim’s new tID. Compare your statement and
( results to those shown below:
mysql> UPDATE pet_info
-> SET tID = 8
-> WHERE pName = 'Slim';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 16
c. Confirm the changes to both tables. Compare your statement and results to those
shown below:
mysql> SELECT * FROM pet_info;
+-----+----------+---------+------------+------------+-----+-----+
| pID | pName | pGender | pBday | pDday | oID | tID |
+-----+----------+---------+------------+------------+-----+-----+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| 1 | Fluffy | F | 2003-02-04 | NULL | 1 | 1 |


| 2 | Claws | M | 2004-03-17 | NULL | 2 | 1 |
| 3 | Buffy | F | 1999-05-13 | NULL | 1 | 2 |
| 4 | Fang | M | 2000-08-27 | NULL | 3 | 2 |
| 5 | Bowser | M | 1989-08-31 | 2009-07-29 | 4 | 2 |
| 6 | Chirpy | F | 2008-09-11 | NULL | 2 | 3 |
| 7 | Whistler | M | 2007-12-09 | NULL | 2 | 4 |
| 8 | Slim | M | 2006-04-29 | NULL | 3 | 8 |

to
| 9 | Puffball | F | 2009-03-30 | NULL | 4 | 1 |
| 10 | Opus | F | NULL | NULL | 5 | 1 |
A 1n ense
3% le lic
| 11 | Rocky | M | 1998-04-04 | 2013-02-11 | 6 | 1 |
| 12 | Koko | M | 1997-02-08 | NULL | C
3 |
l% erab
1 |
| 13 | Scruffy | M | 2008-04-17 | NULL
n|c 2 | 1 |
2 0I ansf
+-----+----------+---------+------------+------------+-----+-----+
13 rows in set (0.00 sec)
i l l a% on-tr
8. ad the anecessary
Harold has given Buffy the dog to Benny.bMake
o
n ฺchanges to the database.
B Buffy
a. Update the pet_info table to assign asto Benny. e
idCompare your statements and
d
results to those shown below:r a x ) h G u
an owners;
mysql> SELECTle*j FROM d yฺm dent
2 0A oฺua s Stu
+-----+--------+-------------+
| oID l%
a e | oName o r re| oPhonethi |
Y c se
+-----+--------+-------------+
1 |@ Harold |u15554159855
| il2la| Gwen
| |
d | 15551234567 |

l ฺb oba| 3 | Benny | 15553456789 |


...
ya e +-----+--------+-------------+
(
mysql> UPDATE pet_info SET oID = 3
-> WHERE oID = 1 AND pName = 'Buffy';
Query OK, 1 row affected (4.16 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 17
b. Confirm the change. Compare your statement and results to those shown below:
mysql> SELECT * FROM pet_info;
+-----+----------+---------+------------+------------+-----+-----+
| pID | pName | pGender | pBday | pDday | oID | tID |
+-----+----------+---------+------------+------------+-----+-----+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| 1 | Fluffy | F | 2003-02-04 | NULL | 1 | 1 |


| 2 | Claws | M | 2004-03-17 | NULL | 2 | 1 |
| 3 | Buffy | F | 1999-05-13 | NULL | 3 | 2 |
. . .
13 rows in set (0.00 sec)
9. Two of the owners, Caryn and Chris, marry and share a new phone number: 16163429988.
a. Update Chris and Caryn’s records in the owners table with the new number. Compare
your statement and results to those shown below:
mysql> UPDATE owners
-> SET oPhone = '16163429988' to
-> WHERE oName IN ('Caryn', 'Chris');
A 1n ense
Query OK, 2 rows affected (0.13 sec)
3 % e lic
Rows matched: 2 Changed: 2 Warnings: 0
l C
% rabl
c
b. Confirm the changes. Compare your statement and results
2 sfeshown below:
0In toanthose
mysql> SELECT * FROM owners;
l l a % n-tr
i
d a no
|ba
+-----+--------+-------------+
| oID | oName | oPhone
B o as i d eฺ
ra x| ) h t Gu
+-----+--------+-------------+
| d
1 | Harold | 15554159855
n
| 2 | Gwen
l
| ja
e yฺm || den
15551234567
d
|
|
3 | Benny
2
4 | Diane
|
ua s S|tu
0A | o15554567890
15553456789

|
a
| Carynrre
e56 l% o t hi ||
| 16163429988
e
Y
| |
@ c us
Chris | 16163429988
a
ill in set (0.02 sec)
+-----+--------+-------------+
6d
ob a rows

e l ฺb
10. All the animals born before 2000 are no longer patients. Remove them from the database.

( ya a. Delete all the animals from the pet_info table that were born before 2000. Compare
your statement and results to those shown below:
mysql> DELETE FROM pet_info
-> WHERE pBday < '2000-01-01';
Query OK, 4 rows affected (0.05 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 18
b. Confirm the change. Compare your statement and results to those shown below:
mysql> SELECT * FROM pet_info;
+-----+----------+---------+------------+-------+-----+-----+
| pID | pName | pGender | pBday | pDday | oID | tID |
+-----+----------+---------+------------+-------+-----+-----+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| 1 | Fluffy | F | 2003-02-04 | NULL | 1 | 1 |


| 2 | Claws | M | 2004-03-17 | NULL | 2 | 1 |
| 4 | Fang | M | 2000-08-27 | NULL | 3 | 2 |
| 6 | Chirpy | F | 2008-09-11 | NULL | 2 | 3 |
| 7 | Whistler | M | 2007-12-09 | NULL | 2 | 4 |
| 8 | Slim | M | 2006-04-29 | NULL | 3 | 8 |
| 9 | Puffball | F | 2009-03-30 | NULL | 4 | 1 |
| 10 | Opus | F | NULL | NULL | 5 | 1 |
| 13 | Scruffy | M | 2008-04-17 | NULL | 2 | 1 |
+-----+----------+---------+------------+-------+-----+-----+
n nse to
9 rows in set (0.00 sec)
A 1
− Note that there are now only nine rows, as opposed to the original%
3 13.
l i ce
11. After removing the pets in the previous step, there is an owner without
l % a b le
C any pets.
I nc fromsthe
a. Determine who the owner is and delete that person’s record
0 f erowners table.
Compare your statements and results to those shown
a % 2 below:
- t r an
mysql> SELECT DISTINCT oID FROM ilpet_info;
d l on
a n
+-----+
| oID | B ob as a ideฺ
+-----+
n d ra x) h t Gu
| 1 |
l e ja dyฺm den
0A oฺua s Stu
| 2 |
| 3 |
2
| ae
| 4 l%
|
o r re
e t hi
Y 5 |
+-----+@
c us
a
ill in set (0.09 sec)
d
5 rows
a
l ฺ b ob
yae
mysql> SELECT * FROM owners;
( +-----+--------+-------------+
| oID | oName | oPhone |
+-----+--------+-------------+
| 1 | Harold | 15554159855 |
| 2 | Gwen | 15551234567 |
| 3 | Benny | 15553456789 |
| 4 | Diane | 15554567890 |
| 5 | Caryn | 16163429988 |
| 6 | Chris | 16163429988 |
+-----+--------+-------------+
6 rows in set (0.00 sec)

mysql> DELETE FROM owners


-> WHERE oID = 6;
Query OK, 1 row affected (0.05 sec)
− The oID number 6 (Chris) is missing from the pet_info table.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 19
b. Confirm the change. Compare your statement and results to those shown below:
mysql> SELECT * FROM owners;
+-----+--------+-------------+
| oID | oName | oPhone |
+-----+--------+-------------+
| 1 | Harold | 15554159855 |
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| 2 | Gwen | 15551234567 |
| 3 | Benny | 15553456789 |
| 4 | Diane | 15554567890 |
| 5 | Caryn | 16163429988 |
+-----+--------+-------------+
5 rows in set (0.00 sec)
12. Diane has moved and is not bringing her hamster Puffball to the clinic any more. The clinic
wants to reuse her ID number for a new client. Make the necessary changes to the
database.
a. Use REPLACE INTO to delete Puffball’s record and replace it with the new pet’s
details. Compare your statement and results to those shown below:
to
mysql> REPLACE INTO pet_info (pID, pName, pGender, pBday, pDday,
A 1n ense
oID, tID)
C 3% le lic
-> VALUES (9,'Chewy','F', NULL, NULL,6,6);
n c l% erab
sf shown below:
Query OK, 2 rows affected (0.03 sec)
b. Confirm the change. Compare your statement and2 0I toathose
results n
i l l a% on-tr
bad s a n eฺ
mysql> SELECT * FROM pet_info;

o
+-----+----------+---------+------------+-------+-----+-----+
B| pBday id | oID | tID |
| pID | pName
r a
| pGender
d x ) ha G|upDday
jan ฺm dent | NULL | 1 | 1 |
+-----+----------+---------+------------+-------+-----+-----+
1 | Fluffyle | F dy | 2003-02-04
|
2 tu
0A o| ฺuM a s |S2004-03-17
| 2 | Claws
l % r e h i | NULL | 2 | 1 |
|
Y ae46 || Fangc or ||sMFe t || 2000-08-27 | NULL | 3 | 2 |
|
l l a @Chirpy u 2008-09-11 | NULL | 2 | 3 |
| di 7 | Whistler | M | 2007-12-09 | NULL | 2 | 4 |
o b a
| 8 | Slim | M | 2006-04-29 | NULL | 3 | 8 |
e l ฺb
ya
| 9 | Chewy | F | NULL | NULL | 6 | 6 |
( | 10 | Opus | F | NULL | NULL | 5 | 1 |
| 13 | Scruffy | M | 2008-04-17 | NULL | 2 | 1 |
+-----+----------+---------+------------+-------+-----+-----+
9 rows in set (0.00 sec)
13. Add the new owner Olga to the owners table. Her phone number is 18563330000. You
must specify the owner ID.
a. Compare your statement and results to those shown below:
mysql> INSERT INTO owners (oID, oName, oPhone)
-> VALUES (6,'Olga','18563330000');
Query OK, 1 row affected (0.02 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 20
b. Confirm the change. Compare your statement and results to those shown below:
mysql> SELECT * FROM owners;
+-----+--------+-------------+
| oID | oName | oPhone |
+-----+--------+-------------+
| 1 | Harold | 15554159855 |
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| 2 | Gwen | 15551234567 |
| 3 | Benny | 15553456789 |
| 4 | Diane | 15554567890 |
| 5 | Caryn | 16163429988 |
| 6 | Olga | 18563330000 |
+-----+--------+-------------+
6 rows in set (0.00 sec)
14. Exit the mysql client:
Note: You use the Pets database in future practices, so do not make any further changes
to the 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 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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 21
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Table Data Manipulation


Chapter 9 - Page 22
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
c b
l% era10:
Practices for n Lesson
f
2 0I ans
Functionsa% on-tr
i l l
o ad 10a n ฺ
bChapter
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 ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Functions


Chapter 10 - Page 1
Practices for Lesson 10: Overview
Practices Overview
These practices test your knowledge of functions. They target the Windows operating system,
provided in Oracle classrooms. For non-Oracle classrooms, you might need to adjust file
locations.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Assumptions
• You have installed and configured the MySQL server.
• You have created and populated the world_innodb database.
• You can access the mysql client from a command-line prompt.
• You can access MySQL Workbench if you choose to complete the practices using this
tool.
Note: In this practice, the first letters of table names are in uppercase. Windows is not case-
sensitive but some operating systems are, so it is good practice to use proper capitalization. to
The SQL statements are all in uppercase for clarity, but this is not required.
A 1n ense
Practice 10-1: Quiz – Functions C 3% le lic
n c l% erab
Overview
2 0I ansf
In this quiz, you answer questions about MySQL functions.
i l l a% on-tr
Duration o bad s a n eฺ
This practice takes approximately 10ra
B complete.
ha Guid
d minutes to
n yฺm ent x )
e j a
Quiz Questions
2 0 Al ฺuad Stud
Choose the best answer fromothose provided.
is
e l % r r e t h
1. Parentheses
Y o insefunction calls.
a arecoptional
a. True la
l @ u
b. a d i
False
o b
e l
2. ฺb The following query calculates the difference between the old and current gross national
( ya product of Montserrat. The result is NULL because the value of GNPOld is NULL. This
means you cannot determine the result of the subtraction.
mysql> SELECT Name, GNP, GNP - GNPOld
-> FROM Country
-> WHERE Name = 'Montserrat';
+------------+--------+---------------+
| Name | GNP | GNP - GNPOld |
+------------+--------+---------------+
| Montserrat | 109.00 | NULL |
+------------+--------+---------------+
a. True
b. False

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Functions


Chapter 10 - Page 2
3. What is the default format of the TIMESTAMP date component?
a. HH:MI:SS YYYY-MM-DD
b. TIMESTAMP
c. YYYY-MM-DD HH:MI:SS
d. All of the above
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

4. The CHAR_LENGTH function returns the number of ____________ in a specified string.


a. Numerals
b. Characters
c. Strings
d. Bytes
5. ROUND is a ____________ function that rounds a number to the ____________ integer.
a. String, exact
b. Temporal, nearest
c. Numerical, lowest to
d. Numerical, closest
A 1n ense
6. 3% le lic
MySQL does not support geometrical and trigonometric functions.
C
a. True
n c l% erab
b. False
2 0I ansf
7.
i l l a% on-tr
Which aggregate function calculates the average of a group of rows?

bad s a n eฺ
a. WITH ROLLUP
o
B ha uid
b. CALC()
c. GROUP_CONCAT() d r a x ) G
j a n yฺm ent
e
d. None of the above
l
8. 0A oฺuad s Stud
In a SELECT statement, if a WHERE clause selects 20 rows and a GROUP BY arranges them
2
el% corre e thi
into four groups of five rows each, a summary function produces a value for each of the four
a
Y @
groups.
us
l l a
b a di
a. True
b. False
l
9. ฺb o There can never be a space between a function name and the subsequent parenthesis.
ya e
( a. True
b. False

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Functions


Chapter 10 - Page 3
Solutions 10-1: Quiz – Functions
Quiz Solutions
1. b. False
2. a. True
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

3. c. YYYY-MM-DD HH:MI:SS
4. b. Characters
5. d. Numerical, closest
6. b. False
7. d. The function to use is AVG(). WITH ROLLUP is a modifier (not a function) that is used
with the AVG() function to perform a “super-aggregate” operation.
8. a. True
9. b. False. You can allow spaces by setting the IGNORE_SPACE SQL mode.

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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Functions


Chapter 10 - Page 4
Practice 10-2: Using Built-In, String, and Temporal Functions
Overview
In this practice, you use built-in, string, and temporal functions.

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

This practice takes approximately 15 minutes to complete.

Tasks
1. Show the version of MySQL that is currently running on your system.
2. Compare the string sort order of the words “awake” to “asleep”, and “awake” to “awake” and
“asleep” to “awake”, all in one function call.
3. Combine the following words to result in a complete sentence: I ' 'am ' 'mostly ' 'awake!'
4. Determine the partial string that starts on the sixth character of the string “HarryMonkey”.
5. Look up the available formats for the DATE_FORMAT() function in the online reference:
to
1n ense
http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html
A
the 4th of June in the year 2009”. C 3% le lic
6. Show the current day of the week, date, month, and year in the following format: “Tuesday

7. What weekday is it 500 days from now? n c l% erab


2 0I ansf
Note: Keep your mysql session open for the next practice.
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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Functions


Chapter 10 - Page 5
Solutions 10-2: Using Built-In, String, and Temporal Functions
Tasks
1. Show the version of MySQL that is currently running on your system:
Compare your statement and results to those shown below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

shell> mysql -uroot -poracle


...

mysql> SELECT VERSION();


+---------------------------------------+
| VERSION() |
+---------------------------------------+
| 5.6.10-enterprise-commercial-advanced |
+---------------------------------------+
1 row in set (0.09 sec)
2. Compare the string sort order of the words “awake” to “asleep”, and “awake” to “awake” and to
“asleep” to “awake”, all in one function call: A 1n ense
Compare your statement and results to those shown below:
C 3% le lic
mysql> SELECT strcmp('awake','asleep'),
n c l% erab
-> strcmp('awake','awake'),
2 0I ansf
-> strcmp('asleep','awake'); la%
i l n - tr
a d a no strcmp('asleep','awake')|
+-------------------------+------------------------+-------------------------+
b
B o as
| strcmp('awake','asleep')| strcmp('awake','awake')|
i d eฺ
1ra ) h t Gu 0 |
+-------------------------+------------------------+-------------------------+
|
a n d |
m x n
-1 |

lej sec)adyฺ tude


+-------------------------+------------------------+-------------------------+

− Returns2three
A
1 row in set (0.05
0 comparisons,
ฺu isshowingS the number of character differences.
l % r e o h
3. Combinee
Y or words
a the following
c s e totresult in a complete sentence: 'I ' 'am ' 'mostly ' 'awake!'
Compare
l l u and results to those shown below:
a@your statement
i
d SELECT CONCAT('I ','am ','mostly ', 'awake!');
oba+----------------------------------------+
mysql>

e l ฺb | CONCAT('I ','am ','mostly ', 'awake!') |


( ya +----------------------------------------+
| I am mostly awake! |
+----------------------------------------+
1 row in set (0.02 sec)
− Returns the completed sentence without the quotation marks
4. Determine the partial string that starts on the sixth character of the string “HarryMonkey”:
Compare your statement and results to those shown below:
mysql> SELECT SUBSTRING('HarryMonkey', 6);
+-----------------------------+
| SUBSTRING('HarryMonkey', 6) |
+-----------------------------+
| Monkey |
+-----------------------------+
1 row in set (0.02 sec)
− Returns the last six characters of the original string.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Functions


Chapter 10 - Page 6
5. Look up the available formats for the DATE_FORMAT() function in the online reference:
http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html
− There is a table that lists the format specifiers under the DATE_FORMAT entry.
6. Show the current day of the week, date, month, and year in the following format: “Tuesday
the 4th of June in the year 2009”:
Compare your statement and results to those shown below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT DATE_FORMAT(NOW(),


-> '%W the %D of %M in the year %Y');
+------------------------------------------------------+
| DATE_FORMAT(NOW(), '%W the %D of %M in the year %Y') |
+------------------------------------------------------+
| Tuesday the 2nd of April in the year 2013 |
+------------------------------------------------------+
1 row in set (0.03 sec)
− Returns the current date in the format specified
to
7. What weekday is it 500 days from now?
A 1n ense
Compare your statement and results to those shown below:
3 % e lic
mysql> SELECT DAYNAME(NOW() + INTERVAL 500 DAY);
l C
% rabl
c
0In ansfe
+-----------------------------------+
| DAYNAME(NOW() + INTERVAL 500 DAY) |
+-----------------------------------+a%
2 tr
i l l n -
| Friday
b a d | a no
1 row in set (0.01 sec) B
o as
+-----------------------------------+
i d eฺ
− The result depends onn d ra ) h the
when youxexecute t G u
function.
l
Note: Keep your mysql e a dopen
jsession yฺmfor thedenext
n practice.
2 0A oฺua s Stu
a el% corre e thi
Y @ us
l l a
b a di
l ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Functions


Chapter 10 - Page 7
Practice 10-3: Using Numeric and Control Flow Functions
Overview
In this practice, you use numeric and control flow functions.

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

This practice takes approximately 10 minutes to complete.

Tasks
1. Round the numbers -8.6 and 8.6 down to the nearest, smaller integer.
2. Examine the year of independence column for each record in the Country table and use a
CASE statement to put the dates into appropriate categories. Display the results in
descending year order.
Year Text
Before 1300 ‘Ancient’ to
Before 1800 ‘Really Old’ A 1n ense
3 % e lic
Before 1900 ‘Not Old’
l C
% rabl
c
Before 2000 ‘New’
2 0In ansfe
All others ‘Brand New’ la%
i l n - tr
Note: Keep your mysql session open for theb a
next a no ฺ
dpractice.
B o as ide
r a ) h u
j a nd yฺmx ent G
A le ad tud
2 0 ฺ u S
e l % rreo this
Ya @co use
d i lla
b o ba
a e lฺ
( y

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Functions


Chapter 10 - Page 8
Solutions 10-3: Using Numeric and Control Flow Functions
Tasks
1. Round the numbers -8.6 and 8.6 down to nearest (smaller) integer.
Compare your statement and results to those shown below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT FLOOR(-8.6), FLOOR(8.6);


+-------------+------------+
| FLOOR(-8.6) | FLOOR(8.6) |
+-------------+------------+
| -9 | 8 |
+-------------+------------+
1 row in set (0.03 sec)
− Shows the numbers rounded down
2. Examine the year of independence column for each record in the Country table and use a
CASE statement to put the dates into appropriate categories. Display the results in
descending year order. to
Compare your statement and results to those shown below:
A 1n ense
mysql> USE world_innodb 3 % e lic
Database changed
l C
% rabl
c
mysql> SELECT IndepYear, Name, 2 0In ansfe
-> CASE
i l l a% on-tr
-> WHEN IndepYear < 1300 athen d 'Ancient'
b then a n Old'
-> WHEN IndepYear < 1800
B o s 'Really
d e ฺ
-> WHEN IndepYear ra<< 1900 a
h 'Not
) then i
u Old'
n d x t G
l e ja New'
-> WHEN IndepYear
d y ฺm den
2000 then 'New'

0A oฺua s Stu
-> ELSE 'Brand
2
-> END

a e-> e
l%FROMorCountry
rBY
e t hi DESC;
Y -> c us
ORDER
@
IndepYear
ill a
+-----------+--------------------------+-----------------------------+
|d
o b a IndepYear
...
| Name | CASE |

e l ฺb +-----------+--------------------------+-----------------------------+
( ya |
|
1994 | Palau
1993 | Czech Republic
| New
| New
|
|
| 1993 | Slovakia | New |
...
| 1878 | Romania | Not Old |
| 1867 | Luxembourg | Not Old |
| 1867 | Canada | Not Old |
...
| 1776 | United States | Really Old |
| 1769 | Nepal | Really Old |
| 1581 | Netherlands | Really Old |
...
| 1278 | Andorra | Ancient |
| 1143 | Portugal | Ancient |
| 1066 | United Kingdom | Ancient |
...
| NULL | Turks and Caicos Islands | Brand New |
| NULL | French Polynesia | Brand New |

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Functions


Chapter 10 - Page 9
| NULL | Svalbard and Jan Mayen | Brand New |
...

Note: Keep your mysql session open for the next practice.
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Functions


Chapter 10 - Page 10
Practice 10-4: Using Aggregate Functions
Overview
In this practice, you use aggregate functions.

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

This practice takes approximately 20 minutes to complete.

Tasks
1. List all the continents from the Country table, and the total population of each continent.
2. List the average life expectancy on each continent, rounded to the closest integer.
3. List the average population of each city in the City table, where that figure is over
500,000. Group the results by country code.
4. Find the five most common government forms in the world.
5. List the average surface area per country on each continent. to
6. 1n ense
List the average surface area per country on each continent, and the average surface area
A
of all countries.
C 3% le lic
7. Exit the mysql client.
n c l% erab
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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Functions


Chapter 10 - Page 11
Solutions 10-4: Using Aggregate Functions
Tasks
1. List all the continents from the Country table, and the total population of each continent:
Compare your statement and results to those shown below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> USE world_innodb


Database changed

mysql> SELECT Continent, SUM(Population)


-> FROM Country
-> GROUP BY Continent;
+---------------+-----------------+
| Continent | SUM(Population) |
+---------------+-----------------+
| Asia | 3705025700 |
to
| Europe |
| North America |
730074600 |
482993000 | A 1n ense
| Africa | 784475000 |
C 3% le lic
| Oceania | 30401150 |
n c l% erab
0I ansf
| Antarctica | 0 |
| South America | 345780000 |
2
+---------------+-----------------+
i l l a% on-tr
ad arounded
7 rows in set (0.00 sec)
bcontinent, n toฺ the closest integer.
2. List the average life expectancy on each o
B those as shown de
ibelow:
Compare your statement and r a )
results to h
x nt G u
j a nd yฺmROUND(AVG(LifeExpectancy))
0 A le ad
mysql> SELECT Continent,
t u de
-> FROM Country
ฺ u
2 eoContinent; s S
l %GROUP rBY h i
ae cor se t
->
Y
+---------------+----------------------------+
u| ROUND(AVG(LifeExpectancy)) |
l a@
| Continent
i l
d
+---------------+----------------------------+

l ฺb oba| Asia
| Europe |
|
75 |
67 |

ya e | North America | 73 |
( | Africa | 53 |
| Oceania | 70 |
| Antarctica | NULL |
| South America | 71 |
+---------------+----------------------------+
7 rows in set (0.00 sec)
3. List the average population of each city in the City table, where that figure is over
500,000. Group the results by country code:
Compare your statement and results to those shown below:
mysql> SELECT CountryCode, AVG(Population) AS AvgPop
-> FROM City
-> GROUP BY CountryCode
-> HAVING AVG(Population) > 500000;
+-------------+--------------+
| CountryCode | AvgPop |
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Functions


Chapter 10 - Page 12
+-------------+--------------+
| AFG | 583025.0000 |
| AGO | 512320.0000 |
| ARM | 544366.6667 |
| AUS | 808119.0000 |
| AZE | 616000.0000 |
| CAF | 524000.0000 |
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| CIV | 638227.4000 |
| CMR | 503222.0000 |
| COD | 548034.1667 |
| COG | 725000.0000 |
| COL | 532920.7895 |
| EGY | 542785.9189 |
| GIN | 1090610.0000 |
| HKG | 1650316.5000 |
| IRQ | 595069.4000 |
| KOR | 557141.3286 |
| LBN | 670000.0000 |
| LBR | 850000.0000 |
to
| LBY
| MLI
| 674251.7500 |
| 809552.0000 | A 1n ense
| MNG | 773700.0000 |
C 3% le lic
| PAK | 534690.5932 |
n c l% erab
0I ansf
| PER | 552147.3636 |
| SGP | 4017733.0000 |
2
| SLE | 850000.0000 |
i l l a% on-tr
bad s a n eฺ
| THA | 662763.4167 |
| UGA | 890800.0000 |
o
B ha uid
| URY | 1236000.0000 |
d r
+-------------+--------------+ a x ) G
j a
28 rows in set (0.23 sec)n yฺm ent
− The optionalA
e
l clauseaprovides
d an d for the resulting column of data.
tualias
2 0 AS
ฺ u S
4. l
Find the five
e r r eo government
%most common t h is forms in the world:
Y a your
Compare
@ costatement
u seand results to those shown below:
i
mysql>
d lla SELECT GovernmentForm, COUNT(GovernmentForm) AS
oba
Governments

e l ฺb -> FROM Country


( ya -> GROUP BY GovernmentForm
-> ORDER BY Governments DESC
-> LIMIT 5;
+-------------------------------+-------------+
| GovernmentForm | Governments |
+-------------------------------+-------------+
| Republic | 122 |
| Constitutional Monarchy | 29 |
| Federal Republic | 15 |
| Dependent Territory of the UK | 12 |
| Monarchy | 5 |
+-------------------------------+-------------+
5 rows in set (0.00 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Functions


Chapter 10 - Page 13
5. List the average surface area per country on each continent.
Compare your statement and results to those shown below:
mysql> SELECT Continent, AVG(SurfaceArea) AS AverageSurfaceArea
-> FROM Country
-> GROUP BY Continent;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

+---------------+--------------------+
| Continent | AverageSurfaceArea |
+---------------+--------------------+
| Asia | 625117.745098 |
| Europe | 501068.128261 |
| North America | 654445.135135 |
| Africa | 521558.224138 |
| Oceania | 305867.642857 |
| Antarctica | 2626420.200000 |
| South America | 1276066.142857 |
+---------------+--------------------+
to
6. 1n ense
List the average surface area per country on each continent, and the average surface area
A
3% le lic
of all countries:
Compare your statement and results to those shown below: C
n c l%
f e r ab
mysql> SELECT Continent, AVG(SurfaceArea)
2 0I ans
AS AverageSurfaceArea

a% on-tr
-> FROM Country
i l l
bad s a n eฺ
-> GROUP BY Continent
-> WITH ROLLUP; o
B ha
d r a
+---------------+--------------------+
x ) G uid
| Continent
j
|nAverageSurfaceArea
a ฺ m e n t |
e y
Al |ฺuad 625117.745098tud
+---------------+--------------------+
| Asia
2 0 o s S |

| a el% America
| Europe
o r re || thi 501068.128261 |
Y North c us| e 654445.135135 |
lla
| Africa @ 521558.224138 |
i
| dOceania | 305867.642857 |

l ฺb oba| Antarctica | 2626420.200000 |

ya e | South America | 1276066.142857 |


( | NULL | 623248.146025 |
+---------------+--------------------+
8 rows in set (0.00 sec)
− Note that the average of all countries appears as a NULL column at the bottom of
the list.
7. Exit the mysql client.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Functions


Chapter 10 - Page 14
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
c b
l% era11:
Practices for n Lesson
f
2 0I ans
Exportinga% oand-tr Importing Data
i l l n
o ad 11a n ฺ
bChapter
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 ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 1
Practices for Lesson 11: Overview
Practices Overview
These practices test your knowledge of exporting and importing database data. They target the
Windows operating system, provided in Oracle classrooms. For non-Oracle classrooms, you
might need to adjust file locations.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Assumptions
• You have installed and configured the MySQL server.
• You have created and populated the world_innodb database.
• You can access the mysql client from a command-line prompt.
Note: In this practice, the first letters of table names are in uppercase. Windows is not case-
sensitive but some operating systems are, so it is good practice to use proper capitalization.
The SQL statements are all in uppercase for clarity, but this is not required.
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 2
Practice 11-1: Quiz – Exporting and Importing Data
Overview
In this quiz, you answer questions about exporting and importing data.

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

This practice takes approximately 15 minutes to complete.

Quiz Questions
Choose the best answer from those provided.
1. You can export data by using a MySQL query.
a. True
b. False
2. Which of the following are valid reasons to export your database data?
a. If tables are lost or damaged
to
b. If there is a system crash, to minimize data loss
A 1n ense
c. If a copy of the database is needed on another server
C 3% le lic
d. To load data into external applications
n c l% erab
e. To transfer data between RDBMSs
2 0I ansf
a% on-tr
f. All of the above
i l l
bad s a n eฺ
3. Use the SELECT statement with the ____________ clause to write the results directly into a
file. o
r a B ha uid
a. INTO OUTFILE
d
n yฺm entx ) G
b. INSERT INTO
l e j a
c. LOAD DATA INFILE
2 0A oฺuad s Stud
el% corre e thi
d. LOAD DATA OUTFILE
a
4. Which of the following clauses do you use to send query results to a text file containing
Y @
a
comma-separated values?
l l us
a di
a. OUTFILE WITH ','
b
l ฺb o
b. FIELDS TERMINATED BY ','
ya e
( c. ENCLOSED BY ','
d. Any of the above
5. The ____________ utility writes table contents to a file.
a. mysqlimport
b. INTO OUTFILE
c. mysqloutfile
d. mysqldump
6. Use the ____________ operator with mysqldump to indicate the export file name and
location.
a. <
b. =
c. >
d. :
7. You cannot import data from the shell prompt.
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 3
a. True
b. False
8. A SQL statement file (.sql) can create and populate tables. Use the ____________
statement within the MySQL client to execute this file.
a. mysql–import
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

b. INPUT FILE
c. IMPORT
d. SOURCE
9. Which of the following statements imports a file containing data only (not SQL statements)?
a. LOAD DATA INFILE
b. LOAD DATA OUTFILE
c. LOAD SOURCE FILE
d. None of the above.
10. The mysqlimport client program imports data files into tables.
to
a. True
A 1n ense
b. False
C 3% le lic
11. Which option displays detailed usage information for the import/export utilities?
n c l% erab
a. -h
0 I n s f
b. -info 2
% n-tra
i l l a
c. --help
b a d a no
12. When using the mysqlimport utility, the
B o destination
s tablese
d ฺ already be present and
must
a
ra x) h values.
the input files can contain only ____________ u i
n d t G
a. Column
l e ja dyฺm den
b. Data
2 0A oฺua s Stu
c. Database
a e l% orre
e t hi
d. Y Table
@ c us
a
ill a file by using LOAD DATA INFILE, MySQL assumes that the file resides
13. When importing
a
onbthe
dserver host, unless you specify otherwise.
b o
lฺ a. True
y a e
( b. False

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 4
Solutions 11-1: Quiz – Exporting and Importing Data
Quiz Solutions
1. a. True
2. f. All of the above
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

3. a. INTO OUTFILE
4. b. FIELDS TERMINATED BY ','
5. d. mysqldump
6. c. > (redirect)
7. b. False
8. d. SOURCE
9. a. LOAD DATA INFILE
10. a. True
11. c. --help to
12. b. Data A 1n ense
13. a. True
C 3% le lic
n c l% erab
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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 5
Practice 11-2: Exporting Files by Using a Query
Overview
In this practice, you use SELECT …INTO OUTFILE to export database data.

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

You have access to the Pets database, which you populated with data in the “Data
Manipulation” practice.

Duration
This practice takes approximately 20 minutes to complete.

Tasks
1. Set the Pets database as the default database.
2. Execute a SELECT...INTO OUTFILE statement to export the pet_info table to a text
to
all the rows and columns from the table. A 1n ense
file. Put this file in the D:\labs directory. Examine the text file and confirm that it contains

Hints: C 3% le lic
c l% erab
− In the Oracle classroom environment, use Notepad++ to view the text files in the correct
n
format. 2 0I ansf
− The contents are the same as the output of iallSELECT a% o*n-FROM tr pet_info statement.
3. Execute a query to export the owners table
o batod astextafilen in CSV
e ฺ format. Put this file in the
B
ra x) a ttheGformat.
D:\labs directory. Examine the text file andhnote
uid Confirm that it contains all the
rows and columns from the n d
table.
m character
n terminates each row, double quotation
Note: In the CSV format, l e jaa carriage
d y ฺreturn d e
marks enclose 2 0Avalue,oฺand
each uacommas S u
tseparate the values.
l %
4. Using theeworld_innodb e
rr database, i s
th back up the CountryLanguage table to a standard
Y a c o
text file. Put this file in the e
sD:\labs directory. Examine the text file and confirm that it
l
containsilall
@rows anducolumns
athe from the table.
Note: b a d
l ฺ b o Keep your mysql session open for the next practice.
( yae

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 6
Solutions 11-2: Exporting Files by Using a Query
Tasks
1. Set the Pets database as the default database.
a. Log in to the mysql client program:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

cmd> mysql -u root -p


Enter password: oracle
...
b. Compare your statement and results to those shown below:
mysql> USE Pets
Database changed
2. Execute a SELECT...INTO OUTFILE statement to export the pet_info table to a text
file. Put this file in the D:\labs directory.
a. Compare your statement and results to those shown below:
n nse to
mysql> SELECT * INTO OUTFILE 'D:/labs/pet_info.txt' A1
3 % e lice
-> FROM pet_info;
l % C bl
Query OK, 9 rows affected (0.00 sec)
I n c f e ra
− The statement creates a text file in the D:\labs 0 an
2directory. s
b. Open the text file in Notepad++ and examine i l l % n -
athe contents:tr
b a d a n\No 1 1
1 Fluffy F
o as \Nideฺ2 1
2003-02-04
B
2 Claws M
a x) h Gu\N 3 2
2004-03-17
M dr2000-08-27
4 Fang
j a n ฺ m e n t \N 2 3
6 Chirpy
e F y
2008-09-11
Al M ฺuad2007-12-09 ud
7
2 0
Whistler
S t \N 2 4
8
l% orre F th\Ni
Slim oM s
2006-04-29 \N 3 8
9 aeChewy
Y c s e
uM 2008-04-17
\N 6 6
a@
10 Opus
13 illScruffy
F \N \N 5 1

a d \N 2 1

l ฺb oc.b Confirm that it contains all the rows and columns from the table. Compare your
ya e statement and results to those shown below:
( mysql> SELECT * FROM pet_info;
+-----+----------+---------+------------+-------+-----+-----+
| pID | pName | pGender | pBday | pDday | oID | tID |
+-----+----------+---------+------------+-------+-----+-----+
| 1 | Fluffy | F | 2003-02-04 | NULL | 1 | 1 |
| 2 | Claws | M | 2004-03-17 | NULL | 2 | 1 |
| 4 | Fang | M | 2000-08-27 | NULL | 3 | 2 |
| 6 | Chirpy | F | 2008-09-11 | NULL | 2 | 3 |
| 7 | Whistler | M | 2007-12-09 | NULL | 2 | 4 |
| 8 | Slim | M | 2006-04-29 | NULL | 3 | 8 |
| 9 | Chewy | F | NULL | NULL | 6 | 6 |
| 10 | Opus | F | NULL | NULL | 5 | 1 |
| 13 | Scruffy | M | 2008-04-17 | NULL | 2 | 1 |
+-----+----------+---------+------------+-------+-----+-----+
9 rows in set (0.00 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 7
3. Execute a query to export the owners table to a text file in CSV format. Put this file in the
D:\labs directory.
a. Compare your statement and results to those shown below:
mysql> SELECT *
-> INTO OUTFILE 'D:/labs/owners.txt'
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-> FIELDS TERMINATED BY ','


-> ENCLOSED BY '"'
-> LINES TERMINATED BY '\r'
-> FROM owners;
Query OK, 6 rows affected (0.02 sec)
− The statement creates a text file in the D:\labs directory.
b. Inspect the contents of the text file by using Notepad++ and note the format. Confirm
that it contains all the rows and columns from the table:
"1","Harold","15554159855"
to
"2","Gwen","15551234567"
A 1n ense
"3","Benny","15553456789"
C 3% le lic
"4","Diane","15554567890"
n c l% erab
"5","Caryn","16163429988"
2 0I ansf
"6","Olga","18563330000"
l l a % n-tr
4.
a i
Using the world_innodb database, back updthe CountryLanguage no ฺ table to a standard
b
o as
text file. Put this file in the D:\labs directory. a
r a B h u de
ibelow:
a. Compare your statement and results
nd yฺmx ent G )
to those shown
j
le ad
mysql> USE world_innodb a
2
Database changed0 A ฺ u S tud
e l % rreo this
Y a SELECT
mysql>
@ co *usINTO e OUTFILE 'D:/labs/CountryLanguage.txt'
i a FROM CountryLanguage;
ll->
d
l obaQuery OK, 984 rows affected (0.00 sec)
ฺb b.
ya e Inspect the contents of the text file by using Notepad++. Confirm that it contains all the
( rows and columns from the table.
ABW Dutch T 5.3
ABW English F 9.5
ABW Papiamento F 76.7
ABW Spanish F 7.4
AFG Balochi F 0.9
AFG Dari T 32.1
AFG Pashto T 52.4
AFG Turkmenian F 1.9
AFG Uzbek F 8.8
AGO Ambo F 2.4
...
ZAF Zulu T 22.7
ZMB Bemba F 29.7
ZMB Chewa F 5.7
ZMB Lozi F 6.4
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 8
ZMB Nsenga F 4.3
ZMB Nyanja F 7.8
ZMB Tongan F 11.0
ZWE English T 2.2
ZWE Ndebele F 16.2
ZWE Nyanja F 2.2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

ZWE Shona F 72.1

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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 9
Practice 11-3: Importing Files from a Data File
Overview
In this practice, you use a LOAD DATA INFILE statement to import database data.

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

This practice takes approximately 15 minutes to complete.

Tasks
1. In the Pets database, create a table like pet_info called pet_info2. Check that the
new table exists in the database.
2. Use a LOAD DATA INFILE statement to import the data from the pet_info.txt file
(from the previous practice) into the new pet_info2 table.
3. List all the records in the new pet_info2 table and confirm that it contains all the data.
4. In the world_innodb database, create a table like CountryLanguage called to
CountryLanguage2.
A 1n ense
5. Import the CountryLanguage.txt file created in the previous practice 3%into the lic
CountryLanguage2 table. Confirm that the new table containsl%
C b le of
the correctanumber
rows.
0 I nc sfer
%
Note: Keep your mysql session open for the next practice. 2 tran
d i l non-
l a
B oba as a ideฺ
n d ra x) h t Gu
l e ja dyฺm den
2 0A oฺua s Stu
a el% corre e thi
Y @ us
l l a
b a di
l ฺ b o
( yae

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 10
Solutions 11-3: Importing Files from a Data File
Tasks
1. In the Pets database, create a table like pet_info called pet_info2.
a. Compare your statement and results to those shown below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> USE Pets

mysql> CREATE TABLE pet_info2 LIKE pet_info;


Query OK, 0 rows affected (0.08 sec)
b. Check that the new table exists in the database:
mysql> SHOW TABLES LIKE 'pet_info%';
+----------------------------+
| Tables_in_pets (pet_info%) |
+----------------------------+
| pet_info | to
| pet_info2 |
A 1n ense
3% le lic
+----------------------------+
2 rows in set (0.02 sec)
C
2. Use a LOAD DATA INFILE statement to import the data fromcthe
n f e r ab file
l%pet_info.txt
(from the previous practice) into the new pet_info2 table. 2 0I ans
Compare your statement and results to those
i l l % below:
ashown n - tr
b a d a no
eฺ
mysql> LOAD DATA INFILE 'D:/labs/pet_info.txt'
B o as i d
-> INTO TABLE pet_info2;
d ra (0.00 x h Gu
) sec)
Query OK, 9 rows affected
j a n ฺ m e n t
Records: 9 Deleted:
A l e a
0 d y
Skipped:
u d0 Warnings: 0
0
2 in theeonew u
ฺ pet_info2 t
S table and confirm that it contains all the data.
3. List all the records
l % r r h i s
t results to those shown below:
ae your
Compare
Y c ostatements e and
l l a@ SELECT *uFROM pet_info2;
i
mysql>
d
oba| pID | pName | pGender | pBday
+-----+----------+---------+------------+-------+-----+-----+

e l ฺb | pDday | oID | tID |


+-----+----------+---------+------------+-------+-----+-----+
( ya |
|
1 | Fluffy
2 | Claws
| F
| M
| 2003-02-04 | NULL |
| 2004-03-17 | NULL |
1 |
2 |
1 |
1 |
| 4 | Fang | M | 2000-08-27 | NULL | 3 | 2 |
| 6 | Chirpy | F | 2008-09-11 | NULL | 2 | 3 |
| 7 | Whistler | M | 2007-12-09 | NULL | 2 | 4 |
| 8 | Slim | M | 2006-04-29 | NULL | 3 | 8 |
| 9 | Chewy | F | NULL | NULL | 6 | 6 |
| 10 | Opus | F | NULL | NULL | 5 | 1 |
| 13 | Scruffy | M | 2008-04-17 | NULL | 2 | 1 |
+-----+----------+---------+------------+-------+-----+-----+
9 rows in set (0.00 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 11
4. In the world_innodb database, create a table like CountryLanguage called
CountryLanguage2.
Compare your statement and results to those shown below:
mysql> USE world_innodb
Database changed
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> CREATE TABLE CountryLanguage2 LIKE CountryLanguage;


Query OK, 0 rows affected (0.03 sec)
5. Import the CountryLanguage.txt file created in the previous practice into the
CountryLanguage2 table.
a. Compare your statement and results to those shown below:
mysql> LOAD DATA INFILE 'D:/labs/CountryLanguage.txt'
-> INTO TABLE CountryLanguage2;

to
Query OK, 984 rows affected (0.08 sec)
Records: 984 Deleted: 0 Skipped: 0 Warnings: 0
1 n nse
b. Confirm that the new table contains the correct number of rows: A
% e lice
mysql> SELECT COUNT(*) FROM CountryLanguage2;%C
3
c l r a bl
0In ansfe
+----------+
| COUNT(*) | 2
+----------+
i l l a% on-tr
| 984 |
+----------+
o b ad a n ฺ
1 row in set (0.06 sec) B
r a ) h as uide
Note: Keep your mysql sessionnopen
a d form n t G
thexnext practice.
j
le ady tude ฺ
2 0 A ฺu is S
% e o
el rr th
Ya @co use
d i lla
b o ba
a e lฺ
( y

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 12
Practice 11-4: Backing Up Database Files with a Utility
Overview
In this practice, you use the mysqldump utility to back up a database.

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

This practice takes approximately 25 minutes to complete.

Tasks
Tip: Open two separate command-prompt windows. Work with the shell commands in one
window and the MySQL statements in the other. This avoids having to enter and exit the
mysql client repeatedly.
1. Use mysqldump to create a SQL backup of the world_innodb database in the D:\labs
directory. Examine the contents of the backup file.
2. Create another backup file, this time with the --skip-opt flag. Compare the two files.
to
What is the difference?
A 1n ense
3% le lic
3. Use the mysql client to create a new database called world_innodb2. Confirm that the
new database exists. Exit the mysql client. C
4. n
Use one of your new dump files as part of the mysql client startup c l%command
f e r abto import the
contents of world_innodb to world_innodb2. Examine 2 0Ithe world_innodb2
a n s database
to confirm. %
lla non- t r
d i
5. Exit the mysql client.
o ba s a ฺ Ensure that the output
etable.
6. B
Use a MySQL utility to create a backup of just athe i d
) hThis creates
rad:\labs. u country.txt and
Country
file is tab-delimited and written
n dto x t G
l
country.sql files: review e ฺm den
ja themdboth.
y
2 0A oฺua s Stu
a el% corre e thi
Y @ us
l l a
b a di
l ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 13
Solutions 11-4: Backing Up Database Files with a Utility
Tasks
1. Use mysqldump to create a SQL backup of the world_innodb database in the D:\labs
directory.
a. Execute the following at the command prompt:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

cmd> mysqldump -uroot -poracle world_innodb >


D:/labs/world_innodb_backup.sql
b. Examine the contents of the backup file:
-- MySQL dump 10.13 Distrib 5.6.10, for Win64 (x86_64)
--
-- Host: localhost Database: world_innodb
-- ------------------------------------------------------
-- Server version 5.6.10-enterprise-commercial-advanced
to
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT A 1n*/; ense
c
3% le li*/;
C
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS
l% erab */;
I n c
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION
f
/*!40101 SET NAMES utf8 */;
2 0 n s
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE
l l a %*/; n-tra
/*!40103 SET TIME_ZONE='+00:00' */;
a i
d a no
b
o as
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, e ฺ UNIQUE_CHECKS=0 */;
B
ra x) h t Gu i d
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS,
n d
FOREIGN_KEY_CHECKS=0
l e ja dyฺm den
*/;

0A oฺua s Stu */;


/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE,
2
SQL_MODE='NO_AUTO_VALUE_ON_ZERO'
el% SET
/*!40111
a o r re t hi
@OLD_SQL_NOTES=@@SQL_NOTES,
e
SQL_NOTES=0 */;
Y @c us
-- illa
d
l ฺb oba-- Table structure for table `city`
ya e --
(
DROP TABLE IF EXISTS `city`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `city` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` char(35) NOT NULL DEFAULT '',
`CountryCode` char(3) NOT NULL DEFAULT '',
`District` char(20) NOT NULL DEFAULT '',
`Population` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`),
KEY `CountryCode` (`CountryCode`),
CONSTRAINT `city_ibfk_1` FOREIGN KEY (`CountryCode`) REFERENCES
`country` (`Code`)
) ENGINE=InnoDB AUTO_INCREMENT=4080 DEFAULT CHARSET=latin1;
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 14
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `city`
--
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

LOCK TABLES `city` WRITE;


/*!40000 ALTER TABLE `city` DISABLE KEYS */;
INSERT INTO `city` VALUES
(1,'Kabul','AFG','Kabol',1780000),(2,'Qandahar','AFG','Qandahar',23750
0),(3,'Herat','AFG','Herat',186800),(4,'Mazar-e-
Sharif','AFG','Balkh',127800),(5,'Amsterdam','NLD','Noord-
Holland',731200),(6,'Rotterdam','NLD','Zuid-
Holland',593321),(7,'Haag','NLD','Zuid-
Holland',440900),(8,'Utrecht','NLD','Utrecht',234323),(9,'Eindhoven','
NLD','Noord-Brabant',201843),(10,'Tilburg','NLD','Noord-
Brabant',193238),(11,'Groningen','NLD','Groningen',172701),(12,'Breda'
to
,'NLD','Noord-Brabant',160398),
... A 1n ense
2. Create another backup file, this time with the --skip-opt flag. C 3% le lic
a. Execute the following at the command prompt:
n c l% erab
0I world_innodb
n s f
cmd> mysqldump -uroot -poracle --skip-opt
% 2 t r a >
D:/labs/world_innodb_backup2.sql l a
il non -
a
b sad
b. Compare the two files. What is the difference?
B o5.6.10,a i d eฺ(x86_64)
-- MySQL dump 10.13 Distrib
n d ra x) h t Gu for Win64
--
l e d y ฺm dworld_innodb
ja Database: e n
0A oฺua s Stu
-- Host: localhost
2 i
-- ------------------------------------------------------
a el% cversion
-- Server o rre e th5.6.10-enterprise-commercial-advanced
Y us
@SET @OLD_TIME_ZONE=@@TIME_ZONE
/*!40103
l l a */;

b a di
/*!40103 SET TIME_ZONE='+00:00' */;

l ฺb o /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;

ya e /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS,


( FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE,
SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `city`
--

/*!40101 SET @saved_cs_client = @@character_set_client */;


/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `city` (
`ID` int(11) NOT NULL,
`Name` char(35) NOT NULL DEFAULT '',
`CountryCode` char(3) NOT NULL DEFAULT '',
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 15
`District` char(20) NOT NULL DEFAULT '',
`Population` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`),
KEY `CountryCode` (`CountryCode`),
CONSTRAINT `city_ibfk_1` FOREIGN KEY (`CountryCode`) REFERENCES
`country` (`Code`)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

);
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `city`
--

INSERT INTO `city` VALUES (1,'Kabul','AFG','Kabol',1780000);


INSERT INTO `city` VALUES (2,'Qandahar','AFG','Qandahar',237500);
to
1n ense
INSERT INTO `city` VALUES (3,'Herat','AFG','Herat',186800);
INSERT INTO `city` VALUES A
(4,'Mazar-e-Sharif','AFG','Balkh',127800);
INSERT INTO `city` VALUES
C 3% le lic
(5,'Amsterdam','NLD','Noord-
Holland',731200);
n c l% erab
INSERT INTO `city`
0 I s f
VALUES (6,'Rotterdam','NLD','Zuid-Holland',593321);
n
2
INSERT INTO `city`
i l l a% on-tra
VALUES (7,'Haag','NLD','Zuid-Holland',440900);

ad a n ฺ
INSERT INTO `city` VALUES (8,'Utrecht','NLD','Utrecht',234323);
...
o b s oridALTER e TABLE statements. A
− There are no DROP DATABASE,
r a B LOCKhaTABLES, u
separate INSERT statement )
nd yฺpopulates
x each t G
row.
j a m n
3. Use the mysql client lto
0 A t u de called world_innodb2.
ecreateaadnew database
a. Compare your 2 statement u s S to those shown below:
oฺ andhiresults
l % r e
Y ae CREATE
mysql>
c or DATABASE
s e t world_innodb2;
Querya@ OK, 1 rowuaffected (0.02 sec)
i l l
d that the new database exists:
oba
b. Confirm

e l ฺb mysql> SHOW DATABASES;


( ya +--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| pets |
| sakila |
| test |
| world |
| world_innodb |
| world_innodb2 |
+--------------------+
9 rows in set (0.03 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 16
c. Exit the mysql client. Enter the following at the mysql> prompt:
mysql> EXIT
4. Use one of your new dump files as part of the mysql client startup command to import the
contents of world_innodb to world_innodb2.
a. Execute the following at the command prompt:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

cmd> mysql -uroot -poracle world_innodb2 <


D:/labs/world_innodb_backup2.sql
− This can take several minutes to complete.
b. Examine the world_innodb2 database to confirm.
cmd> mysql -uroot -poracle
...
mysql> SHOW DATABASES;
+--------------------+
| Database |
to
1n ense
+--------------------+
| information_schema |
A
| mysql |
| performance_schema | C 3% le lic
| pets |
n c l% erab
| sakila |
2 0I ansf
a% on-tr
| test |
| world |
i l l
| world_innodb |
o bad s a n eฺ
| world_innodb2 |
r a B ha uid
+--------------------+
d
n yฺm ent
9 rows in set (0.05 sec) x ) G
l e j a
2 0A ฺ u ad Stud
mysql> USE
e l r r eo this
world_innodb2
% changed
Ya @co use
Database

d i lla SHOW TABLES;


oba+-------------------------+
mysql>

e l ฺb | Tables_in_world_innodb2 |
( ya +-------------------------+
| city |
| country |
| country2 |
| countrylanguage |
| countrylanguage2 |
| gelderlanddist |
+-------------------------+
6 rows in set (0.02 sec)
5. Exit the mysql client:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 17
6. Use a MySQL utility to create a backup of just the Country table. Ensure that the output
file is tab-delimited and written to d:\labs.
a. Execute the following at the command prompt:
cmd> mysqldump -uroot -poracle --tab=D:/labs
world_innodb Country
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

b. Review the country.txt file:


ABW Aruba North America Caribbean 193.00 \N 103000 78.4 828.00 793.00
Aruba Nonmetropolitan Territory of The Netherlands Beatrix 129
AW
AFG Afghanistan Asia Southern and Central Asia 652090.00 1919
22720000 45.9 5976.00 \N Afganistan/Afqanestan
Islamic Emirate Mohammad Omar 1 AF
AGO Angola Africa Central Africa 1246700.00 1975 12878000 38.3
6648.00 7984.00 Angola Republic José Eduardo dos Santos
56 AO
AIA Anguilla North America Caribbean 96.00 \N 8000 76.1 63.20
\N Anguilla Dependent Territory of the UK Elisabeth II 62
to
se
AI
...
1962 A
1n
6695000 en
BDIBurundi Africa Eastern Africa 27834.00
3 % Buyoya
e l ic552
46.2
BI
903.00 982.00 Burundi/Uburundi Republic
l CPierre
l
% 1830rab10239000
BEL Belgium Europe Western Europe 30518.00c fe
In nsConstitutional
77.8 249704.00 243948.00
2 0
België/Belgique
Monarchy, Federation Albert II 179
l l a% BEon-t1960 ra 6097000
BEN Benin Africa Western Africa
d i112622.00
n
50.2

...
2357.00 2141.00
o ba s a
Bénin Republic
e
Mathieu

TON Tonga Oceania B
a x) hTupou
rPolynesia a 650.00 u i
1970d 99000 67.9 146.00 170.00
n d t G
ฺmAmerica
Tonga Monarchy Taufa'ahau IV 3334 TO
TTO Trinidad and
l e a dNorth
jTobago y d e n
Caribbean 5130.00 1962
1295000 A 68.0 a 6232.00tu
2 0 oArthur ฺu N.isR.SRobinson 5867.00 Trinidad and Tobago

l %
Republic
TUN eTunisiaor r e h
3336 TT
t Northern Africa 163610.00 1956 9586000
Y a 73.7 c20026.00Africas e
a @ u 18898.00 Tunis/Tunisie Republic Zine al-

a d illTurkey Asia Middle East 774815.00 1923 66591000 71.0


Abidine Ben Ali 3349 TN

ob
TUR

e l ฺb 210721.00
3358 TR
189122.00 Türkiye Republic Ahmet Necdet Sezer

( ya ...
YUG Yugoslavia Europe Southern Europe 102173.00 1918 10640000
72.4 17000.00 \N Jugoslavija Federal Republic Vojislav
Koštunica 1792 YU
ZAF South Africa Africa Southern Africa 1221037.00 1910 40377000
51.1 116729.00 129092.00 South Africa Republic Thabo Mbeki
716 ZA
ZMB Zambia Africa Eastern Africa 752618.00 1964 9169000 37.2
3377.00 3922.00 Zambia Republic Frederick Chiluba 3162
ZM
ZWE Zimbabwe Africa Eastern Africa 390757.00 1980 11669000
37.8 5951.00 8670.00 Zimbabwe Republic

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 18
c. Review the country.sql file:
-- MySQL dump 10.13 Distrib 5.6.10, for Win64 (x86_64)
--
-- Host: localhost Database: world_innodb
-- ------------------------------------------------------
-- Server version 5.6.10-enterprise-commercial-advanced
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;


/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

to
--
A 1n ense
3% le lic
-- Table structure for table `country`
--
C
l% erab
n c f
DROP TABLE IF EXISTS `country`;
2 0I ans*/;
/*!40101 SET @saved_cs_client
l l % n-tr
= @@character_set_client
a*/;
/*!40101 SET character_set_client = utf8
a i
d a no
CREATE TABLE `country` ( b
o '', as eฺ
B
raDEFAULT
`Code` char(3) NOT NULL DEFAULT
h Gu i d
`Name` char(52) NOT NULL
n d x ) '', t
l e j a yฺ m e n
0A oฺuad s Stud
`Continent` enum('Asia','Europe','North
America','Africa','Oceania','Antarctica','South America') NOT NULL DEFAULT
2
hi DEFAULT '',
rre NOTe tNULL
el% cchar(26)
'Asia',

a
`Region`
Y`SurfaceArea` o
l l a us DEFAULT
@ smallint(6)
float(10,2) NOT NULL DEFAULT '0.00',

a d i
`IndepYear` NULL,

l ฺbob `Population` int(11) NOT NULL DEFAULT '0',

ya e `LifeExpectancy` float(3,1) DEFAULT NULL,

( `GNP` float(10,2) DEFAULT NULL,


`GNPOld` float(10,2) DEFAULT NULL,
`LocalName` char(45) NOT NULL DEFAULT '',
`GovernmentForm` char(45) NOT NULL DEFAULT '',
`HeadOfState` char(60) DEFAULT NULL,
`Capital` int(11) DEFAULT NULL,
`Code2` char(2) NOT NULL DEFAULT '',
PRIMARY KEY (`Code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
...
-- Dump completed on 2013-04-04 13:00:40

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 19
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Exporting and Importing Data


Chapter 11 - Page 20
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
c b
l% era12:
Practices for n Lesson
f
2 0I ans
Joining Tables
a% on-tr
i l l
o ad 12a n ฺ
bChapter
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 ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 1
Practices for Lesson 12: Overview
Practices Overview
These practices test your knowledge of table joins. They target the Windows operating system,
provided in Oracle classrooms. For non-Oracle classrooms, you might need to adjust file
locations.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Assumptions
• You have installed and configured the MySQL server.
• You have created and populated the world_innodb database.
• You can access the mysql client from a command-line prompt.
• You can access MySQL Workbench if you choose to complete the practices by using
this tool.
Note: In this practice the first letters of table names are in uppercase. Windows is not case-
sensitive but some operating systems are, so it is good practice to use proper capitalization. to
1n ense
The SQL statements are all in uppercase for clarity, but this is not required.
A
C 3% le lic
n c l% erab
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 2
Practice 12-1: Performing Inner and Outer Joins
Overview
In this practice, you use the INNER JOIN, LEFT JOIN, and RIGHT JOIN keywords to perform
multi-table queries.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Duration
This practice takes approximately 20 minutes to complete.

Tasks
1. Plan and execute a query to display the country and district details for the city of San
Antonio:
a. Issue SQL statements to display the structure of all the tables in the world_innodb
database. Answer the following questions:
− Which table contains city and district names?
to
− Which table contains country names?
A 1n ense
Antonio in the City table. C 3% le lic
b. Before constructing your join, execute a query to ensure that there is a city named San

c. Use a SELECT...INNER JOIN statement to combineIthe n l% erand


cCountryf abCity tables.
Match records on the Code column from the Country 2 0 tableaand
n sthe CountryCode
column from the Country table. Filter the iresultsl l a%to oretrieve
n r
-t the country and district for
the city of San Antonio.
o b ad a n ฺ
Hint: Use the proper syntax to specify
r a B which h astable ueachi decolumn in your query belongs
to: <table>.<column> d
n )
x nt G
j a
lethe countries ฺ m e to. Use an INNER JOIN statement to
y theyubelong
2. List all capital cities with
0 A a dtables. t dthe
combine the City 2 and ฺ u
Country
o s S Use aliases “CapitalName” for cities and
“CountryName” %
el coand
for e
rr e th
countries. i
3. Yathe names
Display
@ s cities of countries with the codes CHE and ATA. One of
capital
u
i ll
these countriesa has a capital city record associated with it and the other does not, but both
d
oba
countries must appear in the query output. Use appropriate aliases for the columns in the

e l ฺb resultset.

( ya Hint: Use a SELECT...LEFT JOIN statement to join the Country and City tables where
the identifier in the Country table’s Capital column matches the City table’s ID
column. Base the LEFT JOIN on the Country table to ensure that every country features
in the results.
4. Repeat previous step using a RIGHT JOIN to base the query on the City table and
compare the results.
Note: Keep your mysql session open for the next practice.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 3
Solutions 12-1: Performing Inner and Outer Joins
Tasks
1. Plan and execute a query to display the country and district details for the city of San
Antonio:
a. Issue SQL statements to display the structure of all the tables in the world_innodb
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

database.
cmd> mysql -uroot -poracle
...

mysql> USE world_innodb;


Database changed.

mysql> DESC City;


+-------------+----------+------+-----+---------+----------------+
to
| Field | Type | Null | Key | Default | Extra
A 1n ense
|

3% le lic
+-------------+----------+------+-----+---------+----------------+
| ID | int(11) | NO | PRI | NULL | auto_increment |
| Name | char(35) | NO | | | C
l% erab |
n c
0I ansf
| CountryCode | char(3) | NO | MUL | | |
| District | char(20) | NO | | 2 | |
| Population | int(11) | NO |
i
| 0
l l a% on-tr
| |

bad s a n eฺ
+-------------+----------+------+-----+---------+----------------+
5 rows in set (0.02 sec)
o
B ha id
d r a x ) G u
mysql> DESC Country;
j a n yฺm ent
e
Al | Type ad Stud | Null | Key | Default | Extra |
+----------------+--------------------+------+-----+---------+-------+
| Field
2 0 ฺ u
l % rre| ochar(3) is
+----------------+--------------------+------+-----+---------+-------+
e t h
Y a
| Code
c o | char(52)
s e | NO | PRI | | |

@ |uenum('Asia',
| Name | NO | | | |

| dil
l a
| Continent | | | | |

o b a
|
| 'Europe',
| 'North America'
|
|
|
|
|
|
|
|
|
|

e l ฺb | | 'Africa' | | | | |

( ya |
|
| 'Oceania',
| 'Antarctica',
|
|
|
|
|
|
|
|
|
|
| | 'South America') | NO | | Asia | |
| Region | char(26) | NO | | | |
| SurfaceArea | float(10,2) | NO | | 0.00 | |
| IndepYear | smallint(6) | YES | | NULL | |
| Population | int(11) | NO | | 0 | |
| LifeExpectancy | float(3,1) | YES | | NULL | |
| GNP | float(10,2) | YES | | NULL | |
| GNPOld | float(10,2) | YES | | NULL | |
| LocalName | char(45) | NO | | | |
| GovernmentForm | char(45) | NO | | | |
| HeadOfState | char(60) | YES | | NULL | |
| Capital | int(11) | YES | | NULL | |
| Code2 | char(2) | NO | | | |
+----------------+--------------------+------+-----+---------+-------+
15 rows in set (0.06 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 4
mysql> DESC CountryLanguage;
+-------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+-------+
| CountryCode | char(3) | NO | PRI | | |
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| Language | char(30) | NO | PRI | | |


| IsOfficial | enum('T','F') | NO | | F | |
| Percentage | float(4,1) | NO | | 0.0 | |
+-------------+---------------+------+-----+---------+-------+
4 rows in set (0.01 sec)
− Which table contains city and district names? City
− Which table contains country names? Country
b. Before constructing your join, execute a query to ensure that there is a city named San
Antonio in the City table. Compare your statement and results to those shown below:
mysql> SELECT Name FROM City
to
-> WHERE Name = 'San Antonio';
+-------------+ A 1n ense
| Name | 3 % e lic
+-------------+
l C
% rabl
| San Antonio | c
In nsfe
+-------------+
2 0
1 row in set (0.14 sec)
i l l a% on-tra
c. Use a SELECT...INNER JOIN statement
Match records on the Code column o badthetosCountry
from
n theฺ Country and City tables.
combine
a e and the CountryCode
table
a B h a u i d
a n dr m
column from the Country table. Filter) the results to retrieve the country and district for
x nt Gand results to those shown below:
j
the city of San Antonio. Compare ฺ your statement
de
dy tuCity.District
leCountry.Name,
mysql> SELECT 0 A
2 eoฺ u a S
l % r h i s
cor JOIN t
-> FROM Country
e INNER
Ya ->@ u s eCity
i l l
->a ON CountryCode = Code
a d
l ฺbob -> WHERE City.Name
+---------------+----------+
= 'San Antonio';

ya e | Name | District |
( +---------------+----------+
| United States | Texas |
+---------------+----------+
1 row in set (0.11 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 5
2. List all capital cities with the countries they belong to. Use an INNER JOIN statement to
combine the City and Country tables. Use the aliases “CapitalName” for cities and
“CountryName” for countries. Compare your statement and results to those shown below:
mysql> SELECT City.Name AS CapitalName, Country.Name
-> AS CountryName
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-> FROM City


-> INNER JOIN Country
-> ON City.ID = Country.Capital;
+-----------------------------------+---------------------------------------+
| CapitalName | CountryName |
+-----------------------------------+---------------------------------------+
| Oranjestad | Aruba |
| Kabul | Afghanistan |
| Luanda | Angola |
| The Valley | Anguilla |
| Tirana | Albania |
| Andorra la Vella | Andorra |
| Willemstad | Netherlands Antilles | to
| Abu Dhabi | United Arab Emirates
A 1n ense
|

3% le lic
| Buenos Aires | Argentina |
...
| Cittα del Vaticano C
l% erab
| Holy See (Vatican City State) |
n c
0I ansf
| Kingstown | Saint Vincent and the Grenadines |
| Caracas | Venezuela
2 |

a% on-tr
| Road Town | Virgin Islands, British |
| Charlotte Amalie
i l l
| Virgin Islands, U.S. |
| Hanoi
| Port-Vila o bad s a n eฺ
| Vietnam
| Vanuatu
|
|
| Mata-Utu
r a B ha uid
| Wallis and Futuna |
| Apia d
n yฺm ent x )
| Samoa G |
| Sanaa
l e j a | Yemen |

0A oฺuad s Stud
| Beograd | Yugoslavia |
| Pretoria
2 | South Africa |

el% corre e thi


| Lusaka | Zambia |
a
| Harare
Y @
| Zimbabwe |

l l a us
+-----------------------------------+---------------------------------------+

dithe names and capital cities of countries with the codes CHE and ATA. One of
232 rows in set (0.58 sec)
3. b a
Display
o
e l ฺb these countries has a capital city record associated with it and the other does not, but both
( ya countries must appear in the query output. Use appropriate aliases for the columns in the
resultset. Compare your statement and results to those shown below:
mysql> SELECT co.Name AS CountryName, ci.Name AS CityName
-> FROM Country AS co
-> LEFT JOIN City AS ci
-> ON co.Capital = ci.ID
-> WHERE co.Code IN ('CHE', 'ATA');
+-------------+----------+
| CountryName | CityName |
+-------------+----------+
| Antarctica | NULL |
| Switzerland | Bern |
+-------------+----------+
2 rows in set (0.02 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 6
4. Repeat previous step using a RIGHT JOIN to base the query on the City table and
compare the results.
Compare your statement and results to those shown below:
mysql> SELECT co.Name AS CountryName, ci.Name AS CityName
-> FROM Country AS co
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-> RIGHT JOIN city AS ci


-> ON co.Capital = ci.ID
-> WHERE co.Code IN ('CHE', 'ATA');
+-------------+----------+
| CountryName | CityName |
+-------------+----------+
| Switzerland | Bern |
+-------------+----------+
1 row in set (0.00 sec)
− These results include only records from the City table with matching records in the
Country table. to
Note: Keep your mysql session open for the next practice.
A 1n ense
C 3% le lic
n c l% erab
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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 7
Practice 12-2: Creating Queries Requiring Joins
Overview
In this practice, you construct the appropriate join query to answer each of the following
questions.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Duration
This practice takes approximately 30 minutes to complete.

Tasks
Use the world_innodb database to answer the following questions:
1. Which languages are spoken in the country of Sweden? Include the country name and
language in the result.
to
2. Which countries have entries in the CountryLanguage table? Include the country name
A 1n ense
and each of its languages in the output.
Hint: Use an INNER JOIN to ignore records that do not match. C 3% le lic
n c l% erab
2 0I ansf
3. Modify the query used in the previous step to include every country, even when there is no
corresponding entry in the CountryLanguage table. What is the difference in the output?
Hint: Use the LEFT JOIN statement instead. illa
% n-tr
4. Which country has the largest number o ofb ad a no ฺ
cities?
BBY clauses aswith your e to display the correct
idquery
Hint: Use the GROUP BY and ORDER r a ) h u
information.
j a nd yฺmx ent G
5. Which countries have A late least aoned city with d than 7 million (7 000 000) inhabitants?
tumore
2 0 ฺ u S
e l % rrsoeothat each
Hint: Use DISTINCT
t h s appears in the output only once.
icountry
Use the PetsYa database
@ coto answer
u se the following questions:
6. Show the i a
llstructure of all tables in the Pets database.
7. Which a d
b owners have female pets, and a phone number starting with 1555?
l ฺ b o
8. What are the names and types of all pets, and their corresponding owner IDs?
( yae a. Answer the above query with a RIGHT JOIN of the pet_info and pet_types
tables.
b. Answer the above query with a LEFT JOIN of the pet_info and pet_types tables.
c. Answer the above query with an INNER JOIN of the pet_info and pet_types
tables.
d. What is the difference in the output?
9. If you are not going to complete the optional practice, exit the mysql client.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 8
Solutions 12-2: Creating Queries Requiring Joins
Tasks
Use the world_innodb database to answer the following questions:
1. Which languages are spoken in the country of Sweden? Include the country name and
language in the result.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Compare your statement and results to those shown below:


mysql> SELECT Name, Language
-> FROM CountryLanguage, Country
-> WHERE CountryCode = Code
-> AND Name = 'Sweden';
+--------+---------------------------+
| Name | Language |
+--------+---------------------------+

to
| Sweden | Arabic |

1n ense
| Sweden | Finnish |
| Sweden | Norwegian |
A
| Sweden | Southern Slavic Languages |
C 3% le lic
l% erab
| Sweden | Spanish |
| Sweden | Swedish |
n c
+--------+---------------------------+
2 0I ansf
6 rows in set (0.00 sec)
l l a % n-tr
2. i
ad a notable?ฺ Include the country name
Which countries have entries in the CountryLanguage
and each of its languages in the output.ob
r a B those h as shown u de
ibelow:
Compare your statement and )
results to
ndLanguage x nt G
mysql> SELECT Name, j a
le ady tude ฺ m
-> FROM
2 0 A ฺuCountry
CountryLanguage
S
l % r e o h i s
or se t = Code;
ae-> ONcCountryCode
-> INNER JOIN
Y @ u
i l l a
+---------------------------------------+---------------------------+
|d
oba+---------------------------------------+---------------------------+
Name | Language |

e l ฺb | Aruba | Dutch |
( ya | Aruba
| Aruba
|
|
English
Papiamento
|
|
| Aruba | Spanish |
| Afghanistan | Balochi |
...
| Djibouti | Somali |
| Dominica | Creole English |
| Dominica | Creole French |
| Denmark | Arabic |
| Denmark | Danish |
...
| Niger | Tamashek |
| Norfolk Island | English |
| Nigeria | Bura |
...
| Yugoslavia | Slovak |
| South Africa | Afrikaans |
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 9
... |
| Zambia | Tongan |
| Zimbabwe | English |
| Zimbabwe | Ndebele |
| Zimbabwe | Nyanja |
| Zimbabwe | Shona |
+---------------------------------------+---------------------------+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

984 rows in set (0.00 sec)


3. Modify the query used in the previous step to include every country, even when there is no
corresponding entry in the CountryLanguage table. What is the difference in the output?
a. Compare your statement and results to those shown below:
mysql> SELECT Name, Language
-> FROM Country
-> LEFT JOIN CountryLanguage
-> ON CountryCode = Code;
+---------------------------------------+---------------------------+
to
1n ense
| Name | Language |
+---------------------------------------+---------------------------+
A
| Aruba | Dutch
C 3% le lic
|

l% erab
...
| Antarctica | NULL
n c |
| French Southern territories | NULL
2 0I ansf |
...
i l
| South Georgia/South Sandwich Islands | NULL l a% on-tr |
| Saint Helena
o bad s a n eฺ
| English |
...
r a B ha uid
| Zimbabwe
d
n yฺm ent x ) | Shona
G |

l e j a
+---------------------------------------+---------------------------+
990 rows in set (0.00 sec)
0A oฺinuthe
b. What is the2difference
adoutput?
S ud number of rows in the result is different. The
tThe
e
previousl r r e 984throws
%query returned is and this task returned 990 rows. This is because this
Y a cocountries
result includes
@ u sewith no assigned language, indicated by a null value in the
i lla column.
Language
d
4. ba country has the largest number of cities?
oWhich
e l ฺb Compare your statement and results to those shown below:
( ya mysql> SELECT Country.Name, COUNT(City.Name) AS Cities
-> FROM Country
-> INNER JOIN City
-> ON City.CountryCode = Country.Code
-> GROUP BY Country.Name
-> ORDER BY Cities DESC
-> LIMIT 1;

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 10
+-------+--------+
| Name | Cities |
+-------+--------+
| China | 363 |
+-------+--------+
1 row in set (0.01 sec)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

5. Which countries have at least one city with more than 7 million (7 000 000) inhabitants?
Compare your statement and results to those shown below:
mysql> SELECT DISTINCT Country.Name FROM Country
-> INNER JOIN City ON Code = CountryCode
-> WHERE City.Population > 7000000;
+--------------------+
| Name |
+--------------------+
| Brazil |
| China | to
| United Kingdom |
A 1n ense
3% le lic
| Indonesia |
| India
| Japan
|
|
C
l% erab
n c
| South Korea
| Mexico
|
| 2 0I ansf
| Pakistan |
i l l a% on-tr
bad s a n eฺ
| Russian Federation |
| Turkey | o
B ha
| United States |
d r a x ) G uid
+--------------------+
j a n yฺm ent
l e
12 rows in set (0.00 sec)
tudquestions:
athedfollowing
Use the Pets database
2 0Ato answerฺ u S
l % ofrralleotables tinhthe
6. Show theestructure is Pets database.
Y a your
Compare @ costatement
u seand results to those shown below:
d i lla USE Pets
baDatabase changed
mysql>

lฺ b o
y a e
( mysql> DESC pet_info;
+---------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+----------------+
| pID | int(11) | NO | PRI | NULL | auto_increment |
| pName | varchar(20) | NO | | NULL | |
| pGender | enum('M','F') | YES | | NULL | |
| pBday | date | YES | | NULL | |
| pDday | date | YES | | NULL | |
| oID | int(11) | NO | | NULL | |
| tID | int(11) | NO | | NULL | |
+---------+---------------+------+-----+---------+----------------+
7 rows in set (0.05 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 11
mysql> DESC owners;
+--------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+----------------+
| oID | int(11) | NO | PRI | NULL | auto_increment |
| oName | varchar(20) | NO | | NULL | |
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| oPhone | char(11) | NO | | NULL | |


+--------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> DESC pet_types;


+-----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+----------------+
| tID | int(11) | NO | PRI | NULL | auto_increment |
| pType | varchar(20) | NO | | NULL | |
| pCategory | varchar(20) | NO | | NULL | |
to
1n ense
+-----------+-------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)
A
7. 3% le lic
Which owners have female pets, and a phone number starting with 1555?
C
Compare your statement and results to those shown below:
n c l% erab
mysql> SELECT owners.oName 2 0I ansf
-> FROM owners
i l l a% on-tr
-> JOIN pet_info
o bad s a n eฺ
a B ha
-> ON owners.oID = pet_info.oID
r uid = 'F';
-> WHERE oPhone d
n yฺm ent
LIKE x )
'1555%' G
AND pGender
l e j a
ad Stud
+--------+
| oName | 0A u
2 o ฺ
el% |corre e this
+--------+
| a
Harold
Y
| Gwen
@| us
i l l a
+--------+
2d
a
o b rows in set (0.00 sec)

e l
8. ฺb What are the names and types of all pets, and their corresponding owner IDs?
( ya a. Answer the above query with a RIGHT JOIN of the pet_info and pet_types
tables. Compare your statement and results to those shown below:
mysql> SELECT oID, pName, pet_types.pType
-> FROM pet_info
-> RIGHT JOIN pet_types
-> ON pet_info.tID = pet_types.tID;
+------+----------+---------+
| oID | pName | pType |
+------+----------+---------+
| 1 | Fluffy | Cat |
| 2 | Claws | Cat |
| 5 | Opus | Cat |
| 2 | Scruffy | Cat |
| 3 | Fang | Dog |
| 2 | Chirpy | Parrot |
| 2 | Whistler | Canary |

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 12
| NULL | NULL | Snake |
| 6 | Chewy | Hamster |
| NULL | NULL | Ferret |
| 3 | Slim | Iguana |
+------+----------+---------+
11 rows in set (0.00 sec)
− The result includes all pets in pet_info and two records without a name or owner,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

indicated by null values in those columns. The right join bases the query on the
pet_types table so every pet type appears in the query, regardless of whether
there is a corresponding entry in the pet_info table.
b. Answer the above query with a LEFT JOIN of the pet_info and pet_types tables.
Compare your statement and results to those shown below:
mysql> SELECT oID, pName, pet_types.pType
-> FROM pet_info
-> LEFT JOIN pet_types
-> ON pet_info.tID = pet_types.tID; to
+-----+----------+---------+
A 1n ense
3% le lic
| oID | pName | pType |
+-----+----------+---------+
| 1 | Fluffy | Cat | C
l% erab
n c
0I ansf
| 2 | Claws | Cat |
| 3 | Fang | Dog | 2
| 2 | Chirpy | Parrot |
i l l a% on-tr
bad s a n eฺ
| 2 | Whistler | Canary |
| 3 | Slim | Iguana |
o
B ha
| 6 | Chewy | Hamster |
d r a x ) G uid
|
|
5 | Opus | Cat
2 | Scruffy | Cat j a n yฺm ent
|
|
l e
2 0A oฺuad s Stud
+-----+----------+---------+
9 rows in set (0.00 sec)
− a
Theel% o r re an entry
result includes
e t hi for each pet in the pet_info table. It does not include
@ c pet
Y the unassigned ustypes (Snake and Ferret) from the previous query because the
i l
left l a
join bases the query on the pet_info table.
a d
l ฺboc.b Answer the above query with an INNER JOIN of the pet_info and pet_types
ya e tables. Compare your statement and results to those shown below:
( mysql> SELECT oID, pName, pet_types.pType
-> FROM pet_info
-> INNER JOIN pet_types
-> ON pet_info.tID = pet_types.tID;
+-----+----------+---------+
| oID | pName | pType |
+-----+----------+---------+
| 1 | Fluffy | Cat |
| 2 | Claws | Cat |
| 3 | Fang | Dog |
| 2 | Chirpy | Parrot |
| 2 | Whistler | Canary |
| 3 | Slim | Iguana |
| 6 | Chewy | Hamster |
| 5 | Opus | Cat |
| 2 | Scruffy | Cat |
+-----+----------+---------+
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 13
9 rows in set (0.00 sec)
− The results are identical to a LEFT JOIN, and ignore all non-matching records.
9. If you are not going to complete the optional practice, exit the 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 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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 14
Optional Practice 12-3: Additional Join Practice
Overview
In this practice, you continue to test your knowledge of joins by using your answers from the
previous practice.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Duration
This practice takes approximately 15 minutes to complete.

Tasks
Answer the following questions using the world_innodb database and your answers from the
previous practice:
1. From Task 1 in 12-2: Does adding DISTINCT make a difference? Why?
2. From Task 1 in 12-2: How do you list the languages in reverse alphabetical order?
3. From Task 2 in 12-2: How do you limit the results to French-speaking countries?
to
1n ense
4. From Task 3 in 12-2: How do you limit the results to countries with no matching entries in
A
the CountryLanguage table?
C 3% le lic
n c l% erab
5. From Task 3 in 12-2: Which table are the nulls from? Why do they appear in the results?

that have no matches in the Country table? 2 0I ansf


6. From Task 3 in 12-2: What join displays all the records in the CountryLanguage table

i l l a% n - tr keyword?
7.
b a d a no
From Task 5 in 12-2: What happens if you remove the DISTINCT
8. Exit the mysql client.
B o as i d eฺ
n d ra x) h t Gu
l e ja dyฺm den
2 0A oฺua s Stu
a el% corre e thi
Y @ us
l l a
b a di
l ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 15
Solutions 12-3: Additional Join Practice
Tasks
1. From Task 1 in 12-2: Does adding DISTINCT make a difference? Why?
Compare your statement and results to those shown below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT DISTINCT Name, Language


-> FROM CountryLanguage, Country
-> WHERE CountryCode = Code
-> AND Name = 'Sweden';
+--------+---------------------------+
| Name | Language |
+--------+---------------------------+
| Sweden | Arabic |
| Sweden | Finnish |
| Sweden | Norwegian |
| Sweden | Southern Slavic Languages | to
| Sweden | Spanish |
A 1n ense
3% le lic
| Sweden | Swedish |
+--------+---------------------------+
6 rows in set (0.00 sec) C
l% erab
n c f are unique.
− Adding DISTINCT does not change the result because
2 0I atheall
n srows
2. From Task 1 in 12-2: How do you list the languages% in reversetralphabetical order?
i l l a n -
b a d shown
Compare your statement and results to those
a nobelow:
mysql> SELECT Name, Language B o as i d eฺ
d ra x) Country h Gu
n
-> FROM CountryLanguage,
ja dyฺm= Code e n t
e
-> WHERE lCountryCode
a Stud
2
-> AND 0A
Name =ฺu'Sweden'
e l eoLanguage
%ORDERrrBY t h is DESC;
co use
->
Y a
+--------+---------------------------+
@
lla | Language
d i
| Name |

oba| Sweden | Swedish


+--------+---------------------------+
|
e l ฺb | Sweden | Spanish |
( ya | Sweden | Southern Slavic Languages |
| Sweden | Norwegian |
| Sweden | Finnish |
| Sweden | Arabic |
+--------+---------------------------+
6 rows in set (0.02 sec)
3. From Task 2 in 12-2: How do you limit the results to French-speaking countries?
Compare your statement and results to those shown below:
mysql> SELECT Name, Language
-> FROM CountryLanguage
-> LEFT JOIN Country
-> ON CountryCode = Code
-> WHERE Language = 'French';
+---------------------------+----------+
| Name | Language |

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 16
+---------------------------+----------+
| Andorra | French |
| Burundi | French |
| Belgium | French |
| Canada | French |
| Switzerland | French |
| France | French |
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| Guadeloupe | French |
| Haiti | French |
| Italy | French |
| Lebanon | French |
| Luxembourg | French |
| Monaco | French |
| Madagascar | French |
| Martinique | French |
| Mauritius | French |
| Mayotte | French |
| New Caledonia | French |
| French Polynesia | French |
to
| Rwanda | French
| Saint Pierre and Miquelon | French
|
| A 1n ense
| Sao Tome and Principe | French |
C 3% le lic
| Seychelles | French |
n c l% erab
0I ansf
| United States | French |
| Virgin Islands, U.S. | French |
2
| Vanuatu | French |
i l l a% on-tr
bad s a n eฺ
+---------------------------+----------+
25 rows in set (0.02 sec)
o
B the results id with no matching entries in
4. From Task 3 in 12-2: How do youalimit
d r x ) ha toG u
countries
the CountryLanguage table?
j a n yฺm ent
Compare your A l e
statement
tutodthose shown below:
aandd results
2 0 ฺ u
o Language S
mysql>%SELECT e
e l r r Name,
t h is
Ya -> co Country
FROM
@ u s e
i a LEFT JOIN CountryLanguage
ll->
d
oba
-> ON CountryCode = Code

e l ฺb -> WHERE Language IS NULL;


( ya +----------------------------------------------+----------+
| Name | Language |
+----------------------------------------------+----------+
| Antarctica | NULL |
| French Southern territories | NULL |
| Bouvet Island | NULL |
| Heard Island and McDonald Islands | NULL |
| British Indian Ocean Territory | NULL |
| South Georgia and the South Sandwich Islands | NULL |
+----------------------------------------------+----------+
6 rows in set (0.00 sec)
5. From Task 3 in 12-2: Which table are the nulls from? Why do they appear in the results?
− This is a left join, so the results are from the Country table.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 17
6. From Task 3 in 12-2: What join displays all the records in the CountryLanguage table that
have no matches in the Country table?
Compare your statement and results to those shown below:
mysql> SELECT Name, Language
-> FROM Country
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-> RIGHT JOIN CountryLanguage


-> ON CountryCode = Code
-> WHERE Language IS NULL;
Empty set (0.00 sec)
7. From Task 5 in 12-2: What happens if you remove the DISTINCT keyword?
Compare your statement and results to those shown below:
mysql> SELECT Country.Name FROM Country
-> INNER JOIN City ON Code = CountryCode
-> WHERE City.Population > 7000000; to
+--------------------+
A 1n ense
3% le lic
| Name |
+--------------------+
| Brazil | C
l% erab
n c
| China
| China
|
| 2 0I ansf
| United Kingdom |
i l l a% on-tr
bad s a n eฺ
| Indonesia |
| India |
o
B ha
| India |
d r a x ) G uid
| Japan
j a n yฺm ent
|
| South Korea
l e |
| Mexico
2 0A oฺuad s Stud
|

el% corre e thi


| Pakistan |
| Russian Federation |
a
Y @
| Turkey
l l a
| United States us |
|

b a di
+--------------------+

l ฺb o 14 rows in set (0.00 sec)

ya e − Without DISTINCT, two duplicate country rows appear in the results. This is
( because these countries have more than one city with a population of 7 000 000 or
above.
8. Exit the mysql client.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Joining Tables


Chapter 12 - Page 18
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
c b
l% era13:
Practices for n Lesson
f
Tablea% 20I trans
Subqueries
d i ll non-
a 13a
obChapter
B a s i d eฺ
n d ra x) h t Gu
l e ja dyฺm den
2 0A oฺua s Stu
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Table Subqueries


Chapter 13 - Page 1
Practices for Lesson 13: Overview
Practices Overview
These practices test your knowledge of subqueries. They target the Windows operating system,
provided in Oracle classrooms. For non-Oracle classrooms, you might need to adjust file
locations.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Assumptions
• You have installed and configured the MySQL server.
• You have created and populated the world_innodb database.
• You can access the mysql client from a command-line prompt.
• You can access MySQL Workbench if you choose to complete the practices using this
tool.
Note: In this practice, the first letters of table names are in uppercase. Windows is not case-
sensitive but some operating systems are, so it is a good practice to use proper capitalization. to
1n ense
The SQL statements are all in uppercase for clarity, but this is not required.
A
C 3% le lic
n c l% erab
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Table Subqueries


Chapter 13 - Page 2
Practice 13-1: Performing Different Types of Subqueries
Overview
In this practice, you use subqueries in the FROM and WHERE clauses of a SELECT statement.

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

This practice takes approximately 20 minutes to complete.

Tasks
1. Write a query with a non-correlated subquery that retrieves the first three cities in the City
table with a population larger than New York. List the results in order of population.
a. The first step is to write the subquery, which must not be dependent on the outer
query. The subquery syntax is as follows:
SELECT Population
FROM City
to
WHERE Name = 'New York'
A 1n ense
b. Run the subquery. This returns the value the outer query needs in 3 its% l ic
WHERE condition.
e
c. Write the outer query to complete the statement. l C
% rabl
c
2. 0In asubquery
Write a query that retrieves all Nordic countries, with a correlated
2 n sfe that calculates
the number of cities per country. The outer query syntax
l l r
a% ois nas-tfollows:
i
SELECT Country.Name,
o bad s a n eฺ
(<subquery>)
r a B ha uid
AS CityCount d
n yฺm ent x ) G
FROM Country eja
l tud
WHERE Region2 ฺ uad sCountries'
0A = o'Nordic S
a. Writeethe
a l%subquery
o r e t hi the full statement and execute it.
reto complete
b. Y @ c correlated
Is the subquery us or non-correlated?
3. Write d l l a
i with a non-correlated subquery that retrieves all the languages spoken in
a query
b a
oSingapore, in descending alphabetical order of Language. The subquery syntax is as
e l ฺb follows:
( ya SELECT Code
FROM Country
WHERE Name='Singapore'
a. Run the subquery. This returns the value the outer query uses in its WHERE condition.
b. Write the outer query to complete the statement.
Note: Keep your mysql session open for the next practice.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Table Subqueries


Chapter 13 - Page 3
Solutions 13-1: Performing Different Types of Subqueries
Tasks
1. Write a query with a non-correlated subquery that retrieves the first three cities in the City
table with a population larger than New York. List the results in order of population.
a. Log in to the mysql client and set world_innodb as the default database:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

cmd> mysql -uroot -poracle


...
mysql> USE world_innodb;
Database changed.
b. Run the subquery. This returns the value the outer query needs in its WHERE condition.
Compare your statement and results to those shown below:
mysql> SELECT Population
-> FROM City
to
-> WHERE Name = 'New York';
A 1n ense
3% le lic
+------------+
| Population |
+------------+ C
l% erab
n c
0I ansf
| 8008278 |
+------------+ 2
1 row in set (0.02 sec)
i l l a% on-tr
− The subquery returns the population
o b aofd NewaYorkn City.ฺ
c. Write the outer query to complete
to those shown below: dra ) h as Compare
Bthe statement. u ide your statement and results
j a nNameyฺmx ent G
le ad
mysql> SELECT
A tud
2 0
-> ฺ
FROM City u S
e l r r eo Population
% -> WHERE t h is >
Ya @-> co u(SELECT
se Population
d i lla -> FROM City
o b a -> WHERE Name = 'New York')
e l ฺb
ya
-> ORDER BY Population
( -> LIMIT 3;
+------------------+
| Name |
+------------------+
| Moscow |
| Ciudad de México |
| Istanbul |
+------------------+
3 rows in set (0.00 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Table Subqueries


Chapter 13 - Page 4
2. Write a query that retrieves all Nordic countries, with a correlated subquery that calculates
the number of cities per country. The outer query syntax is as follows:
SELECT Country.Name,
(<subquery>)
AS CityCount
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

FROM Country
WHERE Region = 'Nordic Countries'
a. Write the subquery to complete the full statement and execute it. Compare your
statement and results to those shown below:
mysql> SELECT Country.Name,
-> (SELECT COUNT(*)
-> FROM City
-> WHERE CountryCode = Country.Code)
-> AS CityCount
to
-> FROM Country
A 1n ense
-> WHERE Region = 'Nordic Countries';
+------------------------+-----------+ C 3% le lic
+------------------------+-----------+ Inc
| Name | CityCount | l% erab
52|0 n s f
a%7 |on-tra
| Denmark |
| Finland |
| d i l l 1n|
| Faroe Islands
| Iceland b a
o | as 15 ||ideฺ
| a
| Norway B
raMayenx|) h t G1u|
n
| Svalbard and Jan d
| Sweden
l e ja dyฺm | den 15 |
A ฺua Stu
0in
+------------------------+-----------+
2
%
7 rows
l r e o (0.06hissec)
set
− a
Y
e aclist
Returns orof thesseven
e t countries in the Nordic Region, and the number of cities
@ with each
associated
llasubquery u country
i
b. Isdthe correlated or non-correlated?

l ฺb oba − It is a correlated subquery, because it requires information from the outer query (the
ya e Country table).
( 3. Write a query with a non-correlated subquery that retrieves all the languages spoken in
Singapore, in descending alphabetical order of Language. The subquery syntax is as
follows:
SELECT Code
FROM Country
WHERE Name='Singapore'

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Table Subqueries


Chapter 13 - Page 5
a. Run the subquery. This returns the value the outer query needs in its WHERE condition.
Compare your statement and results to those shown below:
mysql> SELECT Code
-> FROM Country
-> WHERE Name='Singapore';
+------+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| Code |
+------+
| SGP |
+------+
1 row in set (0.00 sec)
− The subquery returns a scalar value containing the country code for Singapore.
b. Write the outer query to complete the statement. Compare your statement and results
to those shown below:
mysql> SELECT Language
-> FROM CountryLanguage to
-> WHERE CountryCode =
A 1n ense
-> (SELECT Code
C 3% le lic
-> FROM Country
n c l% erab
-> WHERE Name='Singapore')
2 0I ansf
-> ORDER BY Language DESC;
i l l a% on-tr
ad a n ฺ
+----------+
| Language |
o b
+----------+
r a B has uide
| Tamil |
| an
d mx) nt G
| Malay
| Chinese le|
A
j
a d yฺ ude
2 0 oฺu s St
+----------+

a e3l% o r e (0.00
rows inrset
e t hisec)
Note: Keep Y your @ c session
mysql us open for the next practice.
l l a
b a di
l ฺ b o
( yae

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Table Subqueries


Chapter 13 - Page 6
Practice 13-2: Performing Advanced Subqueries
Overview
In this practice, you construct advanced subqueries to answer specific questions.

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

This practice takes approximately 45 minutes to complete.

Tasks
1. Which continents have countries where more than 50% of the population speaks English?
Does this query use a correlated subquery? Why or why not?
Hint: Use a subquery in the WHERE clause.
2. List the countries in the European continent where the inhabitants speak Spanish. Can you
write this query without a subquery?
Hint: Use a subquery to find the codes for the countries where they speak Spanish, and
to
1n ense
then compare it to the codes of European countries to filter out all other continents.
A
3% le lic
Hint: Use a subquery in the WHERE clause. Use the AND keyword to filter by both continent
and country code values. C
l% erab
3. c
Which country has the most populous city in the world?
n
2 0I ansf
Hint: Join the Country and City tables to get the population and city information.
i l l a% on-tr
Hint: Use a subquery to determine the city with the largest population, and then retrieve the
associated country name.
o bad s a n eฺ
4. B ha uid
The following statement uses a correlated subquery to find the South American country with
r a
d
the smallest population: x ) G
jan dyc1ฺm dent
SELECT * FROMleCountry
2 0A o=ฺu'South tu
a SAmerica'
WHERE Continent
l% orre= thi
ePopulation s
a
AND
Y (SELECT se
c MIN(Population)
@ u
llaFROM Country c2
d i
l ฺb oba WHERE c2.Continent = c1.Continent)\G
ya e a. Execute the query to display the results.
( b. Run the subquery independently of the main query. What is the result?
5. Rewrite the previous statement (from task 4) using a non-correlated subquery. Explain what
makes the new subquery non-correlated. For extra credit, rewrite the full query by using
aliases for the table names.
6. Exit the mysql client.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Table Subqueries


Chapter 13 - Page 7
Solutions 13-2: Performing Several Advanced Subqueries
Tasks
1. Which continents have countries in which more than 50% of the population speaks English?
a. First, write and test the subquery. Compare your statement and results to those shown
below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SELECT CountryCode


-> FROM CountryLanguage
-> WHERE Language='English'
-> AND Percentage > 50;
+-------------+
| CountryCode |
+-------------+
| AUS |
| BLZ |
| BMU | to
| CAN |
A 1n ense
3% le lic
| GBR |
| GIB
| IRL
|
| C
l% erab
n c
0I ansf
| NZL |
| TTO | 2
| USA |
i l l a% on-tr
bad s a n eฺ
| VIR |
+-------------+
o
B ha
d a
11 rows in set (0.00 sec)
r x ) G uid
n yyour
b. Complete the query. Compare m statementt and results to those shown below:
l e j a ฺ d e n
mysql> A
SELECT
0 FROMoCountry d
ua s Stu
DISTINCT Continent
2 ฺ
a el% ->
->
o r re Code
e t hiIN
Y @-> c us
WHERE

i a
ll -> (SELECT CountryCode
d
oba
FROM CountryLanguage

e l ฺb -> WHERE Language='English'


( ya ->
+---------------+
AND Percentage>50);

| Continent |
+---------------+
| Oceania |
| North America |
| Europe |
+---------------+
3 rows in set (0.02 sec)
c. Does this query use a correlated subquery? Why or why not?
− No. The subquery can run alone with no dependency on the outer query.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Table Subqueries


Chapter 13 - Page 8
2. List the countries in the European continent where the inhabitants speak Spanish.
a. First, write and test the subquery. Compare your statement and results to those shown
below:
mysql> SELECT CountryCode
-> FROM CountryLanguage
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-> WHERE Language = 'Spanish';


+-------------+
| CountryCode |
+-------------+
| ABW |
| AND |
| ARG |
| BLZ |
| BOL |
| CAN |
...
| USA |
to
1n ense
| VEN |
| VIR |
A
+-------------+
C 3% le lic
abbelow:
28 rows in set (0.05 sec)
n c l% e r
0I ans
b. Complete the query. Compare your statement and results to f
those shown
mysql> SELECT Name 2
% n-tr
i l l a
-> FROM Country
b a d a no
-> WHERE Continent
B o as
= 'Europe'
i d eฺ
-> AND Code rIN
d a x) h Gu
j a n ฺ m e n t
->
l e (SELECT
y CountryCode
->
2 0A oFROM ฺ S tud
uadCountryLanguage
e l % -> rre WHERE t h s
iLanguage = 'Spanish')
a o
c ORDER
Y +---------+
-> e
sBY Name;
a @ u
a d ill| Name |
l ฺb ob +---------+

ya e | Andorra |
( | France |
| Spain |
| Sweden |
+---------+
4 rows in set (0.00 sec)
c. Can you write this query without a subquery?
− No.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Table Subqueries


Chapter 13 - Page 9
3. Which country has the most populous city in the world?
a. First, write and test the subquery. Compare your statement and results to those shown
below:
mysql> SELECT MAX(Population) FROM City;
+-----------------+
| MAX(Population) |
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

+-----------------+
| 10500000 |
+-----------------+
1 row in set (0.05 sec)
b. Complete the query. Compare your statement and results to those shown below:
mysql> SELECT Country.Name
-> FROM Country JOIN City
-> ON Country.Code=City.CountryCode
-> WHERE City.Population =
-> (SELECT MAX(Population) FROM City); to
+-------+
A 1n ense
| Name |
+-------+ C 3% le lic
| India |
n c l% erab
+-------+
2 0I ansf
1 row in set (0.03 sec)
l l a % n-tr
4. The following statement uses a correlated subquery
a i
d atonfind o the South American country with
the smallest population. b
o as e ฺ
a. Execute the query to display B
rathe results:h Gu i d
n d x )
Countryntc1
mysql> SELECT
e j a * FROM
l Continent y ฺ m e
-> A a d t =d
u
0 WHERE
ฺ u
2-> ANDeoPopulation s S= 'South America'
l %
e cor (SELECTr h i
t MIN(Population)
Ya @-> s e
i l l a -> u FROM Country c2
d
l ฺb oba -> WHERE c2.Continent = c1.Continent)\G
*************************** 1. row **************
ya e Code: FLK
( Name: Falkland Islands
Continent: South America
Region: South America
SurfaceArea: 12173.00
IndepYear: NULL
Population: 2000
LifeExpectancy: NULL
GNP: 0.00
GNPOld: NULL
LocalName: Falkland Islands
GovernmentForm: Dependent Territory of the UK
HeadOfState: Elisabeth II
Capital: 763
Code2: FK
1 row in set (0.01 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Table Subqueries


Chapter 13 - Page 10
b. Run the subquery independently of the main query. What is the result? Compare your
statement and results to those shown below:
mysql> SELECT MIN(Population)
-> FROM Country c2
-> WHERE c2.Continent = c1.Continent;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

ERROR 1054 (42S22): Unknown column 'c1.Continent' in 'where clause'


5. Rewrite the previous statement (from task 4) using a non-correlated subquery.
a. First, write and test the subquery. Compare your statement and results to those shown
below:
mysql> SELECT MIN(Population) FROM Country
-> WHERE Continent = 'South America';
+-----------------+
| MIN(Population) |
+-----------------+
| 2000 |
+-----------------+ to
1 row in set (0.00 sec)
A 1n ense
b. Complete the query. Compare your statement and results to those3 % below:
shown
e l ic
l C
% rabl
mysql> SELECT * FROM Country
c
-> WHERE Continent = 'South America'
2 0In ansfe
-> AND Population =
i l l a% on-tr
-> ad a n ฺ
(SELECT MIN(Population)
o b
-> B has uide
FROM Country
r a
->
n d
WHERE x ) =t 'South
Continent G America')\G
j a ฺ
leCode: aFLKdy tude
********************** m1. row n
***********************

2 0 A ฺu Falkland S Islands
l % r e o
Name:
h i s
e corRegion:eSouth t America
Ya @
Continent: South America
s
u 12173.00
i l l a SurfaceArea:
d
oba
IndepYear: NULL
Population: 2000
e l ฺb LifeExpectancy: NULL
( ya GNP: 0.00
GNPOld: NULL
LocalName: Falkland Islands
GovernmentForm: Dependent Territory of the UK
HeadOfState: Elisabeth II
Capital: 763
Code2: FK
1 row in set (0.00 sec)
c. Explain what makes the new subquery non-correlated.
− The subquery does not depend on the outer query, and can run independently of it.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Table Subqueries


Chapter 13 - Page 11
d. For extra credit, rewrite the full query by using aliases for the table names. Compare
your statement and results to those shown below:
mysql> SELECT * FROM Country c1
-> WHERE Continent = 'South America'
-> AND Population =
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-> (SELECT MIN(Population)


-> FROM Country c2
-> WHERE c2.Continent = c1.Continent)\G
********************** 1. row ********************
Code: FLK
Name: Falkland Islands
Continent: South America
Region: South America
SurfaceArea: 12173.00
IndepYear: NULL
Population: 2000
LifeExpectancy: NULL to
GNP: 0.00
A 1n ense
3% le lic
GNPOld: NULL
LocalName: Falkland Islands C
l% erab
c
GovernmentForm: Dependent Territory of the UK
n
HeadOfState: Elisabeth II
2 0I ansf
a% on-tr
Capital: 763
Code2: FK
i l l
1 row in set (0.02 sec)
o b ad a n ฺ
6. Exit the mysql client.
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
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Table Subqueries


Chapter 13 - Page 12
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
c b
l% era14:
Practices for n Lesson
f
2 0I ans
MySQL Graphical
a% on-tr User
i l l
o ad a n Tools
bInterface ฺ
B a s i d e
d h 14Gu
ra x)Chapter
j a n ฺ m e n t
l e y
2 0A oฺuad s Stud
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: MySQL Graphical User Interface Tools


Chapter 14 - Page 1
Practices for Lesson 14: Overview
Practices Overview
These practices test your knowledge of MySQL Graphical User Interface tools. They target the
Windows operating system provided in Oracle classrooms. For non-Oracle classrooms, you
might need to adjust file locations.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Assumptions
• You have installed and configured the MySQL server.
• You have created and populated the world_innodb database.
• You have created and populated the Pets database and have completed all the practice
steps that target this database, up to and including the Practices for Lesson 9, “Table
Data Manipulation.”
• MySQL Workbench 5.2 SE is installed.
• The MySQL Enterprise Monitor demonstration files are available in the to
D:\labs\demo\Enterprise_Monitor_demos directory.
A 1n ense
• The MySQL Workbench demonstration files are available in the
C 3% le lic
D:\labs\demo\Workbench_demos directory.
n c l% erab
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 ฺ b o
e
(ya

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: MySQL Graphical User Interface Tools


Chapter 14 - Page 2
Practice 14-1: Creating a Data Model by Using MySQL Workbench
Overview
In this practice, you use the Data Modeling module from Workbench to create an EER diagram
for the world_innodb database.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Duration
This practice takes approximately 20 minutes to complete.

Tasks
Note: There are no solutions for this practice.
1. Open MySQL Workbench from the MySQL programs group:
a. Open the Windows Start menu.
b. Select All Programs.
c. Select MySQL. to
d. Select MySQL Workbench 5.2 SE.
A 1n ense
− The primary MySQL Workbench window (Workbench Central) opens.
C 3% le lic
2. Open the Data Modeling module:
n c l% erab
0I ansf
Under the Data Modeling module heading, click the Create New EER Model link.
2
− The Model Editor opens in the MySQL Model
i l l a %tab and
n - tr the mydb default
displays
schema.
b a d a no
3. Delete the default schema: B o as i d eฺ
a. Click the mydb tab in the d
n ra Schemata
Physical x ) h panel.t G u
e
b. Click the delete button
l mright ofethe
ja(-) atdtheyฺfar n panel header.
0A disappears d
u Physical Schemata panel.
c. The mydb 2 schema
o ฺ ua sfromStthe
4. el% corre database
Add the world_innodb
a e thi schema to the Physical Schemata panel:
a. YClick the@ s on the panel header. A new window called new_schema1
add buttonu(+)
l l a
b a di at the bottom of the screen.
appears

l ฺb ob. Enter world_innodb in the Name field of the new schema window. The schema
ya e name gets updated in the Physical Schemata panel and the new schema window tab
( header as you type.
c. Click the close button (X) in the new schema window.
d. A message box appears, asking if you want to rename all schema occurrences. Click
Yes.
e. You have added the world_innodb schema to the Physical Schemata panel.
5. Import the world_innodb database data and create an EER diagram:
a. Select the File > Import > Reverse Engineer MySQL Create Script menu option.
− The Reverse Engineer MySQL Script dialog box appears.
b. On the Input and Options page:
− Click Browse and navigate to the world_innodb.sql file in the D:\labs
directory.
− Select LATIN1 from the File Encoding list.
− Select the “Place imported objects on a diagram” check box.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: MySQL Graphical User Interface Tools


Chapter 14 - Page 3
c. Click the Execute button.
− The Reverse Engineering Progress page displays “Import Finished. Finished
parsing MySQL SQL script”.
d. Click Next
− The Results page displays “SQL Import Finished Successfully”.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

e. Click Finish
− You have created a new EER diagram for the world_innodb database.
6. Review the new world_innodb EER diagram:
a. The tables appear in the center of the canvas. Drag them to different parts of the
canvas so you can see them all clearly.
b. Confirm that the tables and their column definitions match those in the SQL input file.
7. Examine the table relationships and foreign keys:
a. Move the mouse cursor over the relationship line between the Country and
CountryLanguage tables. This highlights the line and the table columns that
participate in the relationship. to
b. Double-click the relationship line. A 1n ense
C
− The Relationship window opens below the EER diagram. 3% le lic
c l% erab
− Click the Foreign Key tab at the bottom of the Relationship Window and review the
n
relationship details. 2 0I ansf
− Close the Relationship window. i l l a% on-tr
bad s a n eฺ
c. Repeat steps a and b to examine the relationship between the Country and City
o
tables.
r a B ha uid
d
n yฺm entx ) G
d. Close the EER diagram tab with the close button (X) to the right of the tab name.
l e j a
0A oฺuad s Stud
8. View the table information:
2
a. Click the MySQL Model tab at the top of the Workbench window.
a el% corre e thi
b. Double-click the City table icon in the world_innodb schema. The City table
Y @ us
window appears below the Physical Schemata panel.
l l a
b a di
c. Click on each of the following tabs at the bottom of the City table window to review the

l ฺb o table settings: Columns, Indexes, Foreign Keys, Triggers, Partitioning, Options, Inserts,

ya e and Privileges.
( d. Repeat steps a, b, and c for the Country and CountryLanguage tables.
e. Close the City table window.
9. Modify the City table:
a. Double-click the City table icon in the world_innodb schema window.
b. In the Columns tab:
− Double-click the Name column under Column Name.
− Change the name of the column to City_Name.
c. Close the City table window, which saves the change.
10. Export the world_innodb database to a SQL script:
a. Select the File > Export > Forward Engineer SQL CREATE Script menu option.
− The Forward Engineer SQL Script dialog box appears.
b. On the SQL Export Options page:

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: MySQL Graphical User Interface Tools


Chapter 14 - Page 4
− Set the Output SQL Script File to D:\labs\world_innodb_copy.sql.
− Select the following options:
• Generate DROP Statement Before Each CREATE Statement
• Do Not Create Users, Only Export Privileges
• Generate INSERT Statements For Tables
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

− Click Next
c. On the SQL Object Export Filter page:
− Select Export MySQL Table Objects
− Click Next
d. On the Review SQL Script page:
− Note that the contents are in the form of a SQL statement file, like the original
world_innodb.sql file.
− Find the CREATE TABLE statement for the City table and confirm that your column
name change (from Name to City_Name) is included. to
− Click Finish. A 1n ense
e. Open the D:\labs\world_innodb_copy.sql file in Notepad++3and % examine
e l icthe
content. l C
% rabl
c
11. Save the model:
2 0In ansfe
a. Select the File > Save Model As menu option.a%
i l l n - tr
a d a no
b. Save the model as D:\labs\world_innodb_copy.mwb.
b
12. Close the Data Modeling window: Bo a s i d eฺ
Click the close button (X)d
a
torthe rightxof
h MySQL
) the G uModel tab name.
n
jawindow ฺm leaving e t
n the MySQL Workbench window open.
− The MySQL Model l e d ycloses, d
u practice.
0A oฺuopen
Note: Keep MySQL2Workbench
a for the
s S tnext
a el% corre e thi
Y @ us
l l a
b a di
l ฺ b o
( yae

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: MySQL Graphical User Interface Tools


Chapter 14 - Page 5
Practice 14-2: Creating a Server Instance by Using MySQL Workbench
Overview
In this practice, you use the Workbench Server Administration module to create a new server
instance for the world_innodb database.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Duration
This practice takes approximately 20 minutes to complete.

Tasks
Note: There are no solutions for this practice.
1. Open the Server Administration module:
From the Workbench Central window, under the Server Administration module
heading, click New Server Instance.
− The Create New Server Instance Profile dialog box appears.
to
2. Create a new server profile:
A 1n ense
a. On the Specify Host Machine page:
C 3% le lic
− Select the localhost radio button
n c l% erab
− Click Next
2 0I ansf
b. On the Database Connection page:
l l a % n-tr
− For Connection Name, enter MyConnection
a i
d a no
b
o as eฺ
B
− For Default Schema, enter world_innodb i d
− Leave all other options
n das x ) h t Gu
ratheir defaults
− Click Next l e ja dyฺm den
2 0A appears,
ฺ uaprompting
S tuyou for the root user’s password. Enter oracle
c. A pop-up window
l%OK. orre o hi s
and e
a click
e t
c us page indicates that the connection was successful. Click
d. YThe Test@ DB Connection
ill
Next. a
a d
l oe.b On the Windows Management page, accept the defaults and click Next.
ฺb f.
ya e The Test Settings page reports that “Testing host machine settings is done.” Click
( Next.
g. In the Review Settings pop-up window, click Continue.
h. On the Complete Setup page:
− For Server Instance Name, enter mysql_profile
− Click Finish
3. Connect to the new MySQL server instance:
a. Click the Server Administration link just under the Server Administration module
heading.
b. In the Server Administration dialog box select “mysql_profile” and click OK.
c. A pop-up window appears, prompting you for the root user’s password. Enter oracle
and click OK.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: MySQL Graphical User Interface Tools


Chapter 14 - Page 6
4. View the server management options and settings for your new server instance, available
under the MANAGEMENT navigation menu on the left:
a. Select Server Status to show the name, details, and “health” status of the server.
b. Select Startup/Shutdown to show whether the server is running, and to stop or start the
server.
c. Select Status and System Variables to show the current settings of all status and
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

system variables.
d. Select Server Logs to show the type and location of the log file.
5. View the configuration options and settings for your new server instance, available under
the CONFIGURATION navigation menu on the left:
Select Options File to show a tabbed display of the various mysql configuration
options.
6. View the configuration options and settings for your new server instance, available under
the DATA EXPORT/RESTORE navigation menu on the left:
a. Select Data Export to show the various options for exporting data.
to
1n ense
b. Select Data Import/Restore to show the various options for importing data.
A
7. Close the Server Administration window:
Click the close button (X) in the Admin tab header. C 3% le lic
n c l% erab
8. Close MySQL Workbench:
Select the File > Exit menu option. 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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: MySQL Graphical User Interface Tools


Chapter 14 - Page 7
Practice 14-3: Viewing MySQL Enterprise Monitor Demonstrations
Overview
In this practice, you view a web-based demonstration that shows the primary features of
Enterprise Monitor.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Duration
This practice takes approximately 10 minutes to complete.

Tasks
Note: There are no solutions for this practice.
1. Open the MySQL Enterprise Monitor Dashboard demonstration in your web browser:
a. Go to the D:\labs\demo\Enterprise_Monitor_demos directory in Windows
Explorer, and double-click the memdashboard.html file.
b. The demonstration opens in the Mozilla Firefox web browser.
to
1n ense
c. Click the play button in the center of the page to start the demonstration
A
d. The demonstration lasts for approximately 3.5 minutes.
C 3% le lic
2.
l% erab
Open MySQL Enterprise Monitor Query Analyzer demonstration in your web browser:
n c
0I ansf
a. Go to the D:\labs\demo\Enterprise_Monitor_demos directory in Windows
2
i l l a% on-tr
Explorer, and double-click the memqueryanalyzer.html file.

bad s a n eฺ
b. The demonstration opens in the Mozilla Firefox web browser.
o
c. Click the play button in the center of the page to start the demonstration
B ha
r a ) uid
d. The demonstration lasts for approximately 5 minutes.
d x G
j a n yฺm ent
Note: If you are working outside of the Oracle classroom environment, you can access
l e
2 0A oฺuad s Stud
these demonstrations from the MySQL website at:
http://www.mysql.com/products/enterprise/demo.html
a el% corre e thi
Y @ us
l l a
b a di
l ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: MySQL Graphical User Interface Tools


Chapter 14 - Page 8
Optional Practice 14-4: Viewing the MySQL Workbench
Demonstration
Overview
In this practice, you view a web-based demonstration that shows the primary features of MySQL
Workbench.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Duration
This practice takes approximately 15 minutes to complete

Tasks
Note: There are no solutions for this practice.
1. Open the MySQL Workbench demonstration in your web browser.
a. Go to the D:\labs\demo\Workbench_demos directory in Windows Explorer, and
double-click the MySQL-Workbench.html file.
to
b. The demonstration opens in the Mozilla Firefox web browser.
A 1n ense
3% le lic
c. Click the play button in the center of the page to start the demonstration
C
n c l% erab
d. The demonstration lasts for approximately 14 minutes.

demonstration on YouTube at: 2 0I ansf


Note: If you are working outside of the Oracle classroom environment, you can access this

i l
http://www.youtube.com/watch?v=X_umYKqKaF0l 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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: MySQL Graphical User Interface Tools


Chapter 14 - Page 9
Optional Practice 14-5: Creating a Model for the Pets Database by
Using MySQL Workbench
Overview
In this practice, you make a backup of the Pets database, and then use the Data Modeling
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

module in Workbench to create an EER diagram for Pets.

Duration
This practice takes approximately 15 minutes to complete.

Tasks
Note: There are no solutions for this practice.
1. Create a backup SQL file of the Pets database with the mysqldump utility, in the D:\labs
directory.
a. Execute the following at the command prompt: to
cmd> mysqldump -uroot -poracle Pets > D:/labs/Pets.sql
A 1n ense
b. Open the D:\labs\Pets.sql backup file in Notepad++:
C 3% le lic
-- MySQL dump 10.13 Distrib 5.6.10, for Win64 (x86_64)
n c l% erab
--
2 0I ansf
-- Host: localhost Database: Pets
l l a % n-tr
a i
d a no
-- ------------------------------------------------------
b
o as
-- Server version 5.6.10-enterprise-commercial-advanced
eฺ
... B
ra x) h t Gu i d
n d m en
--
l e jafor tableyฺ`owners`
0A oฺua s Stud d
-- Table structure
-- 2
...
a e l% orre
e t hi
Y @
CREATE TABLE c `owners`
u s(
i
`oID`a
ll varchar(20)NULL
int(11) NOT AUTO_INCREMENT,
d
oba
`oName` NOT NULL,

e l ฺb `oPhone` char(11) NOT NULL,

( ya PRIMARY KEY (`oID`)


) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
...
-- Dumping data for table `owners`
--
...
INSERT INTO `owners` VALUES
(1,'Harold','15554159855'),(2,'Gwen','15551234567'),(3,'Benny','15553456789'),
(4,'Diane','15554567890'),(5,'Caryn','16163429988'),(6,'Olga','18563330000');
...
--
-- Table structure for table `pet_info`
--
...
CREATE TABLE `pet_info` (
`pID` int(11) NOT NULL AUTO_INCREMENT,
`pName` varchar(20) NOT NULL,
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: MySQL Graphical User Interface Tools


Chapter 14 - Page 10
`pGender` enum('M','F') DEFAULT NULL,
`pBday` date DEFAULT NULL,
`pDday` date DEFAULT NULL,
`oID` int(11) NOT NULL,
`tID` int(11) NOT NULL,
PRIMARY KEY (`pID`)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;


...
--
-- Dumping data for table `pet_info`
--
...
INSERT INTO `pet_info` VALUES (1,'Fluffy','F','2003-02-
04',NULL,1,1),(2,'Claws','M','2004-03-17',NULL,2,1),(4,'Fang','M','2000-08-
27',NULL,3,2),(6,'Chirpy','F','2008-09-11',NULL,2,3),(7,'Whistler','M','2007-
12-09',NULL,2,4),(8,'Slim','M','2006-04-
29',NULL,3,8),(9,'Chewy','F',NULL,NULL,6,6),(10,'Opus','F',NULL,NULL,5,1),(13,
'Scruffy','M','2008-04-17',NULL,2,1); to
...
A 1n ense
--
C 3% le lic
-- Table structure for table `pet_info2`
n c l% erab
0I ansf
--
... 2
CREATE TABLE `pet_info2` (
i l l a% on-tr
bad s a n eฺ
`pID` int(11) NOT NULL AUTO_INCREMENT,
o
B ha
`pName` varchar(20) NOT NULL,
r a uid
d x )
`pGender` enum('M','F') DEFAULT NULL,
n yฺm ent G
j a
`pBday` date DEFAULT NULL,
l e
0A oฺuad s Stud
`pDday` date DEFAULT NULL,
2
el% corre e thi
`oID` int(11) NOT NULL,

a
Y @
`tID` int(11) NOT NULL,

l l a us
PRIMARY KEY (`pID`)

b a di
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;

l ฺbo ...

ya e --

( -- Dumping data for table `pet_info2`


--
...
INSERT INTO `pet_info2` VALUES (1,'Fluffy','F','2003-02-
04',NULL,1,1),(2,'Claws','M','2004-03-17',NULL,2,1),(4,'Fang','M','2000-08-
27',NULL,3,2),(6,'Chirpy','F','2008-09-11',NULL,2,3),(7,'Whistler','M','2007-
12-09',NULL,2,4),(8,'Slim','M','2006-04-
29',NULL,3,8),(9,'Chewy','F',NULL,NULL,6,6),(10,'Opus','F',NULL,NULL,5,1),(13,
'Scruffy','M','2008-04-17',NULL,2,1);
...
--
-- Table structure for table `pet_types`
--
...
CREATE TABLE `pet_types` (
`tID` int(11) NOT NULL AUTO_INCREMENT,
`pType` varchar(20) NOT NULL,

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: MySQL Graphical User Interface Tools


Chapter 14 - Page 11
`pCategory` varchar(20) NOT NULL,
PRIMARY KEY (`tID`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
...
--
-- Dumping data for table `pet_types`
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

--
...
INSERT INTO `pet_types` VALUES
(1,'Cat','Mammal'),(2,'Dog','Mammal'),(3,'Parrot','Bird'),(4,'Canary','Bird'),
(5,'Snake','Reptile'),(6,'Hamster','Mammal'),(7,'Ferret','Mammal'),(8,'Iguana'
,'Reptile');
...
-- Dump completed on 2013-04-16 11:37:51
2. Start MySQL Workbench.
3. Open the Data Modeling module. (See the instructions for Practice 14-1.)
4. Add the existing Pets database as a schema in the Physical Schemata panel: to
a. Right-click the mydb schema and select Delete ‘mydb’. A 1n ense
3% window.
e l ic
b. Click the add button (+), and enter the name Pets in the new_schema1 C
% rabl
c. Click the close button (x) in the new schema window. ncl e
0Iall schema
n s foccurrences.
d. A message box appears, asking if you want to rename
% 2 t r a Click
l a -
dil Schemata
Yes.
e. You added the Pets database to thebPhysical a n on panel.
Import the Pets database data: a B
o as a ideฺ
5.
a. Select the File > Importn>d
r
Reverse x ) h MySQL
Engineer t G u
Create Script menu option.
l e j a y ฺ m e n
− The Reverse
2 0 AEngineer ฺ u d Script
aMySQL S tuddialog box appears.
b. On the %
e l r r eo page:
Input and Options
t h is
Y− a co andunavigate
Click Browse
@ se to the Pets.sql file in the D:\labs directory
d i lla UTF8 from the File Encoding list
− Select

l oba− Select the “Place imported objects on a diagram” check box


ฺb c. Click Execute
ya e
( − The Reverse Engineering Progress page displays “Import Finished. Finished
parsing MySQL SQL script”.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: MySQL Graphical User Interface Tools


Chapter 14 - Page 12
d. Click Next
− The Results page displays “SQL Import Finished Successfully”.
e. Click Finish
− You have created a new EER diagram for the Pets database.
6. Review the new Pets EER diagram:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

a. The tables appear in the center of the canvas. Drag them to different parts of the
canvas so you can see them all clearly.
b. Confirm that the tables and their column definitions match those in the SQL input file.
7. Create relationships between the tables:
a. Add a foreign key from the pet_info table to the owners table. Select the Place a
Relationship Using Existing Columns tool at the very bottom of the vertical toolbar (on
the left side of the canvas. You might need to maximize the Workbench window to see
this tool.)
− Click the oID column in the pet_info table.
− Click the oID column in the owners table. n nse to
A relationship line appears on the canvas. This shows that the owners A 1table ea
has
3 % l i c
one-to-many relationship with the pet_info table using the C
l %
oID column.
a b le
b. Move the cursor over the relationship line. This highlights
0 I erthe two related
ncthe linesfand
columns.
% 2 tran
d i l
c. Double-click the relationship line. The Relationshipa
l nwindowo n- opens below the EER
obaof athes Relationship
diagram.
d. Click the Foreign Key tab at theB
a eฺ Window and review the
relationship details.
bottom
ra x) h t Gu i d
n d
ja dthat
− The relationshipespecifies
l y ฺm e
one owner
d nID in the owners table can relate to many
owner IDs0inAthe pet_info
2 ฺ ua stable.S tu
o
re window.
%Relationship hi
e. Close
a elthe o r e t
c a. to d.utos create a relationship between the pet_info and pet_types
f. YRepeat steps
@
a
ill using their tID columns.
tables,
a d
b the Pets table information:
8.
l oView
ฺb a.
ya e Click the MySQL Model tab.
( b. Double-click the pet_info table icon in the Pets schema window.
c. Click the Foreign Keys tab at the bottom of the pet_info table window, and ensure
that it lists the foreign keys for the two relationships you created.
d. Close the pet_info table window.
9. Save the model:
a. Select the File > Save Model As menu option.
b. Save the model as D:\labs\Pets.mwb.
10. Close MySQL Workbench.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: MySQL Graphical User Interface Tools


Chapter 14 - Page 13
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: MySQL Graphical User Interface Tools


Chapter 14 - Page 14
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
c b
l% era15:
Practices for n Lesson
f
2 0I ans
Supplemental
a% on-tr Information
i l l
o ad 15a n ฺ
bChapter
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 ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Supplemental Information


Chapter 15 - Page 1
Practices for Lesson 15: Overview
Practices Overview
These practices test your knowledge of views, storage engines, database metadata, and
backups. They target the Windows operating system, provided in Oracle classrooms. For non-
Oracle classrooms, you might need to adjust file locations.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Assumptions
• You have installed and configured the MySQL server.
• You have created and populated the world_innodb database.
• You have created and populated the Pets database and have completed all the practice
steps that target this database, up to and including the Practices for Lesson 9: “Table
Data Manipulation”.
• You can access the mysql client from a command-line prompt.
Note: In this practice, the first letters of table names are in uppercase. Windows is not case- to
1n ense
sensitive but some operating systems are, so it is good practice to use proper capitalization.
A
3% le lic
The SQL statements are all in uppercase for clarity, but this is not required.
C
n c l% erab
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Supplemental Information


Chapter 15 - Page 2
Practice 15-1: Displaying Storage Engine Information
Overview
In this practice, you use the following statements to retrieve information about the use and
availability of storage engines in the MySQL server:

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

SHOW CREATE TABLE


• SHOW TABLE STATUS
• SHOW ENGINES

Duration
This practice takes approximately 10 minutes to complete.

Tasks
1. Display the statement that creates the CountryLanguage table and note which storage
engine it uses. to
1n ense
2. Display the status of the City table and note which storage engine it uses.
A
3. Show all the storage engines that your MySQL server supports.
C 3% le lic
Note: Keep your mysql session open for the next practice.
n c l% erab
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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Supplemental Information


Chapter 15 - Page 3
Solutions 15-1: Displaying Storage Engine Information
Tasks
1. Display the statement that creates the CountryLanguage table and note which storage
engine it uses.
a. Log in to the MySQL server at the command prompt:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

cmd> mysql -uroot -poracle


...
b. Compare your statements and results to those shown below:
mysql> USE world_innodb
Database changed

mysql> SHOW CREATE TABLE CountryLanguage\G


*************************** 1. row ***************************
Table: CountryLanguage to
Create Table: CREATE TABLE `countrylanguage` (
A 1n ense
3% le lic
`CountryCode` char(3) NOT NULL DEFAULT '',
`Language` char(30) NOT NULL DEFAULT '',
C
l% erab
`IsOfficial` enum('T','F') NOT NULL DEFAULT 'F',
n c
`Percentage` float(4,1) NOT NULL DEFAULT '0.0',
2 0I ansf
a% on-tr
PRIMARY KEY (`CountryCode`,`Language`),
KEY `CountryCode` (`CountryCode`),
i l l
bad s a n eฺ
CONSTRAINT `countryLanguage_ibfk_1` FOREIGN KEY (`CountryCode`)
REFERENCES `country` (`Code`) o
B ha
d a
) ENGINE=InnoDB DEFAULT CHARSET=latin1
r x ) G uid
1 row in set (0.06 sec)
j a n yฺm ent
2. l
Display the status of the
A e City
a d and tnote
table
u d which storage engine it uses:
Compare your 0 u S to those shown below:
oฺ andhiresults
2 statement s
l % r e
Y ae SHOW
mysql> c orTABLEseSTATUS
t LIKE 'City'\G
a @ u
***************************
l l 1. row ***************************

b a di Name: city
Engine: InnoDB
l ฺb o Version: 10
ya e Row_format: Compact
( Rows: 4188
Avg_row_length: 97
Data_length: 409600
Max_data_length: 0
Index_length: 131072
Data_free: 0
Auto_increment: 4080
Create_time: 2013-03-18 10:36:00
Update_time: NULL
Check_time: NULL
Collation: latin1_swedish_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.08 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Supplemental Information


Chapter 15 - Page 4
3. Show all the storage engines that your MySQL server supports.
Compare your statement and results to those shown below:
mysql> SHOW ENGINES\G
*************************** 1. row ***************************
Engine: FEDERATED
Support: NO
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Comment: Federated MySQL storage engine


Transactions: NULL
XA: NULL
Savepoints: NULL
*************************** 2. row ***************************
Engine: MRG_MYISAM
Support: YES
Comment: Collection of identical MyISAM tables
Transactions: NO
XA: NO
Savepoints: NO
*************************** 3. row ***************************
Engine: MyISAM
Support: YES to
Comment: MyISAM storage engine
Transactions: NO A 1n ense
XA: NO
C 3% le lic
l% erab
Savepoints: NO

n c
*************************** 4. row ***************************
Engine: BLACKHOLE
2 0I ansf
a% on-tr
Support: YES
i l l
Comment: /dev/null storage engine (anything you write to it disappears)

bad s a n eฺ
Transactions: NO
XA: NO
o
B ha
Savepoints: NO
d r a x ) G uid
*************************** 5. row ***************************
Engine: CSV
j a n yฺm ent
l e
0A oฺuad s Stud
Support: YES

2
Comment: CSV storage engine

el% corre e thi


Transactions: NO
a
Y @
XA: NO
Savepoints: NO
l l a us
di
*************************** 6. row ***************************

o b a Engine: MEMORY
Support: YES

e l ฺb Comment: Hash based, stored in memory, useful for temporary tables

( ya Transactions: NO
XA: NO
Savepoints: NO
*************************** 7. row ***************************
Engine: ARCHIVE
Support: YES
Comment: Archive storage engine
Transactions: NO
XA: NO
Savepoints: NO
*************************** 8. row ***************************
Engine: InnoDB
Support: DEFAULT
Comment: Supports transactions, row-level locking, and foreign keys
Transactions: YES
XA: YES
Savepoints: YES
*************************** 9. row ***************************
Engine: PERFORMANCE_SCHEMA
Support: YES
Comment: Performance Schema
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Supplemental Information


Chapter 15 - Page 5
Transactions: NO
XA: NO
Savepoints: NO
9 rows in set (0.00 sec)
− The order of storage engines might vary on your system.
Note: Keep your mysql session open for the next practice.
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Supplemental Information


Chapter 15 - Page 6
Practice 15-2: Displaying and Creating Views
Overview
In this practice, you determine which tables are base tables and which are views, and create a
view from an existing world_innodb table.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Duration
This practice takes approximately 10 minutes to complete.

Tasks
1. List the tables in the world_innodb database, including the table types.
2. Create a new view called CityView, which consists of the ID and Name columns from the
City table. Confirm that the new view exists.
3. Display the structure of the CityView view.
4. Get a total count of the rows from the CityView view to confirm that it contains the correct to
data.
A 1n ense
Hint: The row count should be the same as for the City table.
C 3% le lic
Note: Keep your mysql session open for the next practice.
n c l% erab
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 ฺ b o
( yae

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Supplemental Information


Chapter 15 - Page 7
Solutions 15-2: Displaying and Creating Views
Tasks
1. List the tables in the world_innodb database, including the table types.
Compare your statements and results to those shown below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> USE world_innodb


Database changed

mysql> SHOW FULL TABLES;


+------------------------+------------+
| Tables_in_world_innodb | Table_type |
+------------------------+------------+
| city | BASE TABLE |
| country | BASE TABLE |
| country2 | BASE TABLE |
| countrylanguage | BASE TABLE | to
| countrylanguage2 | BASE TABLE |
A 1n ense
3% le lic
| gelderlanddist | BASE TABLE |
+------------------------+------------+
6 rows in set (0.00 sec) C
l% erab
n c
0I ansf
− Note that the current tables are all of type BASE TABLE.
2
2. Create a new view called CityView, which consists
l l a r Name columns from the
%of thenID-tand
City table.
a i
d a no
a. Compare your statement and results b
o to those s eฺ
shown below:
mysql> CREATE VIEW d
B
ra x)ASh t Gu
CityView
a i d
n
ja Name y ฺm City; e n
Query OK, 00A
l e
-> SELECT ID,
d FROM
d
tu sec)
2 ฺ ua s(0.05
rows affected
o S
el%thatcthe
b. Confirm
a o e hi
re view texists:
rnew
Y
mysql>@ SHOW FULLusTABLES;
i l l a
|d
+------------------------+------------+

o b a Tables_in_world_innodb | Table_type |

e l ฺb +------------------------+------------+

( ya | city
| cityview
| BASE TABLE |
| VIEW |
| country | BASE TABLE |
| country2 | BASE TABLE |
| countrylanguage | BASE TABLE |
| countrylanguage2 | BASE TABLE |
| gelderlanddist | BASE TABLE |
+------------------------+------------+
7 rows in set (0.00 sec)
− Returns a list of the tables in the world_innodb database, which now includes
CityView

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Supplemental Information


Chapter 15 - Page 8
3. Display the structure of the CityView view.
Compare your statement and results to those shown below:
mysql> DESCRIBE CityView;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| ID | int(11) | NO | | 0 | |
| Name | char(35) | NO | | | |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.08 sec)
− Displays the columns and their attributes in the newly created CityView view
4. Get a total count of the rows from the CityView view to confirm that it contains the correct
data.
Compare your statement and results to those shown below:
mysql> SELECT COUNT(*) FROM CityView;
+----------+
to
| COUNT(*) |
+----------+ A 1n ense
| 4079 |
C 3% le lic
+----------+
n c l%table.erab
0 I
− The CityView view contains all the records from the City
n s f
2
i l l a% on-tra
Note: Keep your mysql session open for the next practice.

o bad s a n eฺ
r a B ha uid
d
n yฺm ent x ) 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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Supplemental Information


Chapter 15 - Page 9
Practice 15-3: Obtaining Metadata
Overview
In this practice, you retrieve metadata from the INFORMATION_SCHEMA database.

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

This practice takes approximately 20 minutes to complete.

Tasks
1. List all available databases and confirm that INFORMATION_SCHEMA is among them.
2. List all the tables in the INFORMATION_SCHEMA database.
3. Use the INFORMATION_SCHEMA database’s schemata table to obtain information about
the world_innodb database.
Hint: Query the schemata table with the schema name set to world_innodb.
4. List the table name, type, and engine for all tables in the world_innodb database.
n nse to
Hint: First, determine which columns you need from the tables table in theA1
INFORMATION_SCHEMA database. Then, query the tables table with 3 the l ice
%tableeschema
l % C bl
set to world_innodb.
I n c f e ra
5. 0 an
List the table name, creation time, and the current value for
2 s
auto-increment table columns
for all tables in the Pets database.
l l a% on-t r
i
Hint: Use the table_name, create_time,
tables table in the INFORMATION_SCHEMA o badand s
database,
n ฺ
auto_increment
a with ethe table
columns from the
schema set to Pets.
a B h a u i d
6. Exit the mysql client.
a n dr 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
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Supplemental Information


Chapter 15 - Page 10
Solutions 15-3: Obtaining Metadata
Tasks
1. List all available databases and confirm that INFORMATION_SCHEMA is among them.
Compare your statement and results to those shown below:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

mysql> SHOW DATABASES;


+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| pets |
| sakila |
| test |
| world |
to
| world_innodb |
A 1n ense
3% le lic
| world_innodb2 |
+--------------------+
C
l% erab
9 rows in set (0.00 sec)
n c
2. List all the tables in the INFORMATION_SCHEMA database. 2 0I ansf
Compare your statement and results to those
i l l % below:
ashown n - tr
b a d a no
eฺ
mysql> SHOW TABLES FROM INFORMATION_SCHEMA;
B o as
+---------------------------------------+
i d
d
| Tables_in_information_schema
n ra x) h t G|u
l e ja dyฺm den |
+---------------------------------------+

0A oฺua s Stu
| CHARACTER_SETS
| COLLATIONS
% 2 e i
|

| a el corr e th
| COLLATION_CHARACTER_SET_APPLICABILITY |
Y COLUMNS
@ u s |

|d i lla
| COLUMN_PRIVILEGES
ENGINES
|
|
o b a| EVENTS |

e l ฺb | FILES |

( ya |
|
GLOBAL_STATUS
GLOBAL_VARIABLES
|
|
| KEY_COLUMN_USAGE |
| OPTIMIZER_TRACE |
| PARAMETERS |
| PARTITIONS |
| PLUGINS |
| PROCESSLIST |
| PROFILING |
| REFERENTIAL_CONSTRAINTS |
| ROUTINES |
| SCHEMATA |
| SCHEMA_PRIVILEGES |
| SESSION_STATUS |
| SESSION_VARIABLES |
| STATISTICS |
| TABLES |
| TABLESPACES |
| TABLE_CONSTRAINTS |
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Supplemental Information


Chapter 15 - Page 11
| TABLE_PRIVILEGES |
| TRIGGERS |
| USER_PRIVILEGES |
| VIEWS |
| . . . |
| INNODB_METRICS |
| INNODB_SYS_FOREIGN_COLS |
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

| INNODB_FT_CONFIG |
| INNODB_BUFFER_POOL_STATS |
| INNODB_SYS_COLUMNS |
| INNODB_SYS_FOREIGN |
+---------------------------------------+
60 rows in set (0.00 sec)
3. Use the INFORMATION_SCHEMA database’s schemata table to obtain information about
the world_innodb database.
Compare your statement and results to those shown below:
mysql> SELECT * FROM information_schema.schemata
to
-> WHERE SCHEMA_NAME = 'world_innodb'\G
A 1n ense
***************** 1. row ********************
3 % e lic
CATALOG_NAME: def
SCHEMA_NAME: world_innodb
l C
% rabl
c
0In ansfe
DEFAULT_CHARACTER_SET_NAME: latin1
DEFAULT_COLLATION_NAME: latin1_swedish_ci 2
% n-tr
SQL_PATH: NULL
i l l a
1 row in set (0.01 sec)
b a d a no
4. List the table name, type, and engineB o all tables
for
a s eฺ
in the world_innodb
i d database.
d a
a. First, list the available columns h G u
r in thex)INFORMATION_SCHEMA database’s tables
a n m n t
A l e adyฺand tresults
table. Compare yourj statement
u d e to those shown below:
mysql> DESC
2 0 INFORMATION_SCHEMA.TABLES;
o ฺu is S
%
el corr | Typee th
+-----------------+---------------------+------+-----+---------+-------+

Y a
| Field
s e | Null | Key | Default | Extra |

a@ u| varchar(512)
+-----------------+---------------------+------+-----+---------+-------+
l l
|d i
| TABLE_CATALOG | NO | | | |

oba| TABLE_NAME
TABLE_SCHEMA | varchar(64) | NO | | | |
| varchar(64) | NO | | | |
e l ฺb | TABLE_TYPE | varchar(64) | NO | | | |

( ya | ENGINE
| VERSION
| varchar(64) | YES |
| bigint(21) unsigned | YES |
| NULL
| NULL
|
|
|
|
| ROW_FORMAT | varchar(10) | YES | | NULL | |
| TABLE_ROWS | bigint(21) unsigned | YES | | NULL | |
| AVG_ROW_LENGTH | bigint(21) unsigned | YES | | NULL | |
| DATA_LENGTH | bigint(21) unsigned | YES | | NULL | |
| MAX_DATA_LENGTH | bigint(21) unsigned | YES | | NULL | |
| INDEX_LENGTH | bigint(21) unsigned | YES | | NULL | |
| DATA_FREE | bigint(21) unsigned | YES | | NULL | |
| AUTO_INCREMENT | bigint(21) unsigned | YES | | NULL | |
| CREATE_TIME | datetime | YES | | NULL | |
| UPDATE_TIME | datetime | YES | | NULL | |
| CHECK_TIME | datetime | YES | | NULL | |
| TABLE_COLLATION | varchar(32) | YES | | NULL | |
| CHECKSUM | bigint(21) unsigned | YES | | NULL | |
| CREATE_OPTIONS | varchar(255) | YES | | NULL | |
| TABLE_COMMENT | varchar(2048) | NO | | | |
+-----------------+---------------------+------+-----+---------+-------+
21 rows in set (0.17 sec)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Supplemental Information


Chapter 15 - Page 12
b. Then, create the query. Compare your statement and results to those shown below:
mysql> SELECT table_name, table_type, engine
-> FROM information_schema.tables
-> WHERE table_schema = 'world_innodb'
-> ORDER BY table_name DESC;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

+------------------+------------+--------+
| table_name | table_type | engine |
+------------------+------------+--------+
| gelderlanddist | BASE TABLE | InnoDB |
| countrylanguage2 | BASE TABLE | InnoDB |
| countrylanguage | BASE TABLE | InnoDB |
| country2 | BASE TABLE | InnoDB |
| country | BASE TABLE | InnoDB |
| cityview | VIEW | NULL |
| city | BASE TABLE | InnoDB |
+------------------+------------+--------+
7 rows in set (0.00 sec)
to
5.
1n ense
List the table name, creation time, and the current value for auto-increment table columns
for all tables in the Pets database. A
Compare your statement and results to those shown below: C 3% le lic
n c l% erab
0I ansf
mysql> SELECT table_name, create_time, auto_increment
2
a% on-tr
-> FROM information_schema.tables
i l l
ad a n ฺ
-> WHERE table_schema = 'pets'
o bDESC;
B has uide
-> ORDER BY table_name
r a
+------------+---------------------+----------------+
d mx) |ntauto_incrementG
j a n
| table_name | create_time

|

| pet_types A
0 |le a dy 10:01:39
t u de|
+------------+---------------------+----------------+

2 ฺ u
2011-11-15
S
o his16:56:28 |
9 |

e l %
| pet_info2
r r e
| 2011-12-30 15:11:02
t 10:01:38 |
| 14 |

owners co | 2011-11-15
| a
| pet_info | 2011-11-17 14 |
Y u s e 7 |
a @
4d
a ill in set (0.00 sec)
+------------+---------------------+----------------+
rows

l ฺ b ob− Creation times might vary on your system.

(y ae6. Exit the mysql client.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Supplemental Information


Chapter 15 - Page 13
OPTIONAL Practice 15-4: Creating a Backup of MySQL Databases
Overview
In this practice, you use MySQL Enterprise Backup to create a backup of the MySQL databases
on your system.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Duration
This practice takes approximately 5 minutes to complete.

Tasks
1. Create a folder called backups in the labs directory (D:\labs).
2. Use the mysqlbackup command to create a backup of all databases on your MySQL
server. Connect to the server host on port 3306 as the root account. Include a time stamp
and specify D:\labs\backups as the destination directory for backup files.
3. Review the contents of the D:\labs\backups folder.
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 ฺb o
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Supplemental Information


Chapter 15 - Page 14
OPTIONAL Solutions 15-4: Creating a Backup of MySQL Databases
Tasks
1. Create a folder called backups in the labs directory (D:\labs).
Use Windows Explorer to navigate to the D:\labs directory and create the specified
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

folder.
2. Use the mysqlbackup command to create a backup of all databases on your MySQL
server. Connect to the server host on port 3306 as the root account. Include a time stamp
and specify D:\labs\backups as the destination directory for backup files.
Compare your command syntax and results to those shown below:
cmd> mysqlbackup --user=root --password=oracle --port=3306
--with-timestamp --backup-dir=D:/labs/backups backup
MySQL Enterprise Backup version 3.8.1 [Mon 01/28/2013 ]
Copyright (c) 2003, 2012, Oracle and/or its affiliates. All Rights Reserved.
to
A 1n ense
mysqlbackup: INFO: Starting with following command line ...
mysqlbackup --user=root --password=xxxxxx --port=3306 --with-timestamp
--backup-dir=d:/labs/backups backup
C 3% le lic
n c l% erab
mysqlbackup: INFO: MySQL server version is '5.6.10-enterprise-commercial-advanced'.

0I ansf
mysqlbackup: INFO: Got some server configuration information from running server.

2
a% on-tr
IMPORTANT: Please check that mysqlbackup run completes successfully.

i l l
At the end of a successful 'backup' run mysqlbackup

bad s a n eฺ
prints "mysqlbackup completed OK!".

o
B ha uid
--------------------------------------------------------------------

d r a )
Server Repository Options:
x G
j a n yฺm ent
--------------------------------------------------------------------

e
datadir = D:\ProgramData\MySQL\MySQL Server 5.6\data\
l
0A oฺuad s Stud
innodb_data_home_dir =

2
innodb_data_file_path = ibdata1:12M:autoextend

el% corre e thi


innodb_log_group_home_dir = D:\ProgramData\MySQL\MySQL Server 5.6\data\

a
Y @
innodb_log_files_in_group = 2

l us
innodb_log_file_size = 50331648
a
innodb_page_size = 16384
l
b a diinnodb_checksum_algorithm = crc32
innodb_undo_directory = D:\ProgramData\MySQL\MySQL Server 5.6\data\

l ฺb o innodb_undo_tablespaces = 0

ya e innodb_undo_logs = 128

( --------------------------------------------------------------------
Backup Config Options:
--------------------------------------------------------------------
datadir = d:\labs\backups\2013-04-19_07-29-42\datadir
innodb_data_home_dir = d:\labs\backups\2013-04-19_07-29-42\datadir
innodb_data_file_path = ibdata1:12M:autoextend
innodb_log_group_home_dir = d:\labs\backups\2013-04-19_07-29-42\datadir
innodb_log_files_in_group = 2
innodb_log_file_size = 50331648
innodb_page_size = 16384
innodb_checksum_algorithm = crc32
innodb_undo_directory = d:\labs\backups\2013-04-19_07-29-42\datadir
innodb_undo_tablespaces = 0
innodb_undo_logs = 128

mysqlbackup: INFO: Unique generated backup id for this is 13663565820627785

mysqlbackup: INFO: Creating 14 buffers each of size 16777216.


130419 07:29:44 mysqlbackup: INFO: Full Backup operation starts with following threads
1 read-threads 6 process-threads 1 write-threads
130419 07:29:44 mysqlbackup: INFO: System tablespace file format is Antelope.
130419 07:29:44 mysqlbackup: INFO: Starting to copy all innodb files...

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Supplemental Information


Chapter 15 - Page 15
130419 07:29:44 mysqlbackup: INFO: Copying D:\ProgramData\MySQL\MySQL Server
5.6\data\ibdata1 (Antelope file format).
130419 07:29:44 mysqlbackup: INFO: Found checkpoint at lsn 8532413.
130419 07:29:44 mysqlbackup: INFO: Starting log scan from lsn 8531968.
130419 07:29:44 mysqlbackup: INFO: Copying log...
130419 07:29:44 mysqlbackup: INFO: Log copied, lsn 8532413.
mysqlbackup: Progress in MB: 200 400 600 800 1000
. . .
130419 07:30:17 mysqlbackup: INFO: Completing the copy of innodb files.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

130419 07:30:17 mysqlbackup: INFO: Preparing to lock tables: Connected to mysqld server.
130419 07:30:17 mysqlbackup: INFO: Starting to lock all the tables...
130419 07:30:18 mysqlbackup: INFO: All tables are locked and flushed to disk
130419 07:30:18 mysqlbackup: INFO: Opening backup source directory
'D:\ProgramData\MySQL\MySQL Server 5.6\data\'
130419 07:30:18 mysqlbackup: INFO: Starting to backup all non-innodb files in
subdirectories of 'D:\ProgramData\MySQL\MySQL Server 5.6\data\'
130419 07:30:18 mysqlbackup: INFO: Copying the database directory 'mysql'
130419 07:30:18 mysqlbackup: INFO: Copying the database directory 'performance_schema'
130419 07:30:19 mysqlbackup: INFO: Copying the database directory 'sakila'
130419 07:30:19 mysqlbackup: INFO: Copying the database directory 'test'
130419 07:30:19 mysqlbackup: INFO: Copying the database directory 'world'
130419 07:30:19 mysqlbackup: INFO: Completing the copy of all non-innodb files.
130419 07:30:20 mysqlbackup: INFO: A copied database page was modified at 8532413.
(This is the highest lsn found on page) to
Scanned log up to lsn 8535769.
Was able to parse the log up to lsn 8535769.
A 1n ense
Maximum page number for a log record 349
130419 07:30:20 mysqlbackup: INFO: All tables unlocked
C 3% le lic
c l% erab
130419 07:30:20 mysqlbackup: INFO: All MySQL tables were locked for 2.188 seconds.
n
0I ansf
130419 07:30:20 mysqlbackup: INFO: Full Backup operation completed successfully.

2
130419 07:30:20 mysqlbackup: INFO: Backup created in directory 'd:\labs\backups\2013-04-

a% on-tr
19_07-29-42'

i l l
bad s a n eฺ
-------------------------------------------------------------
Parameters Summary
o
B ha uid
-------------------------------------------------------------
Start LSN
d r a
: 8531968
x ) G
End LSN
j a n yฺm ent
: 8535769

l e
-------------------------------------------------------------

2 0A oฺuad s Stud
mysqlbackup completed OK!
− Theel% r
exact output i
reon yourthmachine might vary from that shown here.
Y a c o e
l l a us
Note: When using the --with-timestamp
@the mysqlbackup option, you need to create the backup folder

3. b a dithe contents of the D:\labs\backups folder.


before running command.

l o
Review
ฺb a.
ya e Use Windows Explorer to navigate to the D:\labs\backups folder.
( b. A new folder exists in this directory with the date and time as the name, for example:
2013-04-19_07-29-42,
Note: In the Oracle classroom environment, the MySQL server stores the original database
data in D:\ProgramData\MySQL\MySQL Server 5.6\data. Windows hides the
ProgramData folder by default. When using Windows Explorer, you must turn on the option to
show hidden files and folders (Tools > Folder Options > View tab) to view this folder.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Supplemental Information


Chapter 15 - Page 16
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
c b
l% era16:
Practices for n Lesson
f
2 0I ans
Conclusion
a% on-tr
i l l
o ad 16a n ฺ
bChapter
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 ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Conclusion


Chapter 16 - Page 1
Practices for Lesson 16
Practices Overview
There are no practices for this lesson.
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Conclusion


Chapter 16 - Page 2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
Appendix A: n c l% erabof
Glossary
2 0I ansf
MySQL a%Terms - tr
i l l
d 17a no n
b a
B
Chapter
o as i d eฺ
n d ra x) h t Gu
l e ja dyฺm den
2 0A oฺua s Stu
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix A: Glossary of MySQL Terms


Chapter 17 - Page 1
Glossary of MySQL Terms: Overview
Overview
This glossary includes explanations of some of the most important terms that you may come
across while using MySQL.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-A-
ACID
The acronym for the following features of transactional databases: Atomic, Consistent,
Isolated, and Durable. Transactional systems are often described as being ACID compliant,
where "ACID" stands for the following properties:
• Atomic: All the statements execute successfully or are canceled as a unit.
• Consistent: A database is in a consistent state when a transaction begins and is left in
a consistent state by the transaction.
to
• Isolated: One transaction does not affect another.
A 1n ense
• Durable: All the changes that are committed are guaranteed to be stored
3% ic are
persistently
e l
in the database and cannot be lost (even if RDBMS crashes). All
l C
% rabl
the changes that
rolled back are guaranteed not to exist anymore. c
2 0In ansfe
-B-
i l l a% on-tr
Backup
o bad s a n eฺ
Generally refers to the "backup" of table
r a B harecords
data and/or iddatabase transactions to a
of
ulocation.
location other than system memory d
n yฺm ent
and/or x
the )
primary G
data See also Dump.
j
le ad a
BIT
2 0 A ฺ u S t ud
A BIT is a data type
l % thatof rbits
r o bit-field
represents
eper h isfrom values. The BIT column specifications take a width
e
a useful
indicating the number
cofor tracking t
value,
e 1 through 64 bits. A bit is either 1 or 0, on or off.
This dataY type is @ u s a collection of attributes.
i l l a
-C-bob
ad
a e lฺ
( y Certification, MySQL
The Oracle Certification Program (OCP) validates various levels of MySQL expertise, for
MySQL Developers and DBAs with the credentials to prove they have the knowledge,
experience, and skills to use and manage MySQL products. A certificate is granted for those
that pass an exam covering topics associated with various roles and levels of proficiency with
the MySQL server. MySQL currently offers four certificates for Developer and DBA tracks.
Client
A client is an application that sends requests to the database server. Most commands are sent
via a client, whether it is a command-line client, a PHP script, and so on.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix A: Glossary of MySQL Terms


Chapter 17 - Page 2
Column
In the context of a relational database table, a column is a set of data values of a particular
simple type, one for each row of the table. The columns provide the structure according to which
rows are composed.
The term “field” is often used interchangeably with column, although many consider it more
correct to use field (or field value) to refer specifically to the single item that exists at the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

intersection between one row and one column (per Wikipedia).


Connectors
MySQL database connectors (also called software drivers) provide database client
connectivity for a wide range of programming languages.
Constraints, Table
A constraint is simply a restriction placed on one or more column values of a table to actively
enforce integrity rules. Constraints are implemented by using indexes.

-D- to
Database A 1n ense
A database is a loose collection of database objects (such as tables). In C e l ic is
3% a database
% rabl
MySQL,
synonymous with a schema. c l
Data Type 2 0In ansfe
In a database, each table column value can be oneiof l l % different
aseveral n - tr data types (or
datatypes), depending on the form of that data.a
b d dataamight
The no be ฺtext, a whole number, a
number with decimals, a date, or the time. B o adata
MySQL
ide include Numeric,
s type categories
Temporal, and Character String. dr a ) h u
j a n yฺmx ent G
DDL
A le ad ud statements that are specifically designed for
tSQL
The acronym for Data 2 0Definitionฺ u S
Language;
o datahis
l % rofretable
creation and modification
e t
DML Ya @co use
The acronymd i la Data Manipulation Language; SQL statements that are specifically designed
lfor
o ba
for manipulation
b of table data
l ฺ
( yaeDump, Database
A database dump contains a record of the table structure and/or the data from a database and
is usually in the form of a list of SQL statements. A database dump is most often used for
backing up a database so that its contents can be restored in the event of data loss. Corrupted
databases can often be recovered by analysis of the dump (per Wikipedia. See also Backup.

-E-
Engine
See Storage Engine.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix A: Glossary of MySQL Terms


Chapter 17 - Page 3
Enterprise Backup, MySQL
The MySQL Enterprise Backup (MEB) is a command-line tool that performs “hot backup”
operations for MySQL InnoDB databases, and “warm backups” for non-InnoDB storage engine
tables.
Enterprise Monitor, MySQL
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

The MySQL Enterprise Monitor (MEM) is a web-based GUI tool with a monitoring and
advising system, provided only to Enterprise customers. It enables you to monitor multiple
databases, monitor replication, and receive notification of failures and/or resource issues.
Entity
In database theory, the term "entity" is used to denote a distinct item (such as a table or
column), and the term "relationship" is used to denote that two entities have something to do
with each other.
ERD/EER
The acronym for Entity Relationship Diagram/Extended Entity Relationship. An
entity-relationship model is a method of diagramming database objects and the relationships to
between them.
A 1n ense
C 3% le lic
-F-
n c l% erab
File System 2 0I ansf
A file system (or filesystem) is a method of storing and
l l a% -
organizing
n r
tcomputer files and the data
d i n o
oba as a ideฺ
they contain.
Function B
a x) ahgiven G
rtransforms u
d
A function is a stored operationnthat t input into a corresponding output.
e
Functions can be invoked lwithin
d y ฺm anddreturn
ja expressions e n a value that is used in place of the
function call when the0
2 A ฺuisaevaluated.
expression S tu
o s
a el% corre e thi
-G- Y @ us
l l a
GPL
b a di
The o acronym for General Public License; open source license for general use
l ฺ b
( yaeGUI
The acronym for Graphical User Interface. The MySQL GUI tools form a comprehensive
graphical user interface to your MySQL database. These easy-to-use graphical tools enable
database developers and database administrators (DBAs) to be more productive.

-H-
Help, MySQL client
A user can get help on mysql client commands or statements by typing the mysql command
with the --help option at a shell prompt. The help; or \h entered at the mysql>
command-line prompt can also be used for help.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix A: Glossary of MySQL Terms


Chapter 17 - Page 4
Host Name
A host name is a label that is assigned to a device connected to a computer network and that is
used to identify the device in various forms of electronic communication (per Wikipedia).
With MySQL, it refers to the name of the client or system used to connect to the MySQL server.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-I-
Index
An index in MySQL serves to assist in finding table rows more quickly and easily, much like an
index 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, and a pointer of some sort,
used to locate the rows. It also contains information describing where the rows are physically
located.
INFORMATION_SCHEMA
INFORMATION_SCHEMA is a virtual database that provides access to database metadata,
such as schema, schema objects, and server statistics (such as status variables, settings, and to
connections).
A 1n ense
InnoDB
C 3% le lic
c l% erabtransactions.
InnoDB is the default storage engine for MySQL server. It allows ACID-compliant
n
2 0I ansf
-J-
i l l a% on-tr
Join
o bad s a n eฺ
A join is an operation that produces aaresult
r B by combining uid information in one table with
ha G(joining)
information in another. d
n yฺm ent x )
l e j a
-K- 2 0A oฺuad s Stud
Keys a el% corre e thi
Y @ a keyusis used to uniquely identify each row in a table. There are
differenta d il ofa keys available for distinct purposes.
In a relational ldatabase,
types

l ฺ b ob
( yae-L-
LAMP Stack
The acronym for Linux, Apache, MySQL, PHP/Pearl/Python. This is a combination of
hardware and software that represents a solution “stack” of technologies that support
application servers. Other derivatives are WAMP (Windows) and SAMP (Solaris).

-M-
Modes, SQL
SQL modes control aspects of server operation such as which SQL syntax MySQL supports
and what kind of data validation checks it performs.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix A: Glossary of MySQL Terms


Chapter 17 - Page 5
-N-
Normalization/Normal Forms
Normalization is the process of refining a database design to ensure that each independent
piece of information is in only one place. Normalizing tables removes redundant data. This
makes it possible to access data more flexibly, and eliminates the possibility that inappropriate
modifications can take place that make the data inconsistent.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Normalization of a complex table often amounts to taking it through a process (using normal
forms) of decomposition into a set of smaller tables.
NULL
NULL is a SQL keyword used to define data types as allowing a missing (or absent) value. It is
also a query result.
The concept of NULL can actually have several meanings, such as "no value," "unknown
value," "missing value," "out of range," "not applicable," "undefined," and "none of the above."

-O- to
Operating System A 1n ense
An operating system (OS) [also called platform] is an interface between C 3% leandlicusers,
hardware
which is responsible for the management and coordination of activities
c l%and the r b of the
asharing
I
resources of a computer, that acts as a host for computing applications
0 n s
run f e
on the machine (per
2 n
Wikipedia).
i l l a% on-tra
-P- o bad s a n eฺ
r a B ha uid
PERFORMANCE_SCHEMA d
n yฺfor x ) G
t MySQL server execution at a low level,
PERFORMANCE_SCHEMA e j a
is a feature m e n
monitoring
with minimal impact on
2 Al performance.
0server ฺ u ad Stud
l % execution
It inspects the internal
e r r eo of the t h s (at run time) by using the
iserver
Ya @co ustorage
PERFORMANCE_SCHEMA se engine and the PERFORMANCE_SCHEMA database.
Permissionsilla
b ad (also called privileges) are access levels that are generally assigned to specific
Permissions
o
e l ฺb for distinct data and/or task performance.
users
( ya Planet MySQL
A MySQL-sponsored website for blogs, news, and opinions pertaining to MySQL:
http://planet.mysql.com/

-Q-
Query
A query is a form of questioning, in a line of inquiry. In MySQL, the SQL language is used to put
questions into a form that is understood by the MySQL server and can provide a result based on
information stored in a database.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix A: Glossary of MySQL Terms


Chapter 17 - Page 6
-R-
RDBMS
The acronym for Relational Database Management System. An RDBMS organizes and stores
data in the form of tables. An RDBMS manages data according to the relational model. In the
relational model, the fundamental structure to organize data is the "relation," which is where it
gets its name.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Register
A register acts as a communication between the different components of the computer
hardware. An example of a register is the memory data register that acts as a buffer between
the computer memory and the central processing unit. However, there are multiple registers that
perform communication functions within the computer hardware to handle the passing of
information from one component to another. Most registers are multi-directional and can read
and write in any direction (for example, from CPU to memory or from memory to CPU).
Row
A row (also called a record or tuple) represents a single, implicitly structured data item in a
to
A 1n ense
table. In simple terms, a database table can be thought of as consisting of rows and columns or
fields. Each row in a table represents a set of related data, and every row in the table has the
same structure (per Wikipedia).
C 3% le lic
c l% erab
The rows of a table consist of a collection of values that describe an entity (for example, bank
n
account).
2 0I ansf
i l l a% on-tr
-S-
o bad s a n eฺ
SELECT statement
r a B ha uid one or more tables.
The SELECT SQL statement returns d
n yฺm ent
a result x )
set of recordsGfrom
e j a
Server, Database
2 0 Al ฺuad Stud
o program s that provides database services to other computer
ithe
el% coas rredefined
A database server is a computer
programs oracomputers, e t
byh client/server model. The term may also refer to a
Y s
u such a program.
computer dedicated
i l l a@to running
b a d
Database management systems frequently provide database server functionality, and some
DBMSs
l ฺ b o (for example, MySQL) rely exclusively on the client/server model for database access
yae
(per Wikipedia).
( SQL
The acronym for Structured Query Language. SQL is a database computer language designed
for managing data in relational database management systems (RDBMS), and originally based
on Relational Algebra. Its scope includes data query and update, schema creation and
modification, and data access control (per Wikipedia).
Storage Engine
A storage engine (also called a database engine) is the underlying software component that a
database management system uses to create, retrieve, update, and delete data from a
database.

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix A: Glossary of MySQL Terms


Chapter 17 - Page 7
Subquery
A subquery is a query nested within another SQL statement (query).

-T-
Tee file
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

A tee file is created by using the tee command, to record the input and output of SQL
statements for a specified mysql session.
Transaction, Database
A database transaction comprises a unit of work performed against a database, and treated in
a coherent and reliable way independent of other transactions. A transaction is a means to
execute one or more SQL statements as a single unit of work, such that either all or none of the
statements succeed.
Table, Database
A database table is a set of data elements (values) that are organized using a model of vertical to
number of columns, but can have any number of rows (per Wikipedia). A 1n ense
columns (which are identified by their names) and horizontal rows. A table has a specified

C 3% le lic
-U- n c l% erab
0 I n s f
UNIX 2
% n-tra
i l l a
b a d system.
UNIX is a multitasking, multi-user computer operating
a no ฺ
B o as ide
-V- r a ) h u
j a nd yฺmx ent G
View
le aisda database tudobject that is defined in terms of a SELECT
A view (also called 2 0A tables)
virtual ฺ u
o youhwant S
l % the
statement that retrieves
e r r edata t is the view to produce.
Ya @co use
-W-
d i lla
o ba MySQL
Workbench,
b
a e lฺ Workbench is a cross-platform GUI tool for the MySQL server, for database architects,
MySQL
( y developers, and DBAs. MySQL Workbench provides data modeling, SQL development, and
comprehensive administration tools for server configuration, user administration, and much
more. MySQL Workbench is available on Windows, Linux, and Mac OS.

-XYZ-
--

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix A: Glossary of MySQL Terms


Chapter 17 - Page 8
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

to
A 1n ense
C 3% le lic
Appendix B: n c l% erab
Practice
2 0I ansf
Solution a% Scripts
- tr
i l l
d 18a no n
b a
B
Chapter
o as i d eฺ
n d ra x) h t Gu
l e ja dyฺm den
2 0A oฺua s Stu
a el% corre e thi
Y @ us
l l a
b a di
l ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 1
Lesson 2: MySQL Server and Client
Practice 2-1: Install and Start the MySQL Server
-- Step (1)
-- Using Windows Explorer go to D:\stage\MySQL
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-- Step (2)
-- Using Windows Explorer
-- Double click on the “mysql-installer-commercial-5.6.10.0.msi”
file.

-- Steps (3-19)
-- Follow MySQL Installer prompts

-- Step (20)
-- At command prompt:
mysql to
A 1n ense
-- Step (21)
-- Add mysql client program to PATH environmentCvariable:
3% le lic
;D:\Program Files\MySQL\MySQL Server 5.6\bin;
n c l% erab
2 0I ansf
-- Step (22)
l l a % n-tr
-- At command prompt:
a i
d a no
mysql -u root -poracle b
o as eฺ
B
ra x) h t Gu i d
-- Step (23) n d
l e
-- At mysql prompt: ja dyฺm den
EXIT
2 0A oฺua s Stu
% rre i
PracticeY2-2: aelUse the o
c us e
Keyboard
t hEditing and Tee Commands
@
llacommand
d i
-- Step (3)
amysql -u root prompt:
-- At
b o b -poracle
l ฺ
( yae -- Step (4)
-- At mysql prompt:
\h

-- Step (6)
tee D:\labs\Lesson2_tee.txt

-- Step (11)
tee D:\labs\Test.txt

-- Step (12)
notee

-- Step (13)
tee D:\labs\Lesson2_tee.txt

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 2
-- Step (14)
notee \c

-- Step (15)
-- Using Windows Explorer go to D:\labs
-- Double click on the Lesson2_tee.txt file
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

Practice 2-3: Install the world_innodb Database


-- Step (1)
-- At mysql prompt:
CREATE DATABASE world_innodb CHARACTER SET latin1;

-- Step (2)
USE world_innodb

-- Step (3)
SOURCE D:\labs\world_innodb.sql to
A 1n ense
3% le lic
-- Step (4)
EXIT C
l% erab
n c
2 0I ansf
i l l a% on-tr
o bad s a n eฺ
r a B ha uid
d
n yฺm 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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 3
Lesson 3: Database Basics
No scripts for this lesson
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 4
Lesson 4: Database Design
Practice 4-1: Quiz
No scripts for this practice

Practice 4-2: Evaluate a Database


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

-- Step (1)
-- At command prompt:
mysql -u root -poracle

-- Step (2)
-- At mysql prompt:
SHOW DATABASES;

-- Step (3)
USE world_innodb
to
-- Step (4)
A 1n ense
SHOW TABLES;
C 3% le lic
n c l% erab
0I ansf
-- Step (5)
DESCRIBE City; 2
% n-tr
i l l a
-- Step (6)
b a d a no
SELECT * FROM City;
B o as i d eฺ
n d ra x) h t Gu
ja dyฺm den
-- Step (7)
l
DESCRIBE Country; e
2 0A oฺua s Stu
a el%*(8)
-- Step
o r reCountry\G
e t hi
Y @c us
SELECT FROM

d i lla (9)
obaDESCRIBE CountryLanguage;
-- Step

e l ฺb
( ya -- Step (10)
SELECT * FROM CountryLanguage;

-- Step (11)
EXIT

Practice 4-3: Create a Structure Diagram


No scripts for this practice

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 5
Lesson 5: Data Types
No scripts for this lesson
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 6
Lesson 6: Database and Table Creation
Practice 6-1: Display Table Creation Information
-- Step (1)
-- At command prompt:
mysql -u root -poracle
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-- At mysql prompt:
USE world_innodb

-- Step (2)
SHOW CREATE TABLE Country\G

-- Step (3)
CREATE TABLE `Country2` (
`Code` char(3) NOT NULL DEFAULT '',
`Name` char(52) NOT NULL DEFAULT '', to
`Continent` enum('Asia','Europe','North America','Africa',
A 1n ense
'Oceania','Antarctica','South America')
NOT NULL DEFAULT 'Asia', C 3% le lic
`Region` char(26) NOT NULL DEFAULT '',
n c l% erab
0I ansf
`SurfaceArea` float(10,2) NOT NULL DEFAULT '0.00',
2
`IndepYear` smallint(6) DEFAULT NULL,
i l l a% on-tr
bad s a n eฺ
`Population` int(11) NOT NULL DEFAULT '0',
`LifeExpectancy` float(3,1) DEFAULT NULL,
o
B ha
`GNP` float(10,2) DEFAULT NULL,
d r a x ) G uid
j a n yฺm ent
`GNPOld` float(10,2) DEFAULT NULL,
e
`LocalName` char(45) NOT NULL DEFAULT '',
l
0A oฺuad s Stud
`GovernmentForm` char(45) NOT NULL DEFAULT '',
2
el% corre e thi
`HeadOfState` char(60) DEFAULT NULL,
a
`Capital` int(11) DEFAULT NULL,
Y @
l l a us
`Code2` char(2) NOT NULL DEFAULT '',

b a di
PRIMARY KEY (`Code`)
);
l ฺbo
ya e -- Step (4)
( SHOW TABLES;

-- Step (5)
SHOW INDEX FROM Country2\G

-- Step (6)
SHOW INDEX FROM City\G

-- Step (7)
EXIT

Practice 6-2: Create a Database


-- Step (1-4)
-- no scripts

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 7
-- Step (5)
-- At command prompt:
mysql -u root -poracle

-- At mysql prompt:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

CREATE DATABASE Pets;

-- Step (6)
SHOW DATABASES;

-- Step (7)
USE Pets

-- Step (8)
CREATE TABLE pet_info (
pID INT NOT NULL AUTO_INCREMENT,
to
1n ense
pName VARCHAR(20) NOT NULL,
pGender ENUM('M', 'F') DEFAULT NULL, A
pBday DATE DEFAULT NULL,
C 3% le lic
pDday DATE DEFAULT NULL,
n c l% erab
0I ansf
oID INT NOT NULL,
tID INT NOT NULL, 2
PRIMARY KEY (pID)
i l l a% on-tr
);
o bad s a n eฺ
CREATE TABLE owners r (a B ha Guid
d x )
n AUTO_INCREMENT, t
oID INT NOT NULL
l e j a y ฺ m e n
oName VARCHAR(20)
2
oPhone0ACHAR(11) ฺ u d NULL,
NOT
aNOT S tud
NULL,

e l % rKEY
PRIMARY r eo(oID)this
Ya );@co use
d i lla TABLE pet_types (
oba tID INT NOT NULL AUTO_INCREMENT,
CREATE

e l ฺb pType VARCHAR(20) NOT NULL,


( ya pCategory VARCHAR(20) NOT NULL,
PRIMARY KEY (tID)
);

-- Step (9)
SHOW TABLES;

-- Step (10)
DESC pet_info;

DESC owners;

DESC pet_types;

-- Step (11)
EXIT

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 8
Lesson 7: Basic Queries
Practice 7-1: Perform Basic Queries
-- Step (1)
-- At command prompt:
mysql -u root -poracle
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-- At mysql prompt:
USE world_innodb

-- Step (2)
DESC Country;

-- Step (3)
SELECT Continent FROM Country;

-- Step (4) to
SELECT Continent, Name FROM Country;
A 1n ense
C 3% le lic
-- Step (5)
SELECT Region FROM Country;
n c l% erab
2 0I ansf
-- Step (6)
l l a % n-tr
SELECT DISTINCT Region FROM Country;
a i
d a no
b
o as eฺ
-- Step (7) B
ra IDx)= h3875; u i d
SELECT * FROM City n d
WHERE t G
l e ja dyฺm den
-- Step (8)
2 0A Population
ฺ ua s FROMS tu
SELECT l % rre
Name, o h i Country WHERE Population < 1000;
a e co use t
Y @
d i
SELECTlla Name FROM City ORDER BY Name DESC;
-- Step (9)

l ฺboba
ya e -- Step (10)
( DESC CountryLanguage;

-- Step (11)
SELECT CountryCode, Language
FROM CountryLanguage
WHERE Language = 'Swedish'
ORDER BY CountryCode DESC;

-- Step (12)
SELECT Name
FROM City
ORDER BY Name ASC
LIMIT 10;

-- Step (13)
SELECT CountryCode, Language
FROM CountryLanguage
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 9
WHERE Language = 'Chinese'
ORDER BY CountryCode DESC
LIMIT 2;

-- Step (14)
SELECT *
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

FROM Country
WHERE GNP > GNPOld
ORDER BY Name
LIMIT 3\G

-- Step (15)
EXIT

Practice 7-2: Perform Basic Queries Using MySQL Workbench


No scripts for this practice
to
Practice 7-3: Perform Basic Queries on the Pets Database
A 1n ense
-- Step (1)
C 3% le lic
l% erab
-- At command prompt:
mysql -u root -poracle
n c
2 0I ansf
-- From mysql client prompt:
l l a % n-tr
USE Pets
a i
d a no
b
o as eฺ
-- Step (2) B
ra x) h t Gu i d
DESC pet_info; n d
l e ja dyฺm den
-- Step (3)
2 0Apet_infoฺ ua (pName,S tu
INSERT l INTO
r e
% ('Fluffy',o h s
i'F', '2003-02-04',
pGender, pBday, pDday, oID, tID)
e r
o se t
Ya ('Claws',
VALUES
c u '2004-03-17', NULL, 2, 1),
NULL, 1, 1),

i l l a@ 'M',

b a d ('Buffy', 'F', '1999-05-13', NULL, 1, 2);

l ฺbo
ya e -- Step (4)
( SHOW TABLES;

-- Step (5)
SELECT * FROM pet_info;

-- Step (6)
SELECT * FROM pet_info LIMIT 1;

-- Step (7)
SELECT oID FROM pet_info WHERE pName = 'Fluffy';

-- Step (8)
SELECT pName FROM pet_info
WHERE tID = 1 AND pBday > '2003-01-01';

-- Step (9)
SELECT DISTINCT pGender FROM pet_info;
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 10
-- Step (10)
SELECT pName, tID FROM pet_info WHERE tID != 1;

-- Step (11)
SELECT pID, pName FROM pet_info
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

WHERE pName IN ('Claws', 'Buffy');

-- Step (12)
SELECT pID, pName from pet_info
WHERE oID = 1
AND (tID = 2 OR tID=3);

-- Step (13)
SELECT pName, pBday FROM pet_info
ORDER BY pBday ASC;

to
1n ense
-- Step (14)
SELECT pID, pName, pBday FROM pet_info A
ORDER BY pBday DESC;
C 3% le lic
n c l% erab
0I ansf
-- Step (15)
EXIT 2
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 11
Lesson 8: Database and Table Maintenance
Practice 8-1: Remove a Database
-- Step (1)
-- At command prompt:
mysql -uroot -poracle
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-- At mysql prompt:
CREATE DATABASE db1;

-- Step (2)
SHOW DATABASES;

-- Step (3)
DROP DATABASE db1;

-- Step (4) to
SHOW DATABASES;
A 1n ense
3 % e lic
Practice 8-2: Create a New Table and Remove a Table
l % C bl
c r a
-- Step (1)
2 0In ansfe
a% on-tr
USE world_innodb
i l l
SHOW CREATE TABLE City\G
o bad s a n eฺ
r a B ha uid
-- Step (2)
d x ) G
CREATE TABLE GelderlandDist
e
SELECT Name, lDistrict,
ฺm ASdent
jan dyCountryCode
FROM City 2 0A oฺua s Stu
WHERE
a el% r
District
o e hi
re= 'Gelderland';
t
Y @ c us
-- Stepa
ill TABLES;
(3)
a d
SHOW

l ฺ b ob
yae
-- Step (4)
( SELECT * FROM GelderlandDist;

-- Step (5)
CREATE TABLE GelderlandDist2 LIKE GelderlandDist;

DESC GelderlandDist2;

-- Step (6)
SHOW TABLES;

-- Step (7)
DROP TABLE IF EXISTS GelderlandDist2;

-- Step (8)
SHOW TABLES;

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 12
Practice 8-3: Alter Table Columns
-- Step (1)
DESCRIBE GelderlandDist;

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

ALTER TABLE GelderlandDist MODIFY Name char(20);

-- Step (3)
DESCRIBE GelderlandDist;

-- Step (4)
ALTER TABLE GelderlandDist ADD Inauguration DATE NOT NULL;

-- Step (5)
DESCRIBE GelderlandDist;
to
-- Step (6)
SELECT * FROM GelderlandDist; A 1n ense
C 3% le lic
Practice 8-4: Modify Table Indexes and Constraints
n c l% erab
-- Step (1) 0 I n s f
2
SHOW CREATE TABLE City\G
i l l a% on-tra
-- Step (2)
o b ad a n ฺ
ALTER TABLE City ADD INDEX
r a ) h as uide
B CityName(Name);
j a nd yฺmx ent G
-- Step (3)
le City\G
SHOW CREATEATABLE ad Stud
2 0 ฺ u
e l % (4) rreo this
Y a TABLE
-- Step
ALTER @ co City
u e INDEX CityName;
sDROP
d i lla
b o ba-- Step (5)

e l ฺ SHOW CREATE TABLE City\G

( ya -- Step (6)
DESCRIBE GelderlandDist;

-- Step (7)
ALTER TABLE GelderlandDist ADD PRIMARY KEY(Name);

-- Step (8)
DESC GelderlandDist;

Practice 8-5: Further Practice


-- Step (1)
SHOW CREATE TABLE City\G;

-- Step (2)
CREATE TABLE Big_Cities
SELECT id, name, population from City
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 13
WHERE population > 8000000;

SHOW TABLES;

-- Step (3)
DESC Big_Cities;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-- Step (4)
SELECT * FROM Big_Cities;

-- Step (5)
ALTER TABLE Big_Cities ADD COLUMN Founded DATE NULL;

DESC Big_Cities;

-- Step (6)
SELECT * FROM Big_Cities;
to
-- Step (7) A 1n ense
ALTER TABLE Big_Cities DROP Founded;
C 3% le lic
n c l% erab
0I ansf
DESC Big_Cities;
2
-- Step (8)
i l l a% on-tr
ALTER TABLE Big_Cities MODIFY
o badID sINT(11)
a n NULL;
e ฺ
DESC Big_Cities; B
ra x) h t Gua i d
n d
a dyฺm den
-- Step (9) lej
ALTER TABLE 2 0ABig_Cities
ฺ u
ua sADDStPRIMARY KEY (ID);
% e o i
Y aelBig_Cities;
DESC c orr se th
l l a @ u
i
d Step (10)
obaALTER TABLE Big_Cities ADD INDEX Pop (Population);
--

e l ฺb
( ya DESC Big_Cities;

SHOW CREATE TABLE Big_Cities\G

-- Step (11)
ALTER TABLE Big_Cities DROP INDEX Pop;

DESC Big_Cities;

SHOW CREATE TABLE Big_Cities\G

-- Step (12)
DROP TABLE Big_Cities;

SHOW TABLES;

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 14
-- Step (13)
EXIT
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 15
Lesson 9: Table Data Manipulation
Practice 9-1: Insert and Replace Table Row Data
-- Step (1)
-- At command prompt:
mysql -uroot -poracle
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-- At mysql prompt:
USE world_innodb

INSERT INTO GelderlandDist (Name, District, CountryCode,


Inauguration)
VALUES ('Sakila', 'Gelderland', 'SQL', '2001-07-01');

-- Step (2)
SELECT * FROM GelderlandDist;
to
-- Step (3)
A 1n ense
INSERT INTO GelderlandDist (Name, District, CountryCode,
Inauguration) C 3% le lic
c l% erab
VALUES ('MySQLland', 'Gelderland', 'MYS', '1984-08-04'),
n
0I ansf
('Fantasia', 'Gelderland', 'FNT', '1950-01-01');
2
i l l a% on-tr
bad s a n eฺ
-- Step (4)
SELECT * FROM GelderlandDist;
o
B ha
d r a x ) G uid
-- Step (5)
j a n yฺm (Name, e n t District, CountryCode,
e
REPLACE INTO GelderlandDist
Al ฺuad Stud
Inauguration)
2 0
e l % rreo th'Gelderland',
VALUES ('MySQLland', is 'SQL', '1984-08-04');

Y a
-- Step @ co use
(6)
d i
SELECTlla * FROM GelderlandDist;
l oba
ฺb
Practice 9-2: Modify and Delete Table Row Data
y a e
( -- Step (1)
UPDATE GelderlandDist
SET Inauguration = '1880-05-17'
WHERE Name = 'Ede';

-- Step (2)
SELECT * FROM GelderlandDist;

-- Step (3)
UPDATE GelderlandDist
SET CountryCode = 'FOO'
WHERE CountryCode = 'NLD'
ORDER BY Name
LIMIT 2;

-- Step (4)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 16
SELECT * FROM GelderlandDist;

-- Step (5)
DELETE FROM GelderlandDist
WHERE CountryCode = 'FOO'
LIMIT 1;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-- Step (6)
SELECT * FROM GelderlandDist;

-- Step (7)
SELECT * FROM City WHERE CountryCode = 'FOO';

-- Step (8)
DELETE FROM GelderlandDist
WHERE CountryCode = 'FOO'
LIMIT 1;
to
Practice 9-3: Manipulate Table Row Data in the Pets Database A 1n ense
-- Step (1) C 3% le lic
USE Pets
n c l% erab
0 I n s f
2
-- Step (2)
SELECT * FROM pet_info; i l l a% on-tra
o b ad a n ฺ
-- Step (3)
r a ) h as upBday,
B pGender, ide pDday, oID, tID)
INSERT INTO pet_info
VALUES j a nd yฺmx ent G
(pName,

A le ad tud
('Fang','M','2000-08-27',NULL,3,2),
2 0 ฺ u S
e l % rreo this
('Bowser','M','1989-08-31','2009-07-29',4,2),

Y a
@ co use
('Chirpy','F','2008-09-11',NULL,2,3),
('Whistler',NULL,'2007-12-09',NULL,2,4),
i lla
('Slim','M','2006-04-29',NULL,3,5),
d
b o ba('Puffball','F','2009-03-30',NULL,4,1),
e l ฺ ('Opus','F',NULL,NULL,5,1),

( ya ('Rocky','M','1998-04-04','2013-02-11',6,1),
('Koko','M','1997-02-08',NULL,3,1),
('Scruffy','M','2008-04-17',NULL,2,1);

SELECT * FROM pet_info;

-- Step (4)
INSERT INTO owners (oName, oPhone) VALUES
('Harold', '15554159855'),
('Gwen', '15551234567'),
('Benny', '15553456789'),
('Diane', '15554567890'),
('Caryn', '15554444444'),
('Chris', '15556666666');

SELECT * FROM owners;

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 17
-- Step (5)
INSERT INTO pet_types (pType, pCategory) VALUES
('Cat', 'Mammal'),
('Dog', 'Mammal'),
('Parrot', 'Bird'),
('Canary', 'Bird'),
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

('Snake', 'Reptile'),
('Hamster', 'Mammal'),
('Ferret', 'Mammal');

SELECT * FROM pet_types;

-- Step (6)

UPDATE pet_info
SET pGender = 'M'
WHERE pName = 'Whistler';
to
SELECT * FROM pet_info; A 1n ense
3 % e lic
-- Step (7) C
l% erabl
INSERT INTO pet_types (pType, pCategory) nc
VALUES ('Iguana', 'Reptile'); 2 0I ansf
i l l a% on-tr
SELECT * FROM pet_types;
o bad s a n eฺ
r a B ha uid
UPDATE pet_info
d x ) G
SET tID = 8
jan dyฺm dent
WHERE pName =le'Slim';
2 0A oฺua s Stu
el%* cFROM
SELECT
a o e thi
rrepet_info;
Y @(8) us
l l
-- Step a
b a di * FROM owners;
SELECT

l ฺbo
ya e UPDATE pet_info SET oID = 3
( WHERE oID = 1 AND pName = 'Buffy';

SELECT * FROM pet_info;

-- Step (9)
UPDATE owners
SET oPhone = '16163429988'
WHERE oName IN ('Caryn', 'Chris');

SELECT * FROM owners;

-- Step (10)
DELETE FROM pet_info
WHERE pBday < '2000-01-01';

SELECT * FROM pet_info;

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 18
-- Step (11)
SELECT DISTINCT oID FROM pet_info;

SELECT * FROM owners;


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

DELETE FROM owners WHERE oID = 6;

SELECT * FROM owners;

-- Step (12)
REPLACE INTO pet_info (pID, pName, pGender, pBday, pDday, oID,
tID)
VALUES (9,'Chewy','F', NULL, NULL,6,6);

SELECT * FROM pet_info;

to
1n ense
-- Step (13)
INSERT INTO owners (oID, oName, oPhone) A
VALUES (6,'Olga','18563330000');
C 3% le lic
n c l% erab
0I ansf
SELECT * FROM owners;
2
-- Step (14)
i l l a% on-tr
EXIT
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 19
Lesson 10: Functions
Practice 10-1: Quiz
No scripts for this practice

Practice 10-2: Use Simple, String, and Temporal Functions


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

-- Step (1)
-- At command prompt:
mysql -uroot -poracle

-- At mysql prompt:
SELECT VERSION();

-- Step (2)
SELECT strcmp('awake','asleep'),
strcmp('awake','awake'),
to
strcmp('asleep','awake');
A 1n ense
-- Step (3) 3 % e lic
SELECT CONCAT('I ','am ','mostly ', 'awake!');
l C
% rabl
c
-- Step (4) 2 0In ansfe
SELECT SUBSTRING('HarryMonkey', l6);
i l a% on-tr
o bad s a n eฺ
-- Step (5)
r a B ha uid
-- no script
d x ) G
-- Step (6) lej
an dyฺm dent
2 0A oฺua s S'%W
SELECT DATE_FORMAT(NOW(), tu the %D of %M in the year %Y');
e l% orre t h i
Y a
-- Step (7) c us e
ll a @
d i
SELECT DAYNAME(NOW() + INTERVAL 500 DAY);

ฺboba
Practice 10-3: Use Numeric and Control Flow Functions
l
ya e -- Step (1)
( SELECT FLOOR(-8.6), FLOOR(8.6);

-- Step (2)
USE world_innodb

SELECT IndepYear, Name,


CASE
WHEN IndepYear < 1300 then 'Ancient'
WHEN IndepYear < 1800 then 'Really Old'
WHEN IndepYear < 1900 then 'Not Old'
WHEN IndepYear < 2000 then 'New'
ELSE 'Brand New'
END
FROM Country
ORDER BY IndepYear DESC;

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 20
Practice 10-4: Use Aggregate Functions
-- Step (1)
USE world_innodb

SELECT Continent, SUM(Population)


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

FROM Country
GROUP BY Continent;

-- Step (2)
SELECT Continent, ROUND(AVG(LifeExpectancy))
FROM Country
GROUP BY Continent;

-- Step (3)
SELECT CountryCode, AVG(Population) AS AvgPop
FROM City
to
GROUP BY CountryCode
HAVING AVG(Population) > 500000; A 1n ense
3 % e lic
l % C bl
-- Step (4)
c r a
SELECT GovernmentForm, COUNT(GovernmentForm)
FROM Country 2 0In ansfe
AS Governments

GROUP BY GovernmentForm
i l l a% on-tr
ORDER BY Governments DESC
o bad s a n eฺ
LIMIT 5;
r a B ha uid
d
n yฺm ent x ) G
-- Step (5)
l e j a d d
FROM Country 0 A
SELECT Continent,
2 eoฺ u S t u
AVG(SurfaceArea)
a AS AverageSurfaceArea

GROUPl% r h i s
ae cor se t
BY Continent;
Y
l
-- Step
i l a@(6) u
d Continent, AVG(SurfaceArea) AS AverageSurfaceArea
obaFROM Country
SELECT

e l ฺb
ya
GROUP BY Continent
( WITH ROLLUP;

-- Step (7)
EXIT

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 21
Lesson 11: Exporting and Importing Data
Practice 11-1: Quiz
No scripts for this practice

Practice 11-2: Export Files Using a Query


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

-- Step (1)
-- At command prompt:
mysql -uroot -poracle

-- At mysql prompt:
USE Pets

-- Step (2)
SELECT *
INTO OUTFILE 'D:/labs/pet_info.txt'
to
1n ense
FROM pet_info;
A
SELECT * FROM pet_info;
C 3% le lic
n c l% erab
0I ansf
-- Step (3)
SELECT *
INTO OUTFILE 'D:/labs/owners.txt'a%
2 tr
i l l n -
FIELDS TERMINATED BY ','
b a d a no
ENCLOSED BY '"'
B o as i d eฺ
LINES TERMINATED BY '\r'
n d ra x) h t Gu
ja dyฺm den
FROM owners;
l e
-- Step (4)
2 0A oฺua s Stu
el% corre e thi
USE world_innodb
a
Y @ us
SELECT
i l l a * INTO OUTFILE 'D:/labs/CountryLanguage.txt'
d
oba
FROM CountryLanguage;

e l ฺb
Practice 11-3: Import Files from a Data File
( ya -- Step (1)
USE Pets

CREATE TABLE pet_info2 LIKE pet_info;

SHOW TABLES LIKE 'pet_info%';

-- Step (2)
LOAD DATA INFILE 'D:/labs/pet_info.txt'
INTO TABLE pet_info2;

-- Step (3)
SELECT * FROM pet_info2;

-- Step (4)
USE world_innodb
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 22
CREATE TABLE CountryLanguage2 LIKE CountryLanguage;

-- Step (5)
LOAD DATA INFILE 'D:/labs/CountryLanguage.txt'
INTO TABLE CountryLanguage2;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

SELECT COUNT(*) FROM CountryLanguage2;

Practice 11-4: Backup Database Files with a Utility


-- Step (1)
-- At command prompt:
mysqldump -uroot -poracle world_innodb >
D:/labs/world_innodb_backup.sql

-- Step (2)
-- At command prompt: to
mysqldump -uroot -poracle --skip-opt world_innodb >
A 1n ense
3% le lic
D:/labs/world_innodb_backup2.sql
C
l% erab
-- Step (3)
I n c f
-- At mysql prompt:
2 0 n s
CREATE DATABASE world_innodb2;
i l l a% on-tra
SHOW DATABASES;
o bad s a n eฺ
r a B ha uid
EXIT d
n yฺm ent x ) G
e j a
-- Step (4)Al ad Stud
2 0 prompt: ฺ u
e l %
-- At command
r r eo thiworld_innodb2
s
Y a
mysql
c o
-uroot -poracle
e <

l l a @ us
D:/labs/world_innodb_backup2.sql

b a di -uroot -poracle
mysql
l ฺbo
ya e -- At mysql prompt:
( SHOW DATABASES;

USE world_innodb2

SHOW TABLES;

-- Step (5)
EXIT

--Step (6)
-- At command prompt:
mysqldump -uroot -poracle --tab=D:/labs world_innodb Country

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 23
Lesson 12: Joining Tables
Practice 12-1: Perform Inner and Outer Joins
-- Step (1)
-- At command prompt:
mysql -uroot -poracle
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-- At mysql prompt:
USE world_innodb

DESC City;

DESC Country;

DESC CountryLanguage;

SELECT Name FROM City WHERE Name = 'San Antonio'; to


A 1n ense
SELECT Country.Name, City.District
FROM Country C 3% le lic
INNER JOIN City
n c l% erab
ON CountryCode = Code 0 I n s f
2
WHERE City.Name = 'San Antonio'; %
i l l a on-tra
-- Step (2)
o b ad a n ฺ
SELECT City.Name AS CapitalName,
r a B hasCountry.Name
) u ide AS CountryName
FROM City
j a nd yฺmx ent G
INNER JOIN Country
ON City.ID A
e ad
= lCountry.Capital; tud
2 0 ฺ u S
el% (3) r r eo this
--aStep
Y
SELECT@ co uASseCountryName, ci.Name AS CityName
co.Name
d i
FROM llaCountry AS co
l ฺbobaLEFT JOIN City AS ci
ON co.Capital = ci.ID
ya e WHERE co.Code IN ('CHE', 'ATA');
(
-- Step (4)
SELECT co.Name AS CountryName, ci.Name AS CityName
FROM Country AS co
RIGHT JOIN city AS ci
ON co.Capital = ci.ID
WHERE co.Code IN ('CHE', 'ATA');

Practice 12-2: Create Queries Requiring Joins


-- Step (1)
SELECT Name, Language
FROM CountryLanguage, Country
WHERE CountryCode = Code
AND Name = 'Sweden';

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 24
-- Step (2)
SELECT Name, Language
FROM CountryLanguage
INNER JOIN Country
ON CountryCode = Code;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-- Step (3)
SELECT Name, Language
FROM Country
LEFT JOIN CountryLanguage
ON CountryCode = Code;

-- Step (4)
SELECT Country.Name, COUNT(City.Name) AS Cities
FROM Country
INNER JOIN City
ON City.CountryCode = Country.Code
to
1n ense
GROUP BY Country.Name
ORDER BY Cities DESC A
LIMIT 1;
C 3% le lic
n c l% erab
0I ansf
-- Step (5)
SELECT DISTINCT Country.Name FROM Country 2
INNER JOIN City ON Code = CountryCode
i l l a% on-tr
WHERE City.Population > 7000000;
o bad s a n eฺ
r a B ha uid
-- Step (6)
d
n yฺm entx ) G
USE Pets
l e j a
2
DESC pet_info;0A oฺuad s Stud
a
% rre
elowners;o e t hi
Y @c us
DESC

d i llapet_types;
oba
DESC

e l ฺb -- Step (7)
( ya SELECT owners.oName
FROM owners
JOIN pet_info
ON owners.oID = pet_info.oID
WHERE oPhone LIKE '1555%' AND pGender = 'F';

-- Step (8)
SELECT oID, pName, pet_types.pType
FROM pet_info
RIGHT JOIN pet_types
ON pet_info.tID = pet_types.tID;

SELECT oID, pName, pet_types.pType


FROM pet_info
LEFT JOIN pet_types
ON pet_info.tID = pet_types.tID;

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 25
SELECT oID, pName, pet_types.pType
FROM pet_info
INNER JOIN pet_types
ON pet_info.tID = pet_types.tID;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-- Step (9)
-- If you are not doing the next/optional practice:
EXIT

Optional Practice 12-3: Additional Join Practice


-- Step (1)
USE world_innodb

SELECT DISTINCT Name, Language


FROM CountryLanguage, Country
WHERE CountryCode = Code to
AND Name = 'Sweden';
A 1n ense
-- Step (2) C 3% le lic
SELECT Name, Language
n c l% erab
FROM CountryLanguage, Country 0 I n s f
2
WHERE CountryCode = Code
AND Name = 'Sweden' i l l a% on-tra
ORDER BY Language DESC;
o bad s a n eฺ
r a B ha uid
-- Step (3) d
n yฺm entx ) G
j
SELECT Name, Language
e a
2 Al ฺuad Stud
FROM CountryLanguage
0Country
LEFT JOIN
e l % rreo= Codethis
Y a
@ co u=s'French';
ON CountryCode
WHERE Language e
d i lla
oba
-- Step (4)

e l ฺb SELECT Name, Language

( ya FROM Country
LEFT JOIN CountryLanguage
ON CountryCode = Code
WHERE Language IS NULL;

-- Step (5)
-- no script

-- Step (6)
SELECT Name, Language
FROM Country
RIGHT JOIN CountryLanguage
ON CountryCode = Code
WHERE Language IS NULL;

-- Step (7)
SELECT Country.Name FROM Country
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 26
INNER JOIN City ON Code = CountryCode
WHERE City. Population > 7000000;

-- Step (8)
EXIT
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 27
Lesson 13: Table Subqueries
Practice 13-1: Perform Different Types of Subquery
-- Step (1)
-- At command prompt:
mysql -uroot -poracle
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-- At mysql prompt:
USE world_innodb

SELECT Population
FROM City
WHERE Name = 'New York';

SELECT Name
FROM City
WHERE Population > to
(SELECT Population
A 1n ense
FROM City
WHERE Name = 'New York') C 3% le lic
ORDER BY Population
n c l% erab
LIMIT 3;
2 0I ansf
i l l a% on-tr
ad a n ฺ
-- Step (2)
SELECT Country.Name,
o b
(SELECT COUNT(*)
r a B has uide
FROM City
n x )
d= Country.Code) t G
j a
le ady tude
WHERE CountryCode ฺ m n
0
AS CityCount
2 A ฺu is S
%
FROM Country
e o
el Regionrr= 'Nordic th Countries';
Ya @co use
WHERE

lla (3)
-- iStep
d
l ฺbobaSELECT Code
FROM Country
ya e WHERE Name='Singapore';
(
SELECT Language
FROM CountryLanguage
WHERE CountryCode =
(SELECT Code
FROM Country
WHERE Name='Singapore')
ORDER BY Language DESC;

Practice 13-2: Perform Advanced Subqueries


-- Step (1)
SELECT CountryCode
FROM CountryLanguage
WHERE Language='English'
AND Percentage>50;

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 28
SELECT DISTINCT Continent
FROM Country
WHERE Code IN
(SELECT CountryCode
FROM CountryLanguage
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

WHERE Language='English'
AND Percentage>50);

-- Step (2)
SELECT CountryCode
FROM CountryLanguage
WHERE Language = 'Spanish';

SELECT Name
FROM Country
WHERE Continent = 'Europe'
to
1n ense
AND Code IN
(SELECT CountryCode A
FROM CountryLanguage
C 3% le lic
WHERE Language = 'Spanish')
n c l% erab
0I ansf
ORDER BY Name;
2
-- Step (3)
i l l a% on-tr
SELECT MAX(Population) FROM City;
o bad s a n eฺ
SELECT Country.Name ra B ha Guid
FROM Country JOINnCity m d x ) t
l e j a yฺ e n
0A oฺuad =s Stud
ON Country.Code=City.CountryCode
2
WHERE City.Population
el% MAX(Population)
(SELECT
a o r re
e t hi FROM City);
Y @ c us
a
ill * FROM Country c1
-- Step (4)
a d
SELECT

l ฺbob WHERE Continent = 'South America'


ya e AND Population =
( (SELECT MIN(Population)
FROM Country c2
WHERE c2.Continent = c1.Continent)\G

SELECT MIN(Population)
FROM Country c2
WHERE c2.Continent = c1.Continent;

-- Step (5)
SELECT MIN(Population) FROM Country
WHERE Continent = 'South America';

SELECT * FROM Country


WHERE Continent = 'South America'
AND Population =
(SELECT MIN(Population)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 29
FROM Country
WHERE Continent = 'South America')\G

SELECT * FROM Country c1


WHERE Continent = 'South America'
AND Population =
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

(SELECT MIN(Population)
FROM Country c2
WHERE c2.Continent = c1.Continent)\G

-- Step (6)
EXIT;

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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 30
Lesson 14: MySQL GUIs
No scripts for this lesson
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
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 31
Lesson 15: Supplemental Information
Practice 15-1: Displaying Storage Engine Information
-- Step (1)
-- At command prompt:
mysql -uroot -poracle
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

-- At mysql prompt:
USE world_innodb

SHOW CREATE TABLE CountryLanguage\G

-- Step (2)
SHOW TABLE STATUS LIKE 'City'\G

-- Step (3)
SHOW ENGINES\G to
Practice 15-2: Display and Create Views
A 1n ense
-- Step (1)
USE world_innodb C 3% le lic
n c l% erab
SHOW FULL TABLES;
2 0I ansf
i l l a% on-tr
ad a n ฺ
-- Step (2)
CREATE VIEW CityView AS
o b
SELECT ID, Name FROM City;
r a B has uide
a n d mx) nt G
lej adyฺ tude
SHOW FULL TABLES;
A
-- Step 2
0 oฺu s S
% rre e thi
(3)
a el cCityView;
DESCRIBE o
Y @ s
l l
-- iStepa (4) u
d
l ฺbobaSELECT COUNT(*) FROM CityView;
e
ya Practice 15-3: Obtain Metadata
( -- Step (1)
SHOW DATABASES;

-- Step (2)
SHOW TABLES FROM INFORMATION_SCHEMA;

-- Step (3)
SELECT * FROM information_schema.schemata
WHERE SCHEMA_NAME = 'world_innodb'\G

-- Step (4)
DESC INFORMATION_SCHEMA.TABLES;

SELECT table_name, table_type, engine


FROM information_schema.tables

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 32
WHERE table_schema = 'world_innodb'
ORDER BY table_name DESC;

-- Step (5)
SELECT table_name, create_time, auto_increment
FROM information_schema.tables
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

WHERE table_schema = 'pets'


ORDER BY table_name DESC;

-- Step (6)
EXIT

Optional Practice 15-4: Create a Backup of MySQL Databases


-- Step (1)
-- Using Windows Explorer go to D:\labs

-- Step (2) to
-- At command prompt:
A 1n ense
3% le lic
mysqlbackup --user=root --password=oracle --port=3306 --with-
timestamp --backup- C
l% erab
n c
dir=D:/labs/backups backup
2 0I ansf
-- Step (3) i l l a% on-tr
-- Using Windows Explorer go
o batod D:\labs\backups
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 ฺbo
ya e
(

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 33
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2016, Oracle and/or its affiliatesฺ

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

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix B: Practice Solution Scripts


Chapter 18 - Page 34

You might also like