MySQL For Database Administrators (Activity Guide) [PDF]

  • 0 0 0
  • Gefällt Ihnen dieses papier und der download? Sie können Ihre eigene PDF-Datei in wenigen Minuten kostenlos online veröffentlichen! Anmelden
Datei wird geladen, bitte warten...
Zitiervorschau

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

e

s

bl a r fe

an r t n

er e f a

no a s ฺ a MySQL for hDatabase ) de i m Administrators u o ฺc nt G n e e uGuide de atActivity t w S @ s i n h ha se t k ฺ r ee e to u f a (s ens n a lic Kh

S

D61762GC30 Edition 3.0 March 2013 D81030

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

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

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. 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

s

an r t n

Oracle and Java are registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

Sa

e

bl a r fe

no a s ฺ a h Author ) de i m u o Jeremy Smyth ฺc nt G n e de Technical Contributors and Reviewers ate u t w S Jonathon Coombes, Sneha Modi, Mark Lewin, Horst Hunger, Andrew Morgan, Todd Farmer, @ s i n h t Loh, Mattias Jonsson, Chuck Bell, ha Kim Bob Falasco, Saikumar Vishvanatha, Seong e k ฺ s r u Ingo Strüwing, Matt Lord, Matthelié eeBertrand o f t a (s ense n a published This book hwas lic using: Oracle Tutor K r fee

Table of Contents

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

Practices for Lesson 1: Introduction to MySQL ....................................................................................... 1-1 Practices for Lesson 1............................................................................................................................. 1-2 Practices for Lesson 2: Architecture........................................................................................................ 2-1 Practices for Lesson 2: Overiew .............................................................................................................. 2-2 Practice 2-1: Quiz – Architecture Overview .............................................................................................. 2-3 Solutions 2-1: Quiz – Architecture Overview............................................................................................. 2-5 Practices for Lesson 3: System Administration....................................................................................... 3-1 Practices for Lesson 3: Overview............................................................................................................. 3-2 Practice 3-1: Installing the MySQL Server ................................................................................................ 3-3 Solutions 3-1: Installing the MySQL Server .............................................................................................. 3-4 Practice 3-2: MySQL Data Directory ........................................................................................................ 3-7 Solutions 3-2: MySQL Data Directory....................................................................................................... 3-9 Practice 3-3: Starting and Stopping the MySQL Server............................................................................. 3-12 Solutions 3-3: Starting and Stopping the MySQL Server ........................................................................... 3-13

s

an r t n

Practices for Lesson 4: Server Configuration .......................................................................................... 4-1 Practices for Lesson 4: Overview............................................................................................................. 4-2 Practice 4-1: Quiz – MySQL Server Configuration .................................................................................... 4-3 Solutions 4-1: Quiz – MySQL Server Configuration .................................................................................. 4-5 Practice 4-2: Editing and Creating a Configuration File ............................................................................. 4-6 Solutions 4-2: Editing and Creating a Configuration File ........................................................................... 4-8 Practice 4-3: Additional Practice – Server Configuration ........................................................................... 4-14 Solutions 4-3: Additional Practice – Server Configuration ......................................................................... 4-16

Sa

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n Practices for Lesson 5: Clients and Tools ............................................................................................... 5-1 a t h e k Practices for Lesson 5: Overview ............................................................................................................. 5-2 ฺ s r Client o.................................................................................................... u e e Practice 5-1: Invoking the mysql 5-3 f t athe e s Solutions 5-1: Invoking mysql Client ................................................................................................... 5-4 s ( n the en Client ........................................................................................... 5-9 aInvoking Practice 5-2: mysqladmin c i h l K 5-2: Invoking the mysqladmin Client ......................................................................................... 5-10 Solutions r e fePractice 5-3: Viewing the MySQL Enterprise Monitor Demos .................................................................... 5-12

Practice 5-4: Performing System Administration Tasks with MySQL Workbench ....................................... 5-13 Solutions 5-4: Performing System Administration Tasks with MySQL Workbench...................................... 5-14 Practices for Lesson 6: Data Types.......................................................................................................... 6-1 Practices for Lesson 6: Overview............................................................................................................. 6-2 Practice 6-1: Quiz – MySQL Data Types .................................................................................................. 6-3 Solutions 6-1: Quiz – MySQL Data Types ................................................................................................ 6-4 Practice 6-2: Setting a Data Type ............................................................................................................ 6-5 Solutions 6-2: Setting a Data Type........................................................................................................... 6-6 Practices for Lesson 7: Obtaining Metadata ............................................................................................ 7-1 Practices for Lesson 7: Overview............................................................................................................. 7-2 Practice 7-1: Obtaining Metadata by Using INFORMATION_SCHEMA........................................................ 7-3 Solutions 7-1: Obtaining Metadata by Using INFORMATION_SCHEMA ...................................................... 7-4 Practice 7-2: Obtaining Metadata by Using SHOW and DESCRIBE.......................................................... 7-7 Solutions 7-2: Obtaining Metadata by Using SHOW and DESCRIBE ........................................................ 7-8 Practice 7-3: Obtaining Metadata by Using mysqlshow .......................................................................... 7-13 Solutions 7-3: Obtaining Metadata by Using mysqlshow ........................................................................ 7-14 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

MySQL for Database Administrators Table of Contents iii

e

bl a r fe

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

Practices for Lesson 8: Transactions and Locking.................................................................................. 8-1 Practices for Lesson 8: Overview............................................................................................................. 8-2 Practice 8-1: Quiz – Transactions and Locking......................................................................................... 8-3 Solutions 8-1: Quiz – Transactions and Locking ....................................................................................... 8-5 Practice 8-2: Using Transaction Control Statements ................................................................................. 8-6 Solutions 8-2: Using Transaction Control Statements ............................................................................... 8-7 Practice 8-3: Additional Practice with Transactions and Locking ............................................................... 8-11 Solutions 8-3: Additional Practice with Transactions and Locking.............................................................. 8-12 Practices for Lesson 9: Storage Engines ................................................................................................. 9-1 Practices for Lesson 9: Overview............................................................................................................. 9-2 Practice 9-1: Quiz – InnoDB Storage Engine............................................................................................ 9-3 Solutions 9-1: Quiz – InnoDB Storage Engine .......................................................................................... 9-4 Practice 9-2: Setting and Confirming InnoDB Settings .............................................................................. 9-5 Solutions 9-2: Setting and Confirming InnoDB Settings ............................................................................ 9-6

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e Practices for Lesson 11: User Management............................................................................................. 11-1 te tude a Practices for Lesson 11: Overview ........................................................................................................... 11-2 w..................................................................................... S @ Practice 11-1: Quiz – MySQL User Management 11-3 s i n h a t Solutions 11-1: Quiz – MySQL Userh 11-5 ฺkandManagement sea.................................................................................... r u Practice 11-2: Creating, Verifying, Dropping User ........................................................................... 11-7 e feVerifying,eandtoDropping a User ......................................................................... 11-8 a Solutions 11-2: Creating, s ( nsfor the world_innodb Database .............................................................. 11-9 Practice 11-3:n Setting Up ae User a c h11-3: SettingliUp a User for the world_innodb Database............................................................. 11-10 Solutions K r e 11-4: Using the PAM Authentication Plugin................................................................................. 11-13 Practice afeSolutions 11-4: Using the PAM Authentication Plugin ............................................................................... 11-15

S

Practice 11-5: Additional Practice ............................................................................................................ 11-19 Solutions 11-5: Additional Practice........................................................................................................... 11-21 Practices for Lesson 12: Security ............................................................................................................ 12-1 Practices for Lesson 12: Overview ........................................................................................................... 12-2 Practice 12-1: Quiz – MySQL Security ..................................................................................................... 12-3 Solutions 12-1: Quiz – MySQL Security ................................................................................................... 12-5 Practice 12-2: Determining the Status of SSL Connectivity ....................................................................... 12-6 Solutions 12-2: Determining the Status of SSL Connectivity ..................................................................... 12-7 Practice 12-3: Additional Practice – Enabling MySQL Support for SSL Connections .................................. 12-8 Solutions 12-3: Additional Practice – Enabling MySQL Support for SSL Connections ................................ 12-9 Practices for Lesson 13: Table Maintenance ........................................................................................... 13-1 Practices for Lesson 13: Overview ........................................................................................................... 13-2 Practice 13-1: Quiz – Table Maintenance................................................................................................. 13-3 Solutions 13-1: Quiz – Table Maintenance ............................................................................................... 13-5 Practice 13-2: Using Table Maintenance SQL Statements ........................................................................ 13-6 Solutions 13-2: Using Table Maintenance SQL Statements ...................................................................... 13-7 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

MySQL for Database Administrators Table of Contents iv

e

bl a r fe

Practices for Lesson 10: Partitioning ....................................................................................................... 10-1 Practices for Lesson 10: Overview ........................................................................................................... 10-2 Practice 10-1: Quiz – MySQL Partitioning ................................................................................................ 10-3 Solutions 10-1: Quiz – MySQL Partitioning............................................................................................... 10-5 Practice 10-2: Creating and Modifying a Partitioned Table ........................................................................ 10-6 Solutions 10-2: Creating and Modifying a Partitioned Table ...................................................................... 10-7 Practice 10-3: Removing Partitions from a Table ...................................................................................... 10-12 Solutions 10-3: Removing Partitions from a Table .................................................................................... 10-13

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

Practice 13-3: Using Table Maintenance Utilities ...................................................................................... 13-10 Solutions 13-3: Using Table Maintenance Utilities .................................................................................... 13-11 Practices for Lesson 14: Exporting and Importing Data .......................................................................... 14-1 Practices for Lesson 14: Overview ........................................................................................................... 14-2 Practice 14-1: Exporting MySQL Data...................................................................................................... 14-3 Solutions 14-1: Exporting MySQL Data .................................................................................................... 14-4 Practice 14-2: Importing Data .................................................................................................................. 14-6 Solutions 14-2: Importing Data ................................................................................................................ 14-7 Practices for Lesson 15: Programming Inside MySQL ............................................................................ 15-1 Practices for Lesson 15: Overview ........................................................................................................... 15-2 Practice 15-1: Creating Stored Routines .................................................................................................. 15-3 Solutions 15-1: Creating Stored Routines ................................................................................................ 15-5 Practice 15-2: Reviewing Stored Routines ............................................................................................... 15-8 Solutions 15-2: Reviewing Stored Routines .............................................................................................. 15-9 Practice 15-3: Creating a Trigger ............................................................................................................. 15-13 Solutions 15-3: Creating a Trigger ........................................................................................................... 15-14 Practice 15-4: Creating and Testing an Event .......................................................................................... 15-16 Solutions 15-4: Creating and Testing an Event ......................................................................................... 15-18

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a h se t Solutions 16-3: mysqldump ................................................................................................................... 16-19 k ฺ r u e Practice 16-4: Backup and Recovery Using LVM Snapshots and the Binary Log ....................................... 16-24 o LVM Snapshots and the Binary Log ..................................... 16-27 fe e tUsing a Solutions 16-4: Backup and Recovery s ( ens n Practices for a Lesson 17-1 hfor Lesson17:17:licReplication........................................................................................................ K Practices Overview ........................................................................................................... 17-2 er e Practice 17-1: Quiz – Replication ............................................................................................................. 17-3 f a

Practices for Lesson 16: MySQL Backup and Recovery.......................................................................... 16-1 Practices for Lesson 16: Overview ........................................................................................................... 16-2 Practice 16-1: Quiz – Introduction to Backups .......................................................................................... 16-3 Solutions 16-1: Quiz – Introduction to Backups ........................................................................................ 16-4 Practice 16-2: MySQL Enterprise Backup ................................................................................................ 16-5 Solutions 16-2: MySQL Enterprise Backup............................................................................................... 16-7 Practice 16-3: mysqldump ..................................................................................................................... 16-17

S

Solutions 17-1: Quiz – Replication ........................................................................................................... 17-5 Practice 17-2: Configuring Replication ..................................................................................................... 17-6 Solutions 17-2: Configuring Replication.................................................................................................... 17-7 Practice 17-3: Adding a New Slave.......................................................................................................... 17-15 Solutions 17-3: Adding a New Slave ........................................................................................................ 17-16 Practice 17-4: Enabling GTID and Configuring Circular Replication........................................................... 17-19 Solutions 17-4: Enabling GTID and Configuring Circular Replication ......................................................... 17-20 Practices 17-5: Using MySQL Utilities and Performing a Failover .............................................................. 17-26 Solutions 17-5: Using MySQL Utilities and Performing a Failover .............................................................. 17-28

Practices for Lesson 18: Introduction to Performance Tuning ................................................................ 18-1 Practices for Lesson 18: Overview ........................................................................................................... 18-2 Practice 18-1: Quiz – Introduction to Performance Tuning ........................................................................ 18-3 Solutions 18-1: Quiz – Introduction to Performance Tuning....................................................................... 18-5 Practice 18-2: EXPLAIN ......................................................................................................................... 18-6 Solutions 18-2: EXPLAIN ....................................................................................................................... 18-7 Practice 18-3: PROCEDURE ANALYSE..................................................................................................... 18-10 Solutions 18-3: PROCEDURE ANALYSE ................................................................................................... 18-12 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

MySQL for Database Administrators Table of Contents v

e

bl a r fe

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

Practices for Lesson 19: Conclusion ....................................................................................................... 19-1 Practices for Lesson 19 ........................................................................................................................... 19-2 Appendix: EXPLAIN Output Columns ...................................................................................................... 20-1 The EXPLAIN Statement ......................................................................................................................... 20-2 EXPLAIN Output Columns for Joins......................................................................................................... 20-4 EXPLAIN Output Columns for Table Processing ...................................................................................... 20-6 EXPLAIN Output Columns for Joins......................................................................................................... 20-7 Appendix: Practice Solutions Scripts ...................................................................................................... 21-1 Lesson 1: Introduction to MySQL ............................................................................................................. 21-2 Lesson 2: MySQL Architecture ................................................................................................................ 21-2 Lesson 3: System Administration ............................................................................................................. 21-3 Lesson 4: Server Configuration ............................................................................................................... 21-5 Lesson 5: Clients and Tools .................................................................................................................... 21-13 Lesson 6: Data Types ............................................................................................................................. 21-15 Lesson 7: Obtaining Metadata ................................................................................................................. 21-16 Lesson 8: Transactions and Locking ........................................................................................................ 21-18 Lesson 9: Storage Engines...................................................................................................................... 21-21 Lesson 10: Partitioning ............................................................................................................................ 21-23 Lesson 11: User Management ................................................................................................................. 21-25 Lesson 12: Security................................................................................................................................. 21-30 Lesson 13: Table Maintenance ................................................................................................................ 21-32 Lesson 14: Exporting and Importing Data ................................................................................................ 21-33 Lesson 15: Programming Inside MySQL .................................................................................................. 21-34 Lesson 16: MySQL Backup and Recovery ............................................................................................... 21-37 Lesson 17: Replication ............................................................................................................................ 21-45 Lesson 18: Introduction to Performance Tuning ....................................................................................... 21-51

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

MySQL for Database Administrators Table of Contents vi

e

bl a r fe

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

e

s

bl a r fe

an r t n

er e f a

no a s ฺ 1: a Practices for Lesson h e ) toidMySQL m Introduction u o ฺc nt G n e e u1 de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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 Lesson Overview

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

There are no practices for this lesson.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 1: Introduction to MySQL Chapter 1 - Page 2

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

e

s

bl a r fe

an r t n

er e f a

no a s ฺ 2: a Practices for Lesson h ) de i m Architecture u o ฺc nt G n e e u2 de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 2: Architecture Chapter 2 - Page 1

Practices for Lesson 2: Overview

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

Practices Overview In these practices, you test your knowledge of the MySQL architecture. The hands-on practices are written for the Oracle Linux operating system environment, which is provided in Oracle classrooms. For non-Oracle classrooms, some adjustments may need to be made regarding file locations.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 2: Architecture Chapter 2 - Page 2

Practice 2-1: Quiz – Architecture Overview Overview

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

In this practice, you answer questions about the MySQL architecture.

Duration This practice should take approximately 10 minutes to complete.

Quiz Questions Choose the best answer from those provided for each multiple choice or True/False question. 1. All of the MySQL client and non-client programs communicate with the MySQL server. a. True b. False 2. When running a MySQL server under Windows, client programs accessing that server also must run under Windows. a. True b. False 3. A command-line program commonly used to communicate with the MySQL server is called mysqld. a. True b. False 4. Consider the following list of ways to connect to the MySQL server. Which do not depend on the operating system? (Choose all that apply.) a. TCP/IP b. ODBC c. Shared memory d. Named pipe e. UNIX socket file 5. MySQL uses disk space to store the following: a. Server and client programs, and their libraries b. Log files and status files c. Databases d. Table format (.frm) files, data files and index files e. Internal temporary tables that have crossed the size threshold for being converted from in-memory tables to on-disk tables f. All of the above

s

o

an r t n

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

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

Practices for Lesson 2: Architecture Chapter 2 - Page 3

e

bl a r fe

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

6.

7.

The MySQL server allocates memory for the following: a. Connection handlers (every connection uses memory) b. Buffers and caches c. A copy of the grant tables d. The host cache and the table cache e. The query cache f. All of the above The MySQL server uses _________________ as memory set aside to temporarily hold data for the purpose of avoiding costly disk access I/O. a. MEMORY table b. internal temporary tables c. shared memory d. buffers (or caches)

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 2: Architecture Chapter 2 - Page 4

e

bl a r fe

Solutions 2-1: Quiz – Architecture Overview Quiz Solutions

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

1. 2. 3. 4.

5. 6. 7.

b. False. There are MySQL programs that do not communicate with the server, but work directly on data or log files. Examples include innochecksum and mysqlbinlog. b. False. MySQL can be used in heterogeneous environments. For example, a server running on a UNIX host can be accessed by clients running on Windows machines. b. False. The most commonly used command-line program is called mysql, not mysqld. The latter is the MySQL server. a, b. TCP/IP is not operating system–dependent. ODBC is also not operating system– dependent but is available for MySQL only on operating systems where MySQL Connector/ODBC is supported. f. All of those listed are stored using disk space. f. MySQL allocates memory for all of those listed. d. The MySQL server uses buffers (or caches) as memory set aside to temporarily hold data for the purpose of avoiding costly disk access I/O.

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 2: Architecture Chapter 2 - Page 5

e

bl a r fe

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

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 2: Architecture Chapter 2 - Page 6

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

e

s

bl a r fe

an r t n

er e f a

no a s ฺ 3: a Practices for Lesson h ) de i m System Administration u o ฺc nt G n e e u3 de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 3: System Administration Chapter 3 - Page 1

Practices for Lesson 3: Overview

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

Practices Overview In these practices, you test your knowledge of MySQL system administration. The hands-on practices are written for the Oracle Linux operating system environment, which is provided in Oracle classrooms. For non-Oracle classrooms, some adjustments may need to be made regarding file locations. Practices make use of a standard Linux user (oracle) and the root user. Practice steps use a $ prompt to indicate the standard user, and a # prompt to indicate the root user.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 3: System Administration Chapter 3 - Page 2

Practice 3-1: Installing the MySQL Server Overview

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

In this practice, you install the individual Linux RPM files.

Assumptions The MySQL Server Linux RPM files have been downloaded as part of the Oracle class environment and are in the /stage directory.

Duration This practice should take approximately 10 minutes to complete.

Tasks

e

1. Install the individual RPM files located in the /stage/mysql directory (as root). a. Execute the following commands for each file:

Sa



rpm -hi --replacefiles MySQL-server*.rpm



rpm -hi MySQL-client*.rpm

bl a r fe

s

an r t n

o n a • rpm -hi MySQL-devel*.rpm s ฺ a h • rpm -hi MySQL-shared*.rpm ) de i m u o • rpm -hi MySQL-test*.rpm ฺc nt G n e − If your system comes with pre-installed MySQL elibraries from a previous version, dyour ateoption u t you can add the --replacefiles to rpm install command. In the w Srequires this @ s i Oracle classroom, the server package option. n h a t h e 2. Start the MySQL server.rฺk e to us e f 3. Secure the MySQL server. a se s ( n initial root password saved in the location Note: You will need n icethe a h l /root/.mysql_secret. K r e fe For installation at your own location, see the Community Edition download files on the MySQL Downloads webpage: http://dev.mysql.com/downloads/.

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

Practices for Lesson 3: System Administration Chapter 3 - Page 3

Solutions 3-1: Installing the MySQL Server

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

Tasks 1. Install the individual RPM files located in the /stage/mysql directory (as root). a. Execute the following commands for each file in a terminal window and receive the results shown: $ su – Password: oracle # cd /stage/mysql # rpm -hi --replacefiles MySQL-server*.rpm ... A RANDOM PASSWORD HAS BEEN SET FOR THE MySQL root USER ! You will find that password in '/root/.mysql_secret'.

e

You must change that password on your first connect, no other statement but 'SET PASSWORD' will be accepted. See the manual for the semantics of the 'password expired' flag.

bl a r fe

s

an r t n

S

er e f a

no a s removed. Also, the account for the anonymous user has been a h eฺ ) d i m co t Gu In addition, you can run: ฺ n e den e t wa s Stu /usr/bin/mysql_secure_installation @ n hi a t h e k youusthe option of removing the test database. which will alsorฺgive e e This is strongly recommended for production servers. f to a e s s ( ... n n econfig a default c i h New file was created as /usr/my.cnf and l K will be used by default by the server when you start it. You may edit this file to change server settings

WARNING: Default config file /etc/my.cnf exists on the system This file will be read by default by the MySQL server ... # rpm -hi MySQL-client*.rpm # rpm -hi MySQL-devel*.rpm # rpm -hi MySQL-shared*.rpm # rpm -hi MySQL-test*.rpm

2. Start the MySQL server. a. Enter the following in a terminal window, and receive the result shown below: # service mysql start

[ OK ]

Starting MySQL..

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

Practices for Lesson 3: System Administration Chapter 3 - Page 4

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

3. Secure the MySQL server. a. Enter the following in a terminal window, enter the answers appropriate to your installation, and receive the results shown below: # cat /root/.mysql_secret # The random password set for the root user ...: TeDRFkYP # mysql -uroot -p Enter password: TeDRFkYP Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 1 Server version: 5.6.10-enterprise-commercial-advanced Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

e

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

bl a r fe

s

an r t n

S

er e f a

no a Type 'help;' or '\h' for help. Type '\c' to clear s the ฺcurrent input a statement. h ) de i m u o ฺc nt G mysql> SET PASSWORD=PASSWORD('oracle'); n e de Query OK, 0 rows affected (0.00 atesec) u t w S @ s i n h mysql> EXIT ha se t k ฺ r Bye ee e to u f a # /usr/bin/mysql_secure_installation s PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL (s enALL n NOTE: RUNNING a c h li PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY! IN KSERVERS ... Enter current password for root (enter for none): oracle OK, successfully used password, moving on... ... You already have a root password set, so you can safely answer 'n'. Set root password? [Y/n] n ... skipping. ... Remove anonymous users? [Y/n] Y ... Success! ... Disallow root login remotely? [Y/n] Y ... Success! ... Remove test database and access to it? [Y/n] Y Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: System Administration Chapter 3 - Page 5

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

... Success! ... Reload privilege tables now? [Y/n] Y ... Success! ... All done! If you've completed all of the above steps, your MySQL installation should now be secure. Thanks for using MySQL!

Note: Although this solution shows the mysql_secure_installation script run as the Linux root user, you can run it as a normal user. For installation of MySQL at your own location, refer to the Community Edition download files on the MySQL Downloads webpage: http://dev.mysql.com/downloads/.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 3: System Administration Chapter 3 - Page 6

Practice 3-2: MySQL Data Directory

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

Overview In this practice, you review the data directory associated with the MySQL server. This practice requires you to use the mysql client to load the world_innodb database. To view the premade tables in the world_innodb database, you create the database (empty) and then upload the file containing the table data.

Duration This practice should take approximately five minutes to complete.

Tasks 1. Create and populate the world_innodb database.

e

bl a r fe

a. Enter the mysql client. Enter the following in a terminal window: $ mysql –uroot –poracle

s

an r t n

Use the username and password established during the MySQL server installation. b. Create the empty world_innodb database using the following CREATE DATABASE statement. In the mysql client, enter the following:

S

er e f a

no a s ฺ a mysql> CREATE DATABASE world_innodb; h ) de i m u o c. Select the world_innodb database with the USE statement: ฺc nt G n e mysql> USE world_innodb te tude a w d. Build and populate the world_innodb S database tables using the SOURCE @ s i n statement to run the world_innodb.sql script: h a et h k ฺ mysql> SET autocommit=0; r o us e e f t Query OK,a0 rows e affected (0.00 sec) s s ( n han SOURCE lice /labs/world_innodb.sql Kmysql>

− The autocommit option is described in the “Transactions and Locking” lesson. Resetting it here speeds up the script execution. − Several “Query OK…” messages scroll by before the command is completed. e. Set the autocommit option: mysql> SET autocommit=1; Query OK, 0 rows affected (0.00 sec)

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

Practices for Lesson 3: System Administration Chapter 3 - Page 7

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

2. List the current databases. a. In the mysql client, enter the following: mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | world_innodb | +--------------------+ 4 rows in set (0.00 sec)

− At this point, four databases are listed. 3. Locate the local MySQL server data directory. a. In the mysql client, enter the following: mysql> SHOW VARIABLES LIKE 'datadir'\G

e

bl a r fe

s

an r t n

no a s ฺ a h ) de i m u o $ cd /var/lib/mysql ฺc nt G n e $ ls de of its own. ate Staudirectory − Each database on the MySQLwserver has @ isdirectory. n 5. Review the contents of the mysql database h a t ฺkhdirectory seto the mysql directory and review the contents. Enter r a. As root user, change u e finea terminal towindow: the following a e s ( ens $ sun– a c h lioracle Password: K r fee # cd /var/lib/mysql/mysql

4. Review the contents of the data directory. a. Using the result from the preceding SHOW VARIABLES statement, enter the following in another terminal window:

Sa

# ls

− Note the many.frm files contained in the directory, representing the table formats. Also note the .MYD and .MYI files for MyISAM tables, as well as some .ibd files for InnoDB table data, and .CSV and .CSM files for the slow_log and its Metafile respectively. 6. Review the contents of the world_innodb database directory. a. Change directory to the world_innodb directory and review the contents. Enter the following in the terminal window used in the previous step: # cd ../world_innodb # ls

− Note the table .frm files, and InnoDB .idb files contained in the directory.

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

Practices for Lesson 3: System Administration Chapter 3 - Page 8

Solutions 3-2: MySQL Data Directory Tasks

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

1. Create and populate the world_innodb database. a. Enter the mysql client. Type the following in a terminal window, and receive the result shown below: $ mysql -uroot -poracle ... Server version: 5.6.8-enterprise-commercial-advanced-log MySQL Enterprise Server - Advanced Edition (Commercial) ... mysql>

b. Create the empty world_innodb database: mysql> CREATE DATABASE world_innodb; Query OK, 1 row affected (0.02 sec)

c. Select the world_innodb database:

e

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e Database changed te tude a w d. Build and populate the world_innodb S database tables using the SOURCE @ s i n statement to run the world_innodb.sql script: h a et h k ฺ mysql> SET autocommit=0; er to us e f Query OK,a0 rows e affected (0.00 sec) s s ( n han SOURCE lice /labs/world_innodb.sql mysql> K er

bl a r fe

mysql> USE world_innodb Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A

Sa

fe

− The autocommit option is described in the “Transactions and Locking” lesson. Resetting it here speeds up the script execution. − Several “Query OK…” messages scroll by before the command is completed. e. Set the autocommit option: mysql> SET autocommit=1; Query OK, 0 rows affected (0.00 sec)

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

Practices for Lesson 3: System Administration Chapter 3 - Page 9

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

2. List the current databases. a. In the mysql client, enter the following, and receive the result shown below: mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | world_innodb | +--------------------+ 4 rows in set (0.00 sec)

− At this point, the server contains four databases. 3. Locate the local MySQL server data directory. a. In the mysql client, enter the following, and receive the result shown below: mysql> SHOW VARIABLES LIKE 'datadir'\G *************************** 1. row *************************** Variable_name: datadir Value: /var/lib/mysql/ 1 row in set (0.01 sec)

e

s

an r t n

Sa

bl a r fe

no a s ฺ 4. Review the contents of the data directory. a h eresult shown below: a. Enter the following in another terminal window, m and) receiveid the u o ฺc nt G $ cd /var/lib/mysql n e $ ls te tude a w auto.cnf ib_logfile1 mysqlS RPM_UPGRADE_HISTORY @ s i n h ibdata1 hostname.err mysql.sock RPM_UPGRADE_MARKERa et h k ฺ LAST r o us e e ib_logfile0 hostname.pid performance_schema world_innodb f a se t s ( 5. Review the eofnthe mysql database directory: ancontents c i h l Ka. Enter the following in a terminal window, and receive the result shown below: r e $ su – fe Password: oracle # cd /var/lib/mysql/mysql # ls columns_priv.frm innodb_index_stats.frm columns_priv.MYD innodb_index_stats.ibd columns_priv.MYI innodb_table_stats.frm ... help_topic.MYD slave_relay_log_info.ibd help_topic.MYI slave_worker_info.frm

slave_worker_info.ibd slow_log.CSM slow_log.CSV

− Note the many.frm files contained in the directory, representing the table formats. Also note the .MYD and .MYI files for MyISAM tables, as well as some .ibd files for InnoDB table data, and .CSV and .CSM files for the slow_log and its Metafile respectively.

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

Practices for Lesson 3: System Administration Chapter 3 - Page 10

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

6. Review the contents of the world_innodb database directory. a. Change to the world_innodb directory and review the contents. Enter the following in a terminal window, and receive the result shown below: # cd ../world_innodb # ls City.frm Country.frm City.ibd Country.ibd

CountryLanguage.frm CountryLanguage.ibd

db.opt

− Note the table .frm files, and InnoDB .idb files contained in the directory.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 3: System Administration Chapter 3 - Page 11

Practice 3-3: Starting and Stopping the MySQL Server Overview

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

In this practice, you examine how to start and stop the MySQL server in the Linux environment.

Assumptions The MySQL server installation has been completed prior to this exercise.

Duration This practice should take approximately five minutes to complete.

Tasks 1. 2. 3. 4. 5. 6.

Prior to manipulating the server, log in with admin (or root) privileges. Check the status of the MySQL server. (See the solution note if the server is not running.) Stop the MySQL server. Check the status of the MySQL server again. Start the MySQL server again. Check the status of the MySQL server again.

er e f a

s

o

an r t n

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 3: System Administration Chapter 3 - Page 12

e

bl a r fe

Solutions 3-3: Starting and Stopping the MySQL Server Tasks

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

1. Prior to manipulating the server, you must have admin (or root) privileges. a. Enter the following in a terminal window: $ su – Password: oracle

2. Check the status of the MySQL server. a. Enter the following in a terminal window, and receive the result shown below: # service mysql status MySQL running (1117)

[ OK ]

− Note: The server should be running at this point—it was started as part of a preceding practice. If for some reason it is not running, run the start command before running the stop command for the next step. The process number may differ from that shown in the preceding output. 3. Stop the MySQL server. a. Enter the following in a terminal window, and receive the result shown below:

s

an r t n

no a s ฺ # service mysql stop a h ) Shutting down MySQL...... de[ OK ] i m u o G 4. Check the status of the MySQL server again. nฺc t n e e the result shown below: a. Enter the following in a terminal window, ate Sand udreceive t w # service mysql status @ is n h a t MySQL is not running [FAILED] h se k ฺ r u 5. Start the MySQL server ee again. o f t a s following a. Enter (the sein a terminal window, and receive the result shown below: n n e a c start #hservice limysql K r Starting MySQL [ OK ] fee

Sa 6.

− Leave the server running because you will use it in later practices. Check the status of the MySQL server. a. Enter the following in a terminal window, and receive the result shown below: # service mysql status MySQL running (1401)

[ OK ]

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

Practices for Lesson 3: System Administration Chapter 3 - Page 13

e

bl a r fe

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

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 3: System Administration Chapter 3 - Page 14

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

e

s

bl a r fe

an r t n

er e f a

no a s ฺ 4: a Practices for Lesson h ) de i m Server Configuration u o ฺc nt G n e e u4 de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 1

Practices for Lesson 4: Overview

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

Practices Overview In these practices, you test your knowledge of MySQL server configuration. The hands-on practices are written for the Oracle Linux operating system environment, which is provided in Oracle classrooms. For non-Oracle classrooms, some adjustments may need to be made regarding file locations.

Assumptions •

The MySQL server is already installed.



You are logged in as root user in a terminal window.



You can access the mysql client from a command line prompt.



You are familiar with gedit or another text editor within Linux.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 2

Practice 4-1: Quiz – MySQL Server Configuration Overview

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

In this practice, you answer questions about MySQL server configuration.

Duration This practice should take approximately 10 minutes to complete.

Quiz Questions Choose the best answer from those provided for each multiple choice or True/False question. 1. Which of the following statements regarding SQL modes are true? (Choose all that apply.) a. The setting for sql_mode can only be changed globally. b. If you want to set two SQL modes (for example, the STRICT_ALL_TABLES and ERROR_FOR_DIVISION_BY_ZERO modes), you must issue two SET sql_mode statements. c. Unless explicitly declared as global, setting SQL modes affects only the client session that sets the modes. d. SQL modes affect the behavior of the server. For example, they influence the way the server handles invalid input data. e. SQL modes affect the features that the server provides for a client. For example, you could turn InnoDB support on and off using SQL modes. 2. Is this the proper syntax for changing the SQL mode to STRICT_TRANS_TABLES and PIPES_AS_CONCAT?

s

an r t n

S

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his mysql> SET sql_mode a =n 'STRICT_TRANS_TABLES,PIPES_AS_CONCAT'; h se t k ฺ r a. Yes e to u e f a b. No (s se n n e 3. All MySQL haorprograms lic read startup options from plain text option files named my.ini, K my.cnf, ~/.my.cnf. er a. True e f a

b. False 4. If you invoke mysql with the -h 127.0.0.1 option, which of the following statements are true? a. mysql establishes a connection to a remote server. b. mysql uses a TCP/IP connection to the local instance. c. mysql works only for a specific operating system.

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 3

e

bl a r fe

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

5. On Linux, the server writes errors to the standard error output (normally the terminal). You can write error output to a given file instead by starting the server with the --log-error= option. a. True b. False 6. By default, the error log is written in text format to the data directory with the suffix ____________, and can be viewed using any program that displays text files. a. .log b. .error_log c. .err d. .bin_err 7. You can start the MySQL server without specifying options. To override default option values, specify the new options on the command line. a. True b. False 8. The following statements are true for binary logs: a. They are turned on randomly depending on the log file name. b. All actions are logged in one large file. c. They are created with a numeric, sequential, ascending extension. d. They are stored in binary format, not text format.

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 4

e

bl a r fe

Solutions 4-1: Quiz – MySQL Server Configuration

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

Quiz Solutions 1. Which of the following statements regarding SQL modes are true? c. Unless explicitly declared as global, setting SQL modes affects only the client session that sets the modes. d. SQL modes affect the behavior of the server; for example, they influence the way in which the server handles invalid input data. 2. Is this the proper syntax for changing the SQL mode to STRICT_TRANS_TABLES and PIPES_AS_CONCAT? mysql> SET sql_mode = 'STRICT_TRANS_TABLES,PIPES_AS_CONCAT';

3.

a. Yes All MySQL programs read startup options from plain text option files named my.ini, my.cnf, or ~/.my.cnf. a. True Suppose that you invoke mysql with the -h 127.0.0.1 option, which of the following statements are true? b. mysql uses a TCP/IP connection to the local instance. On Linux, the server writes errors to the standard error output (normally the terminal). You can write error output to a given file instead by starting the server with the --log-error= option. a. True By default, the error log is written in text format to the data directory with the suffix ____________, and can be viewed using any program that displays text files. c. .err You can start the MySQL server without specifying options. To override default option values, specify the new options on the command line. b. False. You can also place options in a startup option file. The following statements are true about binary logs: c. They are created with a numeric, sequential, ascending extension. d. They are stored in binary format, not text format.

s

4.

5.

6.

7.

S

er e f a 8.

o

an r t n

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 5

e

bl a r fe

Practice 4-2: Editing and Creating a Configuration File Overview

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

In this practice, you edit the my.cnf configuration file and create a new configuration file.

Duration This practice should take approximately 30 minutes to complete.

Tasks 1. To have a common baseline configuration, take a copy of the my.cnf configuration file template in the /etc directory and place it in /root. 2. Locate the [mysqld] section and change the default port designation to 3309. Add a [client] section with a port designation of 3309.

s

an r t n

o

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

er c. Exit the mysql session. e f a 10. Add the options from the my_opts.txt to the default config file (/etc/my.cnf), with the

S

exception of the password setting, so that these options are used by default each time the client is invoked. 11. Logged in as the oracle user, invoke the mysql client without specifying the new config file. Confirm the settings. 12. Logged in as the oracle user, invoke mysql_config_editor, providing login settings for the root user in the default login path. 13. Use mysql_config_editor to display all stored login paths for the current user. 14. Use the cat command to display the contents of the ~/.mylogin.cnf file. 15. Logged in as the oracle user, invoke the mysql client without providing any command-line options. When you have successfully logged in, exit the mysql client. 16. Remove the default login path by using mysql_config_editor. 17. Invoke the mysql_config_editor again, providing login settings for the root user, storing them in the login path admin. 18. Invoke the mysql client, specifying the login path admin. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Server Configuration Chapter 4 - Page 6

e

bl a r fe

3. In the [mysqld] section, indicate that the following logs are to be turned on: General, Binary, and Slow Query. Give the binary file a base name of mybinlog. 4. Save and close the configuration (config) file. 5. Stop and restart the server as root. 6. Confirm that the log files specified in your config file are now being created. View the /var/lib/mysql directory to see the log files. 7. In a terminal, logged in as the oracle user, create an additional config file with the following options: password = oracle, user name = root, turn on compress mode, show warnings, and add a specific mysql prompt (to include the current system time and database). Call this file my_opts.txt and save it in the home directory (~/). 8. Invoke the mysql client with your new config file. 9. Confirm the settings from the new config file: a. Check the status of options being used for this mysql client session. b. Change the database setting to use the world_innodb database.

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

19. Create a “clean” (original) version of the default config file by copying the existing /root/my.cnf file (created in step 1) into the /etc directory. After saving your new file, restart the server.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 7

Solutions 4-2: Editing and Creating a Configuration File

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

Tasks 1. To have a common baseline configuration, take a copy of the my.cnf configuration file template in the /etc directory and place it in /root. a. Enter the following in a terminal window: $ su – Password: oracle

b. Copy the my.cnf file to /root. # cp /etc/my.cnf /root

c. Open the my.cnf configuration file in gedit (or your preferred text editor). # gedit /etc/my.cnf

s

2. Locate the [mysqld] section and add a port designation of 3309. Add a [client] section with a port designation of 3309. Modify the following lines in the my.cnf file:

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a h se t k ฺ r ee e to u f a − In this (scase,ethensport number used when listening for TCP/IP connections is set to n a3309. Thelicport number must be 1024 or higher, unless the server is started by the Kh root system user. [mysqld] datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock port=3309 user=mysql ... [client] port=3309

eInr the [mysqld] section, indicate that the following logs are to be turned on: General, e f 3. a

S

Binary, and Slow Query. Add the following lines to the [mysqld] section: [mysqld] ... symbolic-links=0 general_log log-bin=mybinlog slow_query_log ...

− MySQL enables the general log, binary log, and slow log the next time that the server is restarted. 4. Save and close the configuration (config) file. − In gedit, press Ctrl + S, and then Ctrl + Q.

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 8

e

bl a r fe

Use vim or emacs (or another editor) if you are more comfortable with those editors.

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

5. Stop and restart the server as root. a. Enter the following in a terminal window, and receive the results shown below: − Be sure to exit any mysql client that you currently have running prior to stopping the server. # service mysql restart Shutting down MySQL.... Starting MySQL....

[ OK ] [ OK ]

6. Confirm that the log files specified in your config file are now being created. View the /var/lib/mysql directory to see the log files. Enter the following in a terminal window, and receive the results shown below: # ls /var/lib/mysql auto.cnf host-name.log host-name.pid host-name-slow.log ibdata1

ib_logfile0 ib_logfile1 mybinlog.000001 mybinlog.index mysql

mysql.sock performance_schema RPM_UPGRADE_HISTORY RPM_UPGRADE_MARKER-LAST world_innodb

s

an r t n

o

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ $ cd n hi a t h $ pwd e rฺk o us e /home/oracle e af se t $ gedit(smy_opts.txt en to the my_opts.txt file: an the following c i b. hAdd l er K

e

bl a r fe

7. In a terminal window, logged in as the oracle user, create an additional config file with the following options: password = oracle, user name = root, turn on compress mode, show warnings, and add a specific mysql prompt. Call this file my_opts.txt and save it in the home directory (~/). a. In the ~ directory (/home/oracle when you are logged in as oracle), create the my_opts.txt configuration file using gedit (or your preferred text editor).

fe Sa

[client] password = oracle user = root

[mysql] compress show-warnings prompt = \R:\m \d>\_

c. Save and close the new config file.

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 9

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

8. Invoke the mysql client with the my_opts.txt file. Enter the following in a terminal window, and receive the result shown below: $ mysql --defaults-extra-file=~/my_opts.txt Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 1 Server version: 5.6.10-enterprise-commercial-advanced-log MySQL Enterprise Server - Advanced Edition (Commercial) 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.

s

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

an r t n

no a sand shows a − The prompt now reflects the current time of the system, h eฺ that no database ) d is currently being used. i m u o G 9. Confirm the settings from the new config file: nฺc t n e teefortthis d a. Check the status of options beingaused mysql client session. Enter the uthe result shown w S following at the mysql prompt, and receive below: @ s i n h 10:21 (none)> STATUS ha se t k ฺ r -------------e to u e f a mysql Ver seDistrib 5.6.10, for Linux (x86_64) using EditLine (s 14.14 n wrapper n e ha lic K r 1 fee Connection id: 10:21 (none)>

Sa

Current database: Current user: SSL: Current pager: Using outfile: Using delimiter: Server version: MySQL Enterprise Server Protocol version: Connection: Server characterset: Db characterset: Client characterset: Conn. characterset: UNIX socket: Protocol:

root@localhost Not in use stdout '' ; 5.6.10-enterprise-commercial-advanced-log - Advanced Edition (Commercial) 10 Localhost via UNIX socket latin1 latin1 utf8 utf8 /var/lib/mysql/mysql.sock Compressed

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 10

e

bl a r fe

Uptime:

8 min 40 sec

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

Threads: 1 Questions: 8 Slow queries: 0 Opens: 70 Open tables: 63 Queries per second avg: 0.015 --------------

Flush tables: 1

− A list of server connection specifications are shown, including the particular settings from the option file. Check the list for the appropriate options settings. b. Change the database setting to use the world_innodb database. Enter the following at the newly changed prompt, and receive the result shown below: 10:22 (none)> USE world_innodb Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A

e

bl a r fe

Database changed

c. Exit the mysql session, and receive the result shown below:

s

an r t n

10:23 world_innodb> EXIT Bye $

S

no a s(/etc/my.cnf), a 10. Add the options from the my_opts.txt to the default confighfile with the ฺ )are usedidbyedefault exception of the password setting, so that these options each time the m u co to thet G ฺ client is invoked. Logged in as root, add the following existing /etc/my.cnf file: n e den e t ... wa s Stu [client] @ port=3309 n hi a t h user = root e rฺk o us e e t [mysql] af e s s ( compress an licen show-warnings h Kprompt = \R:\m \d>\_ r e − Placing the password in the default option file is not secure and a bad practice. afe − You do not have to restart the mysql server when you change client options.

11. Logged in as the oracle user, invoke the mysql client without specifying the new config file. Confirm the settings. Enter the following in a terminal window, logged in as the oracle user, and receive the result shown below: $ mysql -p Enter password: oracle Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 2 Server version: 5.6.8-enterprise-commercial-advanced-log MySQL Enterprise Server - Advanced Edition (Commercial) 12:01 (none)>

− You do not need to provide a value for user, because it is hard-coded into the configuration file.

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 11

12. Logged in as the oracle user, invoke the mysql_config_editor, providing login settings for the root user in the default login path.

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

Enter the following in a new terminal window, logged in as the oracle user, and receive the result shown below: $ mysql_config_editor set --user=root --password Enter password: oracle

13. Use mysql_config_editor to display all stored login paths for the current user. Enter the following in a terminal window, logged in as the oracle user, and receive the result shown below: $ mysql_config_editor print --all [client] user = root password = *****

s

an r t n

no a s ฺ a $ cat ~/.mylogin.cnf h ) de i m u o ฺc nt G n e 2 U 1 OB@1@ `{ ]Nq de E Aq ate$ S tu )^ |{ j s x W $w @ hand is you cannot see the username or password n − The file contents are unreadable, a t h se stored within. rฺk u the mysql client without providing any command-line e e euser, oinvoke f t 15. Logged in as theaoracle (syou have options. When nssuccessfully logged in, exit the mysql client. n e a c h the following li a. KEnter in a terminal window, logged in as the oracle user, and receive r e the result shown below: afe

S

$ mysql Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 3 Server version: 5.6.10-enterprise-commercial-advanced-log MySQL Enterprise Server - Advanced Edition (Commercial) ...

b.

− You are logged in with the username and password provided in step 12. If you provide no command-line options, the mysql client uses the default login path. In step 12, you did not specify a login path name, so the settings were stored under the default path. To exit, enter the following at the mysql prompt: 10:36 (none)> EXIT Bye

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 12

e

bl a r fe

− The command displays the plain-text contents of the newly created ~/.mylogin.cnf file, obscuring the password. 14. Use the cat command to display the contents of the ~/.mylogin.cnf file. Enter the following in a terminal window, logged in as the oracle user, and receive the result shown below:

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

16. Remove the default login path by using mysql_config_editor. Enter the following in a terminal window, logged in as the oracle user, and receive the result shown below: $ mysql_config_editor remove WARNING : No login path specified, so default login path will be removed. Continue? (Press y|Y for Yes, any other key for No) : y

17. Invoke the mysql_config_editor again, providing login path settings for the root user, storing them in the login path admin. Enter the following in a terminal window, logged in as the oracle user, and receive the result shown below: $ mysql_config_editor set --login-path=admin --user=root --password Enter password: oracle

18. Invoke the mysql client, specifying the login path admin. $ mysql --login-path=admin Welcome to the MySQL monitor. Your MySQL connection id is 4 ...

e

bl a r fe

Commands end with ; or \g.

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n 10:39 (none)> EXIT e ate Stude Bye w @ is config file by copying the existing n 19. Create a “clean” (original) version of the tdefault h a e into the /etc directory. After saving your new file, /root/my.cnf file (created 1) ฺkhin step s r u e restart the server. fe to a e s a. Enter (the following ns in a terminal window, logged in as root: n e a c li #h cp /root/my.cnf /etc/ K r cp: overwrite `/etc/my.cnf'? y e e f a − Part of the reason for doing this is to go back to the default port setting. If you leave − You are logged in with the username and password provided in step 17. When you use the --login-path option, the mysql client uses the credentials stored in that login path. To exit, enter the following at the mysql prompt:

S

it set to 3309 (or other non-default), you must specify the port for all client connections, which can be time-consuming and a source of error. Revert to the default now to avoid later misunderstandings. b. Restart the server. Enter the following in a terminal window, and receive the results shown below: # service mysql restart Shutting down MySQL...... [ OK ] Starting MySQL...... [ OK ]

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 13

Practice 4-3: Additional Practice – Server Configuration Overview

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

In this practice, you use the world_innodb database and the information from this lesson regarding MySQL server configuration.

Duration This practice should take approximately 40 minutes to complete.

Tasks 1. Check to see whether the general and slow query logs are turned on, by using the SHOW GLOBAL VARIABLES LIKE '%log' statement. If they are not on, use SET GLOBAL statements to turn on the log files. 2. Make sure that the logs are table-based by checking the log_output variable value. If needed, set the variable value to TABLE, and then empty the tables by using a TRUNCATE statement. 3. Make a new copy of the world_innodb database, called world2. To accomplish this, create a new database called world2 and source the world_innodb.sql database file again when connected to world2.

s

an r t n

Sa

no a s ฺ a h e using the following ) log,idby 4. Count the number of CREATE TABLE statements in them general u o SELECT statement: ฺc nt G n e mysql> SELECT COUNT(*) FROM temysql.general_log de a u t w S TABLE%'; -> WHERE argument@ LIKE 'CREATE s i n h a the eslowt query log: 5. Create a query that makes ithinto k ฺ r us some time e that a. Example: Afe SELECT takes o t a SLEEP(11); e mysql>(s SELECTns n e a licthe slow_log table in the mysql database. b. hView it from K r f6.eeDetermine whether the binary logging is enabled by checking the log_bin variable value. Then exit the current mysql session.

7. Edit the my.cnf file (located in the /etc directory) in the [mysqld] section to turn on binary logging. After saving your edit, stop and restart the server. 8. In a new mysql session, make sure that the binary log is enabled and erase all previous logs (if present), by using the RESET MASTER statement. 9. Perform a data changing operation: a. For instance, create and drop a database: mysql> CREATE DATABASE foo; mysql> DROP DATABASE foo; b. List it from the binary log by using the SHOW BINLOG EVENTS statement. 10. Rotate the binary logs explicitly using FLUSH BINARY LOGS and perform some more data changing queries (similar to the previous step). 11. List all your binary logs (for mysql-bin.000002), and list the latest changes, by using the appropriate SHOW statements. 12. Purge the first binary log. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Server Configuration Chapter 4 - Page 14

e

bl a r fe

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

13. Perform some more data modifying queries (similar to the previous steps) but with the database name foo2. 14. Use mysqlbinlog to display all entries in the binary log that have taken place after the ones seen in step 11. 15. Look in the mysql-bin.000002 binary log file for the start of the events that took place after the logs were flushed. What was the event number for the drop of the foo2 database? 16. From the mysql prompt, load the Audit Log plugin. 17. Execute some modification statements (similar to the previous steps). 18. View the value of the audit_log_file system variable, and use that value to locate and view the contents of the audit log. 19. Unload the Audit Log plugin, noting any warnings. 20. Execute some modification statements (similar to the previous steps). 21. Exit the current mysql session. 22. View the last few lines of the audit log. 23. Configure the /etc/my.cnf file to enable the Audit Log plugin at server start-up, and to prevent it from being unloaded at runtime. Restart the server when you have done this. 24. Attempt to unload the Audit Log plugin, and note the result. 25. View the audit log file again, noting any changes. 26. Remove all settings related to Audit Log from the /etc/my.cnf file, and restart the MySQL server.

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 15

e

bl a r fe

Solutions 4-3: Additional Practice – Server Configuration

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

Tasks 1. Check to see whether the general and slow query logs are turned on, by using the SHOW GLOBAL VARIABLES LIKE '%log' statement. If they are not on, use SET GLOBAL statements to turn on the log files. a. Invoke the mysql client from a terminal logged in as oracle, specifying the login path admin. $ mysql --login-path=admin Your MySQL connection id is 1 ...

b. View the status variables that end with the word “log.” Enter the following at the mysql prompt, and receive the result shown below: +--------------------------------+-------+ | Variable_name | Value | +--------------------------------+-------+ | back_log | 80 | | general_log | OFF | | innodb_api_enable_binlog | OFF | | innodb_locks_unsafe_for_binlog | OFF | | relay_log | | | slow_query_log | OFF | | sync_binlog | 0 | | sync_relay_log | 10000 | +--------------------------------+-------+ 8 rows in set (0.00 sec)

S

er e f a

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a h se t k ฺ r ee e to u f a (s ens n a liclog files. Enter the following and receive the results shown below: Kc. hTurn on the mysql> SET GLOBAL general_log = ON; Query OK, 0 rows affected (0.06 sec) mysql> SET GLOBAL slow_query_log = ON; Query OK, 0 rows affected (0.07 sec)

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 16

e

bl a r fe

mysql> SHOW GLOBAL VARIABLES LIKE '%log';

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

d. View the new status variables that end with the word "log". Enter the following at the mysql prompt, and receive the result shown below: mysql> SHOW GLOBAL VARIABLES LIKE '%log'; +--------------------------------+-------+ | Variable_name | Value | +--------------------------------+-------+ | back_log | 80 | | general_log | ON | | innodb_api_enable_binlog | OFF | | innodb_locks_unsafe_for_binlog | OFF | | relay_log | | | slow_query_log | ON | | sync_binlog | 0 | | sync_relay_log | 10000 | +--------------------------------+-------+ 8 rows in set (0.00 sec)

Sa

ns a r t 2. Make sure that the logs are table-based by checking the log_output variable value. If on-a TRUNCATE needed, set the variable value to TABLE, and then empty the tables bynusing a statement. s a eฺreceive the result ) h idand a. Check the log_output variable value. Enter the following, m shown below: co t Gu ฺ n n e'log_output'; mysql> SHOW GLOBAL VARIABLES LIKE e e t d +---------------+-------+ wa tu S | Variable_name | Value@ | s n hi +---------------+-------+ a t h e | log_output |s rฺ|kFILE u e +---------------+-------+ e o t asetf (0.00 e 1 row in sec) s s ( n n ictoeTABLE, b. hIfait not set then type the following, and receive the result shown below: l K r fee mysql> SET GLOBAL log_output = 'TABLE'; Query OK, 0 rows affected (0.01 sec)

c. Verify that the log_output variable is now set to TABLE. Enter the following, and receive the result shown below: mysql> SHOW GLOBAL VARIABLES LIKE 'log_output'; +---------------+--------+ | Variable_name | Value | +---------------+--------+ | log_output | TABLE | +---------------+--------+ 1 row in set (0.00 sec)

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 17

e

bl a r fe

d. Empty the log tables. Enter the following, and receive the results shown below:

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

mysql> TRUNCATE mysql.general_log; Query OK, 0 rows affected (0.01 sec) mysql> TRUNCATE mysql.slow_log; Query OK, 0 rows affected (0.01 sec)

3. Make a new copy of the world_innodb database, called world2. To accomplish this, create a new database called world2 and source the world_innodb.sql database file again when connected to world2. a. Create and populate the world2 database. Enter the following, and receive the results shown below: mysql> CREATE DATABASE world2; Query OK, 1 row affected (0.02 sec) mysql> USE world2; Database changed mysql> SET autocommit=0; Query OK, 0 rows affected (0.00 sec)

Sa

e

bl a r fe

s

an r t n

no a s ฺ a h ) de i mysql> SOURCE /labs/world_innodb.sql m u o ฺc nt G Query OK ... n e te tude ... a w S Query OK, 0 rows affected (0.00 sec) @ s i n h ha se t k ฺ r mysql> SET autocommit=1; ee affected o u (0.04 sec) t Query OK,a0f rows e s (s theenautocommit n − a Resetting option speeds up the import. c i h l K 4. Count r the number of CREATE TABLE statements in the general log, by using the following e e SELECT statement. Enter the following, and receive the result shown below: f mysql> SELECT COUNT(*) FROM mysql.general_log -> WHERE argument LIKE 'CREATE TABLE%'; +----------+ | COUNT(*) | +----------+ | 3 | +----------+

5. Create a query that makes it into the slow query log: a. Example: A SELECT that takes some time. Enter the following, and receive the result shown below: mysql> SELECT SLEEP(11); +------------+ | SLEEP (11) | +------------+ | 0 | +------------+

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 18

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

b. View it from the slow_log table in the mysql database. Enter the following query, and receive the result shown below: mysql> SELECT * FROM mysql.slow_log\G *************************** 1. row *************************** start_time: 2013-02-01 11:06:36 user_host: root[root] @ localhost [] query_time: 00:00:11 lock_time: 00:00:00 rows_sent: 1 rows_examined: 0 db: world2 last_insert_id: 0 insert_id: 0 server_id: 0 sql_text: SELECT SLEEP(11) thread_id: 1 1 row in set (0.00 sec)

e

bl a r fe

s

an r t n

o

an s a eฺ h ) mysql> SHOW GLOBAL VARIABLES LIKE 'log_bin'; om Guid c +---------------+-------+ ฺ | Variable_name | Value | en dent e t +---------------+-------+ a Stu | log_bin | OFF @ | w is n +---------------+-------+ h a t e ฺkhmysql ssession. r b. Then exit the current u e afe se to mysql> (EXIT s Bye an licen h K

6. Determine whether the binary logging is enabled by checking the log_bin variable value: a. Check the status of the log. Enter the following, and receive the result shown below:

S

r the my.cnf file (located in the /etc directory) in the [mysqld] section to turn on 7. eEdit e f binary logging. After saving your edit, stop and restart the server. a

a. In the terminal logged in as root, open the my.cnf configuration file in gedit (or your preferred text editor). # gedit /etc/my.cnf

b. Add the following line controlling log updates to the [mysqld] section: [mysqld] log-bin=mysql-bin datadir=/var/lib/mysql ...

c. Save and close the configuration file.

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 19

d. After saving your edit, stop and restart the server. Enter the following in a terminal window, and receive the results shown below:

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

# service mysql restart Shutting down MySQL... Starting MySQL.

[ [

OK OK

] ]

8. In a new mysql session, make sure that the binary log is enabled and erase all previous logs (if present), by using the RESET MASTER statement. a. In a Linux terminal logged in as oracle, launch the mysql client: $ mysql --login-path=admin Welcome to the MySQL monitor. Your MySQL connection id is 1 ...

Commands end with ; or \g.

b. Check the status of the log. Enter the following, and receive the result shown below: mysql> SHOW GLOBAL VARIABLES LIKE 'log_bin'; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | log_bin | ON | +---------------+-------+

Sa

s

an r t n

no a s ฺ a h c. Erase all logs. Enter the following, and receive the)result shown de below: i m u o mysql> RESET MASTER; ฺc nt G n e Query OK, 0 row affected (0.09te sec) de a u t w S the binary log. 9. Perform a data changing operation and list it from @ s i n h a ea database. t a. For instance, createh Enter the following, and receive the ฺk and drop s r results showne below: u e DATABASE o f t mysql> CREATE a e foo; s s ( n Query han OK,li1cerow affected (0.00 sec) K r fee mysql> DROP DATABASE foo; Query OK, 0 row affected (0.00 sec)

b. List it from the binary log by using the SHOW BINLOG EVENTS statement. Enter the following, and receive the result shown below: mysql> SHOW BINLOG EVENTS; +------------------+-----+-------------+-----------+----------+---------------------| Log_name

| Pos | Event_type

| Server_id | End_log… | Info

+------------------+-----+-------------+-----------+----------+---------------------| mysql-bin.000001 |

4 | Format_desc |

1 |

120 | Server ver: 5.6.10..

| mysql-bin.000001 | 120 | Query

|

1 |

211 | CREATE DATABASE foo

| mysql-bin.000001 | 211 | Query

|

1 |

294 | DROP DATABASE foo

+------------------+-----+-------------+-----------+----------+--------------------3 rows in set (0.00 sec)

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 20

e

bl a r fe

10. Rotate the binary logs explicitly by using FLUSH BINARY LOGS and perform some more data changing queries (similar to the previous step). a. Flush the binary log. Enter the following:

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

mysql> FLUSH BINARY LOGS; Query OK, 0 row affected (0.04 sec)

b. Change data. Enter the following, and receive the results shown below: mysql> CREATE DATABASE foo; Query OK, 1 row affected (0.00 sec) mysql> DROP DATABASE foo; Query OK, 0 row affected (0.02 sec)

11. List all your binary logs (for mysql-bin.000002), and list the latest changes, by using the appropriate SHOW statements. a. List logs. Enter the following, and receive the result shown below:

s

an r t n

mysql> SHOW MASTER LOGS; +------------------+-----------+ | Log_name | File_size | +------------------+-----------+ | mysql-bin.000001 | 341 | | mysql-bin.000002 | 294 | +------------------+-----------+ 2 rows in set (0.00 sec)

no a s ฺ a h ) de i m u o ฺc nt G n e te receive dthee result shown below: aand u b. List changes. Enter the following, t w S @ s i mysql> SHOW BINLOG EVENTS IN 'mysql-bin.000002'; n h ha se t k ฺ r ee e to u f a (s ens n ha lic K er

+------------------+-----+-------------+-----------+----------+---------------------| Log_name

| Pos | Event_type

| Server_id | End_log… | Info

+------------------+-----+-------------+-----------+----------+---------------------| mysql-bin.000002 |

fe Sa

4 | Format_desc |

1 |

120 | Server ver: 5.6.10..

| mysql-bin.000002 | 120 | Query

|

1 |

211 | CREATE DATABASE foo

| mysql-bin.000002 | 211 | Query

|

1 |

294 | DROP DATABASE foo

+------------------+-----+-------------+-----------+----------+--------------------3 rows in set (0.00 sec)

12. Purge the first binary log. Enter the following, and receive the result shown below: mysql> PURGE MASTER LOGS TO 'mysql-bin.000002'; Query OK, 0 row affected (0.05 sec)

13. Perform some more data modifying queries (similar to the previous steps) but with the database name foo2. Enter the following, and receive the results shown below: mysql> CREATE DATABASE foo2; Query OK, 1 row affected (0.00 sec) mysql> DROP DATABASE foo2; Query OK, 0 row affected (0.00 sec)

14. Use mysqlbinlog to display all entries in the binary log that have taken place after the ones seen in step 11. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Server Configuration Chapter 4 - Page 21

e

bl a r fe

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

Enter the following in a terminal window logged in as root, and receive the result shown below: # mysqlbinlog /var/lib/mysql/mysql-bin.000002 /*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/; /*!40019 SET @@session.max_insert_delayed_threads=0*/; /*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/; DELIMITER /*!*/; # at 4 #130202 12:02:05 server id 1 end_log_pos 120 CRC32 0x061acade Start: binlog v 4, server v 5.6.10-enterprise-commercial-advanced-log created 130202 12:02:05 # Warning: this binlog is either in use or was not closed properly. BINLOG ' PQANUQ8BAAAAdAAAAHgAAAABAAQANS42LjEwLWVudGVycHJpc2UtY29tbWVyY2lhbC1hZH ZhbmNl ZC1sb2cAAAAAAAAAAAAAAAAAEzgNAAgAEgAEBAQEEgAAXAAEGggAAAAICAgCAAAACgoKGR kAAd7K GgY= '/*!*/; # at 120 #130202 12:02:15 server id 1 end_log_pos 211 CRC32 0x9d08e28b Query thread_id=1 exec_time=0 error_code=0 SET TIMESTAMP=1359806535/*!*/; SET @@session.pseudo_thread_id=1/*!*/; SET @@session.foreign_key_checks=1, @@session.sql_auto_is_null=0, @@session.unique_checks=1, @@session.autocommit=1/*!*/; SET @@session.sql_mode=1075838976/*!*/; SET @@session.auto_increment_increment=1, @@session.auto_increment_offset=1/*!*/; /*!\C utf8 *//*!*/; SET @@session.character_set_client=33,@@session.collation_connection=33,@@ session.collation_server=8/*!*/; SET @@session.lc_time_names=0/*!*/; SET @@session.collation_database=DEFAULT/*!*/; CREATE DATABASE foo /*!*/; # at 211 #130202 12:02:21 server id 1 end_log_pos 294 CRC32 0x24ec5ec1 Query thread_id=1 exec_time=0 error_code=0 SET TIMESTAMP=1359806541/*!*/; DROP DATABASE foo /*!*/; # at 294 #130202 12:06:19 server id 1 end_log_pos 388 CRC32 0xa8736010 Query thread_id=1 exec_time=0 error_code=0 SET TIMESTAMP=1359806779/*!*/;

s

o

an r t n

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 22

e

bl a r fe

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

CREATE DATABASE foo2 /*!*/; # at 388 #130202 12:06:19 server id 1 end_log_pos 473 CRC32 0xee26c05a thread_id=1 exec_time=0 error_code=0 SET TIMESTAMP=1359806779/*!*/; DROP DATABASE foo2 /*!*/; DELIMITER ; # End of log file ROLLBACK /* added by mysqlbinlog */; /*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/; /*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;

Query

s

an r t n

no a s ฺ a h ) de i m u o mysql> INSTALL PLUGIN audit_log SONAME G ฺc 'audit_log.so'; t n n e Query OK, 0 rows affected (0.19 sec) te tude a w 17. Execute some modification statements (similar S @ his to the previous steps). Enter the following, n and receive the results shownabelow: t h foo; e k ฺ s mysql> CREATE DATABASE r e to u (0.00 sec) Query OK,a1fe row affected (s ense n ha DROP licDATABASE foo; mysql> K er Query OK, 0 row affected (0.00 sec) e f a

S

18. View the value of the audit_log_file system variable, and use that value to locate and view the contents of the audit log. a. Enter the following, and receive the results shown below: mysql> SHOW VARIABLES LIKE 'audit_log_file'; +----------------+-----------+ | Variable_name | Value | +----------------+-----------+ | audit_log_file | audit.log | +----------------+-----------+ 1 row in set (0.20 sec)

− The audit.log file is in the server’s data directory.

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 23

e

bl a r fe

15. Look in the mysql-bin.000002 binary log file for the start of the events that took place after the logs were flushed. What was the event number for the drop of the foo2 database? 388 − The event position number combined with the binary log file name identifies the specific event. 16. From the mysql prompt, load the Audit Log plugin. Enter the following, and receive the results shown below:

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

b.

In a Linux terminal window, logged in as root, enter the following and receive the results shown: # cat /var/lib/mysql/audit.log





s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e te tEnter dethe following, and receive the 19. Unload the Audit Log plugin, noting any a warnings. u w S results shown below: @ s i n h t mysql> UNINSTALL PLUGIN ha audit_log; e k ฺ s r Query OK, 0 rows ee eaffected, o u 1 warning (0.00 sec) f t a s WARNINGS; (SHOW ns mysql> n e a c h li +---------+------+----------------------------------------------------+ K r e | Level | Code | Message | afe +---------+------+----------------------------------------------------+

S

| Warning | 1620 | Plugin is busy and will be uninstalled on shutdown | +---------+------+----------------------------------------------------+ 1 row in set (0.00 sec)

20. Execute some modification statements (similar to the previous steps). Enter the following, and receive the results shown below: mysql> CREATE DATABASE foo; Query OK, 1 row affected (0.00 sec) mysql> DROP DATABASE foo; Query OK, 0 row affected (0.00 sec)

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 24

e

bl a r fe

21. Exit the current mysql session. Enter the following, and receive the results shown below: mysql> EXIT Bye

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

22. View the last few lines of the audit log. Enter the following in a Linux terminal window logged in as root, and receive the results shown below: # cat /var/lib/mysql/audit.log

...





s

an r t n

no a s ฺ a h ) de i m u o Groot element, and there is no ฺcthe AUDIT − The XML file contains a closing tag, closing t n n e record of the final modification statements. te tude a w 23. Configure the /etc/my.cnf file to enable the S Audit Log plugin at server start-up, and to @ s i n prevent it from being unloadedaat runtime. Restart the server when you have done this. h t h e k ฺ a. Edit the file /etc/my.cnf er to asusfollows: e f [mysqld]sa ( ense plugin-load=audit_log.so n ha lic audit-log=FORCE_PLUS_PERMANENT K er log-bin=mysql-bin e f a

S

datadir=/var/lib/mysql ...

b.

Enter the following in a terminal window, and receive the results shown below: # service mysql restart Shutting down MySQL... Starting MySQL.

[ [

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 25

OK OK

e

bl a r fe

] ]

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

24. Reconnect to mysql as root. Attempt to unload the Audit Log plugin, and note the result. Enter the following, and receive the results shown below: $ mysql --login-path=admin Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 1 Server version: 5.6.10-enterprise-commercial-advanced-log MySQL Enterprise Server - Advanced Edition (Commercial) ... mysql> UNINSTALL PLUGIN audit_log; ERROR 1702 (HY000): Plugin 'audit_log' is force_plus_permanent and can not be unloaded

25. View the audit log file again, noting any changes. Enter the following at a terminal prompt as root, and receive the results shown below:

s

an r t n

o

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

− The XML file has been re-opened by the Audit Log plugin, and it has recorded the second attempt to uninstall the plugin, along with its error number, but it has not unloaded the plugin.

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 26

e

bl a r fe

# cat /var/lib/mysql/audit.log

...





26. Remove all settings related to Audit Log from the /etc/my.cnf file, and restart the MySQL server. a. Remove the following lines from the /etc/my.cnf file:

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

plugin-load=audit_log.so audit-log=FORCE_PLUS_PERMANENT

The top of the file should look similar to the following: [mysqld] log-bin=mysql-bin datadir=/var/lib/mysql ...

b.

Restart the MySQL server. Enter the following in a terminal window, and receive the results shown below: # service mysql restart Shutting down MySQL... Starting MySQL.

[ [

er e f a

S

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 27

e

bl a r fe

s

an r t n

o

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

OK OK

] ]

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

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 4: Server Configuration Chapter 4 - Page 28

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

e

s

bl a r fe

an r t n

er e f a

no a s ฺ 5: a Practices for Lesson h ) Tools de i m Clients and u o ฺc nt G n e e u5 de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 5: Clients and Tools Chapter 5 - Page 1

Practices for Lesson 5: Overview

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

Practices Overview In these practices, you test your knowledge of MySQL clients and tools. The hands-on practices are written for the Oracle Linux operating system environment, which is provided in Oracle classrooms. For non-Oracle classrooms, some adjustments may need to be made regarding file locations.

Assumptions •

The MySQL server installation has been completed prior to this exercise.



You are logged in as oracle user in a terminal window.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 5: Clients and Tools Chapter 5 - Page 2

Practice 5-1: Invoking the mysql Client Overview

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

In this practice, you invoke the mysql client using some of the common options.

Duration This practice should take approximately 10 minutes to complete.

Tasks 1. Display the mysql client version on the local host. 2. Display the mysql client options. 3. Start the mysql client with username and password options. Exit the client. 4. Start the mysql client with a login path of admin, and include a SELECT statement (that displays the current date and time in HTML format) as part of the command line execution. 5. Start the mysql client with username, port (set to 3306), and a tee file for this session. Allow the client to request the password. Enter the client password when requested. Exit the client and confirm the tee file creation. 6. Start the mysql client in Safe Updates mode.

s

o

an r t n

Sa

an s ha deฺ 7. Within the mysql client, display the session status. ) om Gui 8. List server-side help: c ฺ en dent a. Find the overall categories. e t tu b. List the commands related to account wa smanagement. S @ i nto setting c. Show information related hpasswords. a t h e 9. Display the available databases. rฺk o Exit us the client. e e f t a se s ( an licen h K r e fe

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

Practices for Lesson 5: Clients and Tools Chapter 5 - Page 3

e

bl a r fe

Solutions 5-1: Invoking the mysql Client Tasks

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

1. Display the mysql client version on the local host. Enter the following in a terminal window, and receive the result shown below: $ mysql -V mysql

Ver 14.14 Distrib 5.6.10, for Linux (x86_64) using

EditLine wrapper

2. Display the mysql client options. Enter the following in a terminal window, and receive the result shown below: $ mysql --help mysql Ver 14.14 Distrib 5.6.10, for Linux (x86_64) using EditLine wrapper Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

s

an r t n

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

Sa

no a s ฺ a h ) Usage: mysql [OPTIONS] [database] de i m u o -?, --help Display this help G ฺc andntexit. n e -I, --help Synonym tfor -? e ude aautomatic t rehashing. One doesn't need to --auto-rehash Enable w S @ s use n hi a t h ... e rฺk o us e max-join-size 1000000 e f t a e s secure-auth TRUE ( ens n a show-warnings FALSE c h li K (No default value) er plugin-dir

fe

default-auth histignore binary-mode server-public-key-path

(No default value) (No default value) FALSE (No default value)

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

Practices for Lesson 5: Clients and Tools Chapter 5 - Page 4

e

bl a r fe

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

3. Start the mysql client with username and password options. Exit the client. Enter the following in a terminal window, and receive the result shown below: $ mysql -uroot -poracle Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 2 Server version: 5.6.10-enterprise-commercial-advanced-log MySQL Enterprise Server - Advanced Edition (Commercial) 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.

Sa

e

bl a r Type 'help;' or '\h' for help. Type '\c' to clear the current input fe s n statement. tra n no mysql> EXIT a s ฺ Bye a h )for the user − Note that you could also use the following syntax deand password options: i m u o c also tthatGit is considered best practice --user=root --password=oracle. Note n and that you should use enฺ dline, to avoid using the password on thete command e alternative methods (for example where possible. tu wa--login-path) S @ s i and include a SELECT statement (that n path ofthadmin, 4. Start the mysql client with a login a h e k timeuinsHTML format) as part of the command line execution. displays the current date rฺand Enter the followingfe in e a terminal to window, and receive the result shown below: a e s $ mysql( --login-path=admin --html -e \ ns n e a c h "SELECT li CURRENT_DATE(), CURRENT_TIME()" K r

fee
CURRENT_DATE()CURRENT_TIME()
2013-02-0309:56:34
[prompt]$ − This returns the output for the date and time stamp query in HTML format, instead of the default tabular format. You can also redirect this output to a file by adding the following to the command: > /date_time.html 5. Start the mysql client with username, port (set to 3306), and a tee file for this session. Allow the client to request the password. Enter the client password when requested. Exit the client and confirm the tee file creation. a. Enter the following in a terminal window, and receive the result shown below: $ mysql -uroot -p -P 3306 --tee=tee_1.txt Logging to file 'tee_1.txt' Enter password: oracle Welcome to the MySQL monitor. Commands end with ; or \g. ... mysql> EXIT Bye

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

Practices for Lesson 5: Clients and Tools Chapter 5 - Page 5

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

b. View the tee file to make sure that it was created correctly by entering the following in a terminal window, and receive the result shown below: $ cat tee_1.txt Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 4 Server version: 5.6.10-enterprise-commercial-advanced-log MySQL Enterprise Server - Advanced Edition (Commercial) 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.

Sa

e

bl a r Type 'help;' or '\h' for help. Type '\c' to clear the current input fe s n statement. tra n no mysql> EXIT a sin a terminal a 6. Start the mysql client in Safe Updates mode. Enter the following window, and ฺ h e ) d i m receive the result shown below: co t Gu ฺ n $ mysql --login-path=admin --safe-updates en with ; or \g. ee udend Welcome to the MySQL monitor.at Commands w s St Your MySQL connection id is 5 @ n hi a t ... h e k us erฺdisplay 7. Within the mysql fclient, e o the session status. Enter the following in a terminal window, tbelow: a e and receive the result shown s ( ens n a mysql> h STATUS; lic K r -------------fee mysql Ver 14.14 Distrib 5.6.10, for Linux (x86_64) using EditLine wrapper Connection id: Current database: Current user: SSL: Current pager: Using outfile: Using delimiter: Server version: MySQL Enterprise Server Protocol version: Connection: Server characterset: Db characterset: Client characterset:

5 root@localhost Not in use stdout '' ; 5.6.10-enterprise-commercial-advanced-log - Advanced Edition (Commercial) 10 Localhost via UNIX socket latin1 latin1 utf8

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

Practices for Lesson 5: Clients and Tools Chapter 5 - Page 6

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

Conn. characterset: UNIX socket: Uptime:

utf8 /var/lib/mysql/mysql.sock 2 hours 28 min 59 sec

Threads: 1 Questions: 18 Slow queries: 0 Opens: 71 Open tables: 64 Queries per second avg: 0.000

Flush tables: 1

Note that you are running in safe_update_mode: UPDATEs and DELETEs that don't use a key in the WHERE clause are not allowed. (One can force an UPDATE/DELETE by adding LIMIT # at the end of the command.) SELECT has an automatic 'LIMIT 1000' if LIMIT is not used. Max number of examined row combination in a join is set to: 1000000

s

--------------

an r t n

8. List server-side help: a. Find the overall categories. Enter the following in a terminal window, and receive the result shown below:

S

er e f a

no a s ฺ a h mysql> HELP CONTENTS; ) de i You asked for help about help category:om "Contents" u G is one of the ฺc nwhere t n For more information, type 'help e ', following categories: ate Stude w Account Management @ is n h Administration ha t ฺk use r Compound Statements e fe e to Data Definition a s ( Manipulation ns Data n e a c li Kh Data Types Functions Functions and Modifiers for Use with GROUP BY Geographic Features Help Metadata Language Structure Plugins Procedures Storage Engines Table Maintenance Transactions User-Defined Functions Utility

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

Practices for Lesson 5: Clients and Tools Chapter 5 - Page 7

e

bl a r fe

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

b. List the commands related to account management. Enter the following in a terminal window, and receive the result shown below: mysql> HELP Account Management; You asked for help about help category: "Account Management" For more information, type 'help ', where is one of the following topics: ALTER USER CREATE USER DROP USER GRANT RENAME USER REVOKE SET PASSWORD

mysql> HELP SET PASSWORD; Name: 'SET PASSWORD' Description: Syntax: SET PASSWORD [FOR user] = { PASSWORD('cleartext password') | OLD_PASSWORD('cleartext password') | 'encrypted password' }

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a h se t k ฺ r ee e to u f a The SET(sPASSWORDs statement assigns a password to an existing MySQL enWhen the read_only system variable is enabled, the SUPER user anaccount. c i h l er K...

fe the available databases. Exit the client. Enter the following in a terminal window, Sa 9. Display and receive the result shown below: mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | world2 | | world_innodb | +--------------------+ 5 rows in set (0.00 sec) mysql> EXIT Bye

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

Practices for Lesson 5: Clients and Tools Chapter 5 - Page 8

e

bl a r fe

c. Show information related to setting passwords. Enter the following in a terminal window, and receive the result shown below:

Practice 5-2: Invoking the mysqladmin Client Overview

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

In this practice, you invoke the mysqladmin client, using some of the common options.

Duration This practice should take approximately 5 minutes to complete.

Tasks 1. Display the mysqladmin version running on the local host. 2. Display the mysqladmin client options. 3. Start the mysqladmin client with username, password, and list current variable settings.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 5: Clients and Tools Chapter 5 - Page 9

Solutions 5-2: Invoking the mysqladmin Client Tasks

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

1. Display the mysqladmin version running on the local host. Enter the following in a terminal window, and receive the result shown below: $ mysqladmin -V mysqladmin Ver 8.42 Distrib 5.6.10, for Linux on x86_64

2. Display the mysqladmin client options. Enter the following in a terminal window, and receive the result shown below: $ mysqladmin --help mysqladmin Ver 8.42 Distrib 5.6.10, for Linux on x86_64 Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

S

er e f a

e

bl a r Oracle is a registered trademark of Oracle Corporation and/or its fe ns affiliates. Other names may be trademarks of their respective a r t n owners. o an s Administration program for the mysqld daemon.ha eฺ ) d i Usage: mysqladmin [OPTIONS] command command.... m co to.t Gu --bind-address=name IP address tonฺbind e dento make. This works with -i teiterations -c, --count=# Number a of tu w sonly. S (--sleep) @ nCheck memory hi and open file usage at exit. a --debug-check t h e --debug-info rฺk Print s some debug info at exit. u e ... e o af se t Gives a short status message from the server s status ( an licen start-slave Start slave h K stop-slave variables version

Stop slave Prints variables available Get version info from server

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

Practices for Lesson 5: Clients and Tools Chapter 5 - Page 10

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

3. Start the mysqladmin client with username, password, and list current variable settings. Enter the following in a terminal window, and receive the result shown below: $ mysqladmin -uroot -poracle variables +------------------------------+-----------------+ | Variable_name | Value | +------------------------------+-----------------+ | audit_log_buffer_size | 1048576 | | audit_log_file | audit.log | | audit_log_flush | OFF | | audit_log_policy | ALL | | audit_log_rotate_on_size | 0 | | audit_log_strategy | ASYNCHRONOUS | | auto_increment_increment | 1 | | auto_increment_offset | 1 | | autocommit | ON | | automatic_sp_privileges | ON | | back_log | 80 | | basedir | /usr | ... | version_compile_machine | x86_64 | | version_compile_os | Linux | | wait_timeout | 28800 | +------------------------------+-----------------+

er e f a

e

bl a r fe

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ − You can also redirect this output to iasfile by adding the following to the command: n a th h > /mysqladmin_variables.txt e k ฺ er to us e f a se s ( an licen h K

S

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

Practices for Lesson 5: Clients and Tools Chapter 5 - Page 11

Practice 5-3: Viewing the MySQL Enterprise Monitor Demos Overview

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

In this practice, you run the web-based Enterprise Monitor demos, which show its primary features.

Duration This practice should take approximately 10 minutes to complete. Note: There are no separate solutions for this practice.

Tasks 1. Open the Mozilla Firefox web browser. 2. Browse to the “MySQL Enterprise Monitor: Dashboard” bookmark, and run the demo. Note: The demo runs from the following location: file:///labs/demos/memdashboard/memdashboard.html 3. Browse to the “MySQL Enterprise Monitor: Query Analyzer” bookmark, and run the demo. Note: The demo runs from the following location: file:///labs/demos/memqueryanalyzer/memqueryanalyzer.html

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 5: Clients and Tools Chapter 5 - Page 12

e

bl a r fe

Practice 5-4: Performing System Administration Tasks with MySQL Workbench

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

Overview In this practice, you install MySQL Workbench, and use it to create and populate a database, and work with its system administration features.

Duration This practice should take approximately 25 minutes to complete.

Tasks 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13.

Install MySQL Workbench from its RPM file in /stage/mysql. Launch MySQL Workbench by selecting Applications > Programming > MySQL Workbench. At the Home screen, create a new connection to the world_innodb schema and name it World. Use MySQL Workbench to launch a Query Database window. Query the world_innodb.Country table with MySQL Workbench. Query the world_innodb.City table with MySQL Workbench. Query both of the preceding tables at the same time. Use the Plug-ins menu to convert keywords in your query to uppercase. View the list of columns for the world_innodb.CountryLanguage table. Load the sakila database from scripts in your /labs directory, and refresh the Schemas list to confirm that it has loaded correctly. Create a new server instance for the Server Administration module. Connect to the new server instance. On the Server Status page, view the various status graphs showing system load, memory in use, connections in use, traffic, query cache hit-rate, and key efficiency. Select the Startup / Shutdown page and view the Database Server Status. Select the “Status and System Variables” page. On the Status Variables tab, select InnoDB/Stats. Note the InnoDB status variables that appear. Select the Options File page. View the configuration file location, and note that it is /etc/my.cnf. Browse the other pages and tabs within the “Admin (Local server)” tab. Close the “Admin (Local server)” tab.

S

er e f a 14. 15. 16. 17. 18. 19. 20.

s

o

an r t n

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

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

Practices for Lesson 5: Clients and Tools Chapter 5 - Page 13

e

bl a r fe

Solutions 5-4: Performing System Administration Tasks with MySQL Workbench

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

1.

Install MySQL Workbench from its RPM file in /stage/mysql. Execute the following commands in a terminal window and receive the results shown: $ su – Password: oracle # cd /stage/mysql # rpm -hi --nodeps mysql-workbench*.rpm

2. 3.

Launch MySQL Workbench by selecting Applications > Programming > MySQL Workbench. At the Home screen, create a new connection to the world_innodb schema and name it World. a. Under SQL Development, click New Connection. b. In the Setup New Connection dialog box, note the default Connection Method: Standard (TCP/IP), the default Hostname: 127.0.0.1, the default Port: 3306, and the default Username: root. c. For Connection Name, enter World.

s

an r t n

Sa

no a s ฺ d. For Default Schema, enter world_innodb. a h ) de e. Select the Advanced tab. i m u o c G ฺany. f. Note the default settings, but do not change t n n e g. Click Test Connection. ate Stude w h. Enter the password oracle @ and click iOK. s n h a t i. Click OK in the dialog ฺkhbox. use r e j. Click OK to save fe the enewtoconnection. a s 4. Use MySQL(Workbench nsto launch a Query Database window. n e a c a. Right-click the h li newly created World connection and select Query Database. K r feeb. Enter the password oracle and select the “Save password in keychain” option. c. d.

e.

Click OK. If this is the first time a keychain has been used on this system, you see another dialog box. Enter the password oracle once each in the Password field and the “Confirm password” field, and click Create. Note the following: − A new SQL Editor (World) tab appears in MySQL Workbench. − The SCHEMAS pane contains a list of user databases within the MySQL server, which currently consists of the databases world2 and world_innodb. − An empty “Query 1” pane appears, within which you can enter some SQL statements.

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

Practices for Lesson 5: Clients and Tools Chapter 5 - Page 14

e

bl a r fe

5.

Query the world_innodb.Country table with MySQL Workbench. a. Enter the following statement in the Query 1 pane:

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

select * from Country;

6.

b. Press Ctrl + Return to execute the statement. Query the world_innodb.City table with MySQL Workbench. a. Enter the following statement on a new line beneath the preceding statement in the Query 1 pane: select * from City;

b.

Press Ctrl + Return to execute the statement. Ensure that the cursor is flashing at the end of the query in the preceding step. 7. Query both of the preceding tables at the same time. a. Press Ctrl + Shift + Return to execute all statements in the editor window. Note: Two tabs appear in the results pane, one for each result set returned from statements in the query editor window. 8. Use the Plug-ins menu to convert keywords in your query to uppercase. a. In the menu, select Plugins > Utilities > “Make keywords in query uppercase.” 9. View the list of columns for the world_innodb.CountryLanguage table. a. In the SCHEMAS pane, browse to the “world_innodb” > Tables > CountryLanguage > Columns container, and browse the list of columns within the CountryLanguage table. When you click each column, note its definition in the Object Info pane. 10. Load the sakila database from scripts in your /labs directory, and refresh the Schemas list to confirm that it has loaded correctly. a. Select File > Open SQL Script. b. Browse to /labs/sakila-db/sakila-schema.sql. c. Press Ctrl + Shift + Return to execute the entire script. d. Select File > Open SQL Script. e. Browse to /labs/sakila-db/sakila-data.sql. f. In the Unknown File Encoding dialog box, click OK. g. Press Ctrl + Shift + Return to execute the entire script. h. In the Schemas pane, click the Refresh icon. Note that the sakila database appears. 11. Create a new server instance for the Server Administration module. a. Click the Home tab to return to the main screen. Under Server Administration, click New Server Instance. b. A Create New Server Instance Profile dialog box appears, showing the first of a series of pages similar to those covered in the “MySQL Clients” lesson. c. The first such page is labeled “Specify the Host Machine the Database Server is running on.” Click Next to accept the default, localhost. d. On the “Set the Database Connection Values” page, accept the default values and click Next. To test the connection details, you must enter the appropriate password. e. In the “Please enter password for the following service:” dialog box, enter the password oracle.

s

an r t n

o

S

er e f a

f.

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

On the “Testing the Database Connection” page, note the “Database connection tested successfully” message and click Next. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Clients and Tools Chapter 5 - Page 15

e

bl a r fe

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

g.

12.

On the “Specify the installation type for you target operation system” page select the following: − Operating System: Linux (already selected) − MySQL Installation Type: Generic Linux (MySQL tar package) h. Click Next. i. The process checks the configuration settings, and brings you to a screen labeled “Testing Host Machine Settings.” Note the “Testing host machine settings is done” message, and click Next. j. In the “Review settings” dialog box, click Continue. k. On the “Create the Instance Profile” page, enter Local server for the service instance name, and click Finish. Connect to the new server instance. a. On the main screen, note the new “Local server” entry under Server Administration. Double-click the “Local server” entry. b. If prompted, enter the password oracle. c. A new tab appears in Workbench, labeled “Admin (Local server),” with a number of pages on the left, divided into sections titled “Management,” “Configuration,” “Security,” and “Data Export/Restore.” On the Server Status page, view the various status graphs showing system load, memory in use, connections in use, traffic, query cache hit-rate, and key efficiency. Select the Startup / Shutdown page and view the Database Server Status. Select the “Status and System Variables” page. In the Status Variables tab, select InnoDB/Stats. Note the InnoDB status variables that appear. Select the Options File page. View the Configuration File location, and note that it is /etc/my.cnf. Browse the other pages and tabs within the “Admin (Local server)” tab. Close the “Admin (Local server)” tab.

s

o

an r t n

13. 14. 15. 16. 17. 18. 19. 20.

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 5: Clients and Tools Chapter 5 - Page 16

e

bl a r fe

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

e

bl a r fe

s

an r t n

er e f a

no a s ฺ 6: Data a Practices for Lesson h ) de i m Types u o ฺc nt G n e e u6 de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 6: Data Types Chapter 6 - Page 1

Practices for Lesson 6: Overview

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

Practices Overview In these practices, you test your knowledge of MySQL data types. The hands-on practices are written for the Oracle Linux operating system environment, which is provided in Oracle classrooms. For non-Oracle classrooms, some adjustments may need to be made regarding file locations.

Assumptions •

The MySQL server installation has been completed prior to this exercise.



You can access the mysql client from a command line prompt.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 6: Data Types Chapter 6 - Page 2

Practice 6-1: Quiz – MySQL Data Types Overview

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

In this practice, you answer questions about MySQL data types.

Duration This practice should take approximately 5 minutes to complete.

Quiz Questions Choose the best answer from those provided for each multiple choice or True/False question. 1. Which of the following are included in the four major data type categories? a. Temporal b. Numeric c. Binary d. Character e. All of the above 2. True or false: Data type declarations are made when the database is created, as part of the CREATE DATABASE statement. a. True b. False 3. True or false: MySQL does not support the use of fractional numbers for data types. a. True b. False 4. The BLOB data type is part of the __________ category. a. Character b. Numeric c. Temporal d. Binary e. All of the above 5. True or false: NULL column values are supported for data types within MySQL. a. True b. False 6. The following attributes can be used with all data types: a. NULL, NOT NULL, and DEFAULT

s

o

an r t n

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

b. INTEGER c. Column d. Numeric, String, and General

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

Practices for Lesson 6: Data Types Chapter 6 - Page 3

e

bl a r fe

Solutions 6-1: Quiz – MySQL Data Types

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

Quiz Solutions 1. e. All of the above. 2. b. False. The data types are initially assigned within the CREATE TABLE statement, as part of the column declaration. 3. b. False. Floating-point values (approximate-value numbers that have an integer part, a fractional part, or both) are supported as one of the Numeric category data types. 4. d. Binary 5. a. True 6. a. NULL, NOT NULL, and DEFAULT

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 6: Data Types Chapter 6 - Page 4

Practice 6-2: Setting a Data Type Overview

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

In this practice, you set and view one data type for a table column.

Assumptions •

You are logged in to the mysql client.

Duration This practice should take approximately 10 minutes to complete.

Tasks 1. Create a new database, test, to be used for table creation and data type setting.

s

an r t n

no a s ฺ a h ) de i m u o c G t CREATE TABLE CityCopy LIKE City; enฺ n e City; de INSERT INTO CityCopy SELECT *atFROM u t w S @ s 6. Display the CityCopy table’s structure (using a DESC statement) to confirm the current data i n h a table tstatus. Note the average row length and data hcurrent type settings, and show the e k ฺ s r length. ee e to u f a 7. Change the data (s typeenofsthe Population column of the CityCopy table to BIGINT (from n its original INT Then check the table structure and status again, noting the revised a setting). c i h l K average row length and data length. r e e f8. Drop the CityCopy table. 4. Display the integers table’s table status and note the data length for the data type value. 5. In the world_innodb database, create a copy of the City table by using the following statements:

Sa

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

Practices for Lesson 6: Data Types Chapter 6 - Page 5

e

bl a r fe

2. Create a table called integers in the new test database with a column named n (as a small, unsigned integer). Then add a data value of 5 to the table column. 3. Confirm that the integers table exists and contains the specified value, by using the SELECT statement.

Solutions 6-2: Setting a Data Type Tasks

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

1. Create a new database, test, to be used for table creation and data type setting. Enter the following in a terminal window, and receive the result shown below: mysql> CREATE DATABASE test; Query OK, 1 row affected (0.01 sec)

2. Create a table called integers in the new test database with a column named n (as a small, unsigned integer). Then add a data value of 5 to the table column. Enter the following in a terminal window, and receive the results shown below: mysql> USE test Database changed mysql> CREATE TABLE integers(n SMALLINT UNSIGNED); Query OK, 0 rows affected (0.97 sec) mysql> INSERT INTO integers VALUES (5); Query OK, 1 rows affected (0.03 sec)

Sa

e

bl a r fe

s

an r t n

no a 3. Confirm that the integers table exists and contains the specified by using the s value, a ฺ h SELECT statement. Enter the following in a terminal window, e the result shown ) and receive d i m below: u ฺco nt G mysql> SELECT * FROM integers; en ate Stude +------+ w @ his | n | n a h se t +------+ k ฺ r | 5 | ee e to u f a +------+ (s sete(0.01 ns sec) n 1 row in a c h li K r fee

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

Practices for Lesson 6: Data Types Chapter 6 - Page 6

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

4. Display the integers table’s table status and note the data length for the data type value. Enter the following in a terminal window, and receive the result shown below: mysql> SHOW TABLE STATUS LIKE 'integers'\G *************************** 1. row *************************** Name: integers Engine: InnoDB Version: 10 Row_format: Compact Rows: 1 Avg_row_length: 16384 Data_length: 16384 Max_data_length: 0 Index_length: 0 Data_free: 0 Auto_increment: NULL Create_time: 2012-10-04 19:53:31 Update_time: NULL Check_time: NULL Collation: latin1_swedish_ci Checksum: NULL Create_options: Comment: 1 row in set (0.00 sec)

e

s

an r t n

Sa

bl a r fe

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ is of the City table by using the following n 5. In the world_innodb database, create tahcopy a e window, and receive the result shown below: ฺkh inuasterminal statements. Enter the following r e e e to fworld_innodb; mysql> USE a s s ( tableeninformation Reading for completion of table and column names n a c i h l KYou can turn off this feature to get a quicker startup with -A r e fe Database changed mysql> CREATE TABLE CityCopy LIKE City; Query OK, 0 rows affected (0.21 sec)

mysql> INSERT INTO CityCopy SELECT * FROM City; Query OK, 4079 rows affected, 1 warning (0.44 sec) Records: 4079 Duplicates: 0 Warnings: 1

MySQL generates a warning because statement-based logging does not replicate autoincrement columns in a safe way. You can ignore this warning in the current lesson.

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

Practices for Lesson 6: Data Types Chapter 6 - Page 7

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

6. Display the CityCopy table’s structure (using a DESC statement) to confirm the current data type settings, and show the current table status. Note the average row length and data length. a. Enter the following in a terminal window, and receive the result shown below: mysql> DESC CityCopy; +-------------+----------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+----------+------+-----+---------+----------------+ | 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.07 sec)

s

an r t n

mysql> SHOW TABLE STATUS LIKE 'CityCopy'\G *************************** 1. row *************************** Name: CityCopy Engine: InnoDB Version: 10 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: 2012-10-04 20:05:13 Update_time: NULL Check_time: NULL Collation: latin1_swedish_ci Checksum: NULL Create_options: Comment: 1 row in set (0.00 sec)

o

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

7. Change the data type of the Population column of the CityCopy table to BIGINT (from its original INT setting). Then check the table structure and status again, noting the revised average row length and data length. a. Enter the following in a terminal window, and receive the result shown below: mysql> ALTER TABLE CityCopy MODIFY Population BIGINT; Query OK, 4079 rows affected (0.02 sec) Records: 4079 Duplicates: 0 Warnings: 0

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

Practices for Lesson 6: Data Types Chapter 6 - Page 8

e

bl a r fe

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

b. Then check the table status again. Enter the following in a terminal window, and receive the result shown below: mysql> DESC CityCopy; +-------------+-----------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+-----------+------+-----+---------+----------------+ | ID | int(11) | NO | PRI | NULL | auto_increment | | Name | char(35) | NO | | | | | CountryCode | char(3) | NO | MUL | | | | District | char(20) | NO | | | | | Population | bigint(20)| YES | | 0 | | +-------------+-----------+------+-----+---------+----------------+ mysql> SHOW TABLE STATUS LIKE 'CityCopy'\G *************************** 1. row *************************** Name: CityCopy Engine: InnoDB Version: 10 Row_format: Compact Rows: 4118 Avg_row_length: 103 Data_length: 425984 Max_data_length: 0 Index_length: 131072 Data_free: 0 Auto_increment: 4080 Create_time: 2012-10-04 20:13:28 Update_time: NULL Check_time: NULL Collation: latin1_swedish_ci Checksum: NULL Create_options: Comment: 1 row in set (0.00 sec)

e

bl a r fe

s

an r t n

o

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

The average row length and data length values have increased, due to the increase in the size of the Population column. 8. Drop the CityCopy table. Enter the following in a terminal window, and receive the result shown below: mysql> DROP TABLE CityCopy; Query OK, 0 rows affected (0.04 sec)

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

Practices for Lesson 6: Data Types Chapter 6 - Page 9

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

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 6: Data Types Chapter 6 - Page 10

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

e

s

bl a r fe

an r t n

er e f a

no a s ฺ 7: a Practices for Lesson h ) Metadata de i m Obtaining u o ฺc nt G n e e u7 de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 7: Obtaining Metadata Chapter 7 - Page 1

Practices for Lesson 7: Overview

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

Practices Overview In these practices, you test your knowledge of Obtaining MySQL database metadata. The hands-on practices are written for the Oracle Linux operating system environment, which is provided in Oracle classrooms. For non-Oracle classrooms, some adjustments may need to be made regarding file locations.

Assumptions •

The MySQL server installation has been completed prior to these practices.



You are logged in as oracle user in a terminal window.



You can access the mysql client from a command line prompt.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 7: Obtaining Metadata Chapter 7 - Page 2

Practice 7-1: Obtaining Metadata by Using INFORMATION_SCHEMA Overview

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

In this practice, you query the INFORMATION_SCHEMA database for metadata.

Duration This practice should take approximately 15 minutes to complete.

Tasks 1. Obtain metadata about the world_innodb database (schema), by using a SELECT statement against the SCHEMATA table in the INFORMATION_SCHEMA database. 2. Select the name and engine of the tables in the world_innodb database (schema), by using a SELECT statement against the TABLE_SCHEMA table in the INFORMATION_SCHEMA database. 3. List the number of tables, per storage engine, for each database (schema), by using a SELECT statement with a GROUP BY clause against the TABLE_SCHEMA table in the INFORMATION_SCHEMA database. 4. List the data length of the City table in the world_innodb database, by using a SELECT statement against the TABLES table in the INFORMATION_SCHEMA database. 5. List the number of table columns in the world_innodb database that are using the CHAR or the VARCHAR data types, by using a SELECT statement with the COUNT(*) option against the COLUMNS table in the INFORMATION_SCHEMA database.

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 7: Obtaining Metadata Chapter 7 - Page 3

e

bl a r fe

Solutions 7-1: Obtaining Metadata by Using INFORMATION_SCHEMA

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

Tasks 1. Obtain metadata about the world_innodb database (schema), by using a SELECT statement against the SCHEMATA table in the INFORMATION_SCHEMA database. Enter the following in a terminal window, and receive the result shown below: $ mysql -uroot -poracle ... mysql> SELECT * -> FROM INFORMATION_SCHEMA.SCHEMATA -> WHERE SCHEMA_NAME = 'world_innodb'\G *************************** 1. row *************************** CATALOG_NAME: def SCHEMA_NAME: world_innodb DEFAULT_CHARACTER_SET_NAME: latin1 DEFAULT_COLLATION_NAME: latin1_swedish_ci SQL_PATH: NULL 1 row in set (0.00 sec)

e

s

an r t n

Sa

bl a r fe

no a s ฺ a h ) database de (schema), by i m 2. Select the name and engine of the tables in the world_innodb u o G ฺc table t using a SELECT statement against the TABLE_SCHEMA in the INFORMATION_SCHEMA n n e e e t database. Enter the following in a terminal d receive the result shown below: a window, tuand w S mysql> USE INFORMATION_SCHEMA @ his n a Reading table information h sefort completion of table and column names k ฺ r You can turn off to get a quicker startup with -A u ee ethis o feature f t a (s changed ns n Database e a c h li TABLE_NAME, ENGINE mysql> SELECT K r -> FROM TABLES fee -> WHERE TABLE_SCHEMA = 'world_innodb'; +-----------------+--------+ | TABLE_NAME | ENGINE | +-----------------+--------+ | City | InnoDB | | Country | InnoDB | | CountryLanguage | InnoDB | +-----------------+--------+

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

Practices for Lesson 7: Obtaining Metadata Chapter 7 - Page 4

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

3. List the number of tables, per storage engine, for each database (schema), by using a SELECT statement with a GROUP BY clause against the TABLE_SCHEMA table in the INFORMATION_SCHEMA database. Enter the following in a terminal window, and receive the result shown below: mysql> SELECT TABLE_SCHEMA, ENGINE, COUNT(*) -> FROM TABLES -> GROUP BY TABLE_SCHEMA, ENGINE; +--------------------+--------------------+----------+ | TABLE_SCHEMA | ENGINE | COUNT(*) | +--------------------+--------------------+----------+ | information_schema | MEMORY | 50 | | information_schema | MyISAM | 10 | | mysql | CSV | 2 | | mysql | InnoDB | 5 | | mysql | MyISAM | 21 | | performance_schema | PERFORMANCE_SCHEMA | 52 | | sakila | NULL | 7 | | sakila | InnoDB | 15 | | sakila | MyISAM | 1 | | test | InnoDB | 1 | | world2 | InnoDB | 3 | | world_innodb | InnoDB | 3 | +--------------------+--------------------+----------+ 12 rows in set (0.01 sec)

e

bl a r fe

s

an r t n

S

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a t world_innodb database, by using a SELECT h tablesein the 4. List the data length of theฺk City r u in the INFORMATION_SCHEMA database. Enter the statement against fthe table eeTABLES o t a following in a(terminal s nwindow, se and receive the result shown below: n e mysql> ic TABLE_NAME, DATA_LENGTH ha -> SELECT l K FROM TABLES er e f -> WHERE TABLE_SCHEMA = 'world_innodb' a -> AND TABLE_NAME = 'City'; +------------+-------------+ | TABLE_NAME | DATA_LENGTH | +------------+-------------+ | City | 409600 | +------------+-------------+

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

Practices for Lesson 7: Obtaining Metadata Chapter 7 - Page 5

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

5. List the number of table columns in the world_innodb database that are using the CHAR or the VARCHAR data types, by using a SELECT statement with the COUNT(*) option against the COLUMNS table in the INFORMATION_SCHEMA database. Enter the following in a terminal window, and receive the result shown below: mysql> SELECT DATA_TYPE, COUNT(*) -> FROM COLUMNS -> WHERE TABLE_SCHEMA = 'world_innodb' -> AND DATA_TYPE IN ('CHAR', 'VARCHAR') -> GROUP BY DATA_TYPE; +-----------+----------+ | DATA_TYPE | COUNT(*) | +-----------+----------+ | char | 12 | +-----------+----------+

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 7: Obtaining Metadata Chapter 7 - Page 6

e

bl a r fe

− There are no VARCHAR data types in the world_innodb database; therefore, it does not show up in the output.

Practice 7-2: Obtaining Metadata by Using SHOW and DESCRIBE Overview

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

In this practice, you use the SHOW and DESCRIBE statements to database obtain metadata.

Duration This practice should take approximately 10 minutes to complete.

Tasks 1. List all the available databases. 2. List all the databases that have the letter ‘o’ in their name. 3. List all the available INFORMATION_SCHEMA database tables. 4. Show detailed information about the columns in the City table from the world_innodb database. 5. Show the index information for the City table from the world_innodb database. 6. Show the structure of the CountryLanguage table from the world_innodb database. 7. List all character sets available. 8. List all collations available. 9. Exit the mysql client.

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 7: Obtaining Metadata Chapter 7 - Page 7

e

bl a r fe

Solutions 7-2: Obtaining Metadata by Using SHOW and DESCRIBE Tasks

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

1. List all the available databases. Using the mysql client that you opened in the previous practice, enter the following in a terminal window, and receive the result shown below: mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sakila | | test | | world2 | | world_innodb | +--------------------+ 7 rows in set (0.00 sec)

Sa

e

bl a r fe

s

an r t n

no a 2. List all the databases that have the letter ‘o’ in their name.)Enter hasthedfollowing eฺ in a terminal i m window, and receive the result shown below: co t Gu mysql> SHOW DATABASES LIKE '%o%';enฺ n e e t d +--------------------+ wa s Stu | Database (%o%) | @ n hi a t +--------------------+ h e rฺk o| us | information_schema e e af se t | | performance_schema s ( | world2 | an licen h K | world_innodb | r e +--------------------+ fe 4 rows in set (0.00 sec)

3. List all the available INFORMATION_SCHEMA database tables. Enter the following in a terminal window, and receive the results shown below: a. Change the database to information_schema: mysql> USE information_schema; Database changed

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

Practices for Lesson 7: Obtaining Metadata Chapter 7 - Page 8

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

b. List the tables in the information_schema database: mysql> SHOW TABLES; +---------------------------------------+ | Tables_in_information_schema | +---------------------------------------+ | CHARACTER_SETS | | COLLATIONS | | COLLATION_CHARACTER_SET_APPLICABILITY | | COLUMNS | | COLUMN_PRIVILEGES | ... | INNODB_BUFFER_POOL_STATS | | INNODB_SYS_COLUMNS | | INNODB_SYS_FOREIGN | +---------------------------------------+ 60 rows in set (0.00 sec)

e

bl a r fe

s

an r t n

4. Show detailed information about the columns in the City table from the world_innodb database. Enter the following in a terminal window, and receive the result shown below: a. Change the database to world_innodb:

S

er e f a

no a s ฺ a h mysql> USE world_innodb ) dande column names i m u Reading table information for completion of table o Gstartup with -A ฺca quicker t n You can turn off this feature to e get n ate Stude w @ his Database changed n a t table: h for theseCity b. List all the column info k ฺ r e to u FROM City\G mysql> SHOWfe FULL COLUMNS a *************************** 1. row *************************** (s ense n Field: ID a c li int(11) Kh Type: Collation: NULL Null: NO Key: PRI Default: NULL Extra: auto_increment Privileges: select,insert,update,references Comment: *************************** 2. row *************************** Field: Name Type: char(35) Collation: latin1_swedish_ci Null: NO Key: Default: Extra: Privileges: select,insert,update,references Comment: *************************** 3. row *************************** Field: CountryCode Type: char(3) Collation: latin1_swedish_ci Null: NO Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Obtaining Metadata Chapter 7 - Page 9

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

Key: MUL Default: Extra: Privileges: select,insert,update,references Comment: *************************** 4. row *************************** Field: District Type: char(20) Collation: latin1_swedish_ci Null: NO Key: Default: Extra: Privileges: select,insert,update,references Comment: *************************** 5. row *************************** Field: Population Type: int(11) Collation: NULL Null: NO Key: Default: 0 Extra: Privileges: select,insert,update,references Comment: 5 rows in set (0.00 sec)

e

s

an r t n

Sa

bl a r fe

no a s ฺ a h ) de i m u o ฺc nt G n e 5. Show the index information for the City table from thee world_innodb database. Enter the tethe result d a u following in a terminal window, and receive shown below: t w sS @ mysql> SHOW INDEX FROMnCity\G hi ha se 1.t row *************************** *************************** k ฺ r u Table: ee City f Non_unique: 0 e to a s (s enPRIMARY Key_name: n a c Seq_in_index: 1 hColumn_name: li ID K r Collation: A fee Cardinality: 4188 Sub_part: NULL Packed: NULL Null: Index_type: BTREE Comment: Index_comment: *************************** 2. row *************************** Table: City Non_unique: 1 Key_name: CountryCode Seq_in_index: 1 Column_name: CountryCode Collation: A Cardinality: 465 Sub_part: NULL Packed: NULL Null: Index_type: BTREE Comment: Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Obtaining Metadata Chapter 7 - Page 10

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

Index_comment: 2 rows in set (0.01 sec)

Note: The INFORMATION_SCHEMA tables TABLE_CONSTRAINTS and STATISTICS also contain index metadata. 6. Show the structure of the CountryLanguage table from the world_innodb database. Enter the following in a terminal window, and receive the result shown below: mysql> DESCRIBE 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.03 sec)

e

S

bl a r 7. List all character sets available. Enter the following in a terminal window, and receivesthe fe n result shown below: ra t n mysql> SHOW CHARACTER SET; no +---------+---------------------------+---------------------+--------+ a scollation | Charset | Description | Default | Maxlen | a ฺ h +---------+---------------------------+---------------------+--------+ ) de i | big5 | Big5 Traditional Chinese |om big5_chinese_ci | 2 | u c| dec8_swedish_ci G ฺ | dec8 | DEC West European | 1 | t n n e | cp850 | DOS West European tee |dcp850_general_ci | 1 | a Stu| hp8_english_ci | hp8 | HP West European | 1 | w @ | koi8r | KOI8-R Relcom Russian | koi8r_general_ci | 1 | s i n h a t ... h Windows ฺkfor se Japanese | eucjpms_japanese_ci | | eucjpms | UJIS 3 | r u e e o +---------+---------------------------+---------------------+--------+ f t a se sec) 40 rows(sin set (0.02 n en −ha A full listliofccharacter sets on the current system is displayed. Kall collations available. Enter the following in a terminal window, and receive the result r 8. eList afe shown below: mysql> SHOW COLLATION; +---------------------+---------+-----+---------+----------+---------+ | Collation | Charset | Id | Default | Compiled | Sortlen | +---------------------+---------+-----+---------+----------+---------+ | big5_chinese_ci | big5 | 1 | Yes | Yes | 1 | | big5_bin | big5 | 84 | | Yes | 1 | | dec8_swedish_ci | dec8 | 3 | Yes | Yes | 1 | | dec8_bin | dec8 | 69 | | Yes | 1 | | cp850_general_ci | cp850 | 4 | Yes | Yes | 1 | | cp850_bin | cp850 | 80 | | Yes | 1 | ... | eucjpms_bin | eucjpms | 98 | | Yes | 1 | +---------------------+---------+-----+---------+----------+---------+ 219 rows in set (0.00 sec)

− A full list of collations on the current system is displayed.

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

Practices for Lesson 7: Obtaining Metadata Chapter 7 - Page 11

9. Exit the mysql client. Enter the following in a terminal window, and receive the result shown below:

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

mysql> EXIT Bye

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 7: Obtaining Metadata Chapter 7 - Page 12

Practice 7-3: Obtaining Metadata by Using mysqlshow Overview

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

In this practice, you use the mysqlshow client to obtain database metadata.

Duration This practice should take approximately 5 minutes to complete.

Tasks 1. Using the mysqlshow application from the command line, list all the available databases. 2. List all the tables in the world_innodb database, from the command line. 3. Show the structure of the CountryLanguage table in the world_innodb database, from the command line.

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 7: Obtaining Metadata Chapter 7 - Page 13

e

bl a r fe

Solutions 7-3: Obtaining Metadata by Using mysqlshow Tasks

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

1. Using the mysqlshow application from the command line, list all the available databases. Enter the following in a terminal window, and receive the result shown below: $ mysqlshow -uroot -poracle Warning: Using a password on the command line interface can be insecure. +--------------------+ | Databases | +--------------------+ | information_schema | | mysql | | performance_schema | | sakila | | test | | world2 | | world_innodb | +--------------------+

e

an r t n

s

Sa

no a s ฺ a h ) command 2. List all the tables in the world_innodb database, from the deline. Enter the i m u o following in a terminal window, and receive the result below: G ฺc shown t n n e $ mysqlshow world_innodb -uroot de ate-poracle u t +-----------------+ w S | Tables | n@ s i h +-----------------+ ha se t k ฺ r | City | e | to u | Country fe a | CountryLanguage (s ense| n +-----------------+ ha lic K r fee

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

Practices for Lesson 7: Obtaining Metadata Chapter 7 - Page 14

bl a r fe

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

3. Show the structure of the CountryLanguage table in the world_innodb database, from the command line. Enter the following in a terminal window, and receive the result shown below: # mysqlshow world_innodb CountryLanguage -uroot -oracle Database: world_innodb Table: CountryLanguage +-------------+---------------+-------------------+------+-----+--------+-------+---------------------------------+---------+ | Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment | +-------------+---------------+-------------------+------+-----+--------+-------+---------------------------------+---------+ | CountryCode | char(3) | latin1_swedish_ci | NO | PRI | | | select,insert,update,references | | | Language | char(30) | latin1_swedish_ci | NO | PRI | | | select,insert,update,references | | | IsOfficial | enum('T','F') | latin1_swedish_ci | NO | | F | | select,insert,update,references | | | Percentage | float(4,1) | | NO | | 0.0 | | select,insert,update,references | | +-------------+---------------+-------------------+------+-----+--------+-------+---------------------------------+---------+

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 7: Obtaining Metadata Chapter 7 - Page 15

e

bl a r fe

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

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 7: Obtaining Metadata Chapter 7 - Page 16

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

e

s

bl a r fe

an r t n

er e f a

no a s ฺ 8: a Practices for Lesson h ) and de Locking i m Transactions u o ฺc nt G n e e u8 de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 1

Practices for Lesson 8: Overview

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

Practices Overview In these practices, you test your knowledge of transactions and locking in MySQL. The handson practices are written for the Oracle Linux operating system environment, which is provided in Oracle classrooms. For non-Oracle classrooms, some adjustments may need to be made regarding file locations.

Assumptions •

The MySQL server installation has been completed prior to these practices.



You are logged in as the oracle user in a terminal window.



You can access the mysql client from a command line prompt.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 2

Practice 8-1: Quiz – Transactions and Locking Overview

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

In this practice, you answer questions pertaining to transactions and locking using the MySQL server.

Duration This practice should take approximately 10 minutes to complete.

Quiz Questions Choose the best answer from those provided for each multiple choice or True/False question. 1. A transaction is a collection of data manipulation execution steps that are treated as a single unit of work. a. True b. False 2. When the term ACID compliant is used, it refers to the fact that the transactions in MySQL are __________, consistent, _________, and durable. a. atomic, isolated b. automatic, isolated c. atomic, independent d. always on, intended for transactions 3. If AUTOCOMMIT is not enabled, __________________. The transaction is then explicitly committed or rolled back using the COMMIT and ROLLBACK statements respectively. After the transaction terminates, a new transaction is implicitly started. a. transactions include only a single statement at a time b. the server asks you for the value of the AUTOCOMMIT setting before proceeding c. transactions span multiple statements by default 4. The four transaction isolation levels include READ UNCOMMITTED, READ COMMITTED, REPEATABLE, and ISOLATED. a. True b. False 5. Three types of inconsistencies can occur when two simultaneous transactions access the same table: ___________________, non-repeatable read, and/or phantom row/read. a. repeatable read b. “dirty” read c. “polluted” read 6. A SERIALIZABLE level allows non-repeatable reads. a. True b. False 7. Locking is a mechanism to prevent concurrency problems, which is managed by the MySQL server and locks for one client in order to _____________. a. isolate the master client b. remove any non-MySQL clients c. restrict other clients

s

o

an r t n

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 3

e

bl a r fe

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

8. The two locking modifiers that InnoDB supports are LOCK IN SHARE MODE and FOR UPDATE. a. True b. False 9. Both locking types lock selected ______________ to prevent problems that can occur when there is simultaneous access of table data. a. lock(s) b. table(s) c. read(s) d. row(s)

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 4

Solutions 8-1: Quiz – Transactions and Locking

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

Quiz Solutions 1. 2. 3. 4. 5. 6.

a. True. a. ACID = atomic, consistent, isolated, durable c. span multiple statements by default b. False. The last two are actually REPEATABLE READ and SERIALIZABLE. b. “dirty” read. b. False. SERIALIZABLE completely isolates the effects of one transaction from others. It is similar to REPEATABLE READ with the additional restriction that rows selected by one transaction cannot be changed by another until the first transaction finishes. 7. c. restrict other clients. MySQL does this using either a shared or an exclusive lock. 8. a. True. 9. d. row(s).

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 5

e

bl a r fe

Practice 8-2: Using Transaction Control Statements Overview

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

In this practice, you use the transaction control statements to start, manipulate, and commit SQL transactions.

Duration This practice should take approximately 15 minutes to complete.

Tasks 1.

Determine whether any transactional storage engines are available on your system, and determine which one is the default engine, by using the SHOW ENGINES command.

2.

Enable AUTOCOMMIT by using the SET AUTOCOMMIT statement.

Prepare to use the world_innodb database, and confirm that the City table does use the transactional storage engine, InnoDB. 4. Explicitly start a new transaction by using the START TRANSACTION statement. 5. Delete a row. 6. Roll back the open transaction by using the ROLLBACK statement. 7. Start another new transaction. 8. Delete the same row again. 9. Stop and commit the transaction by using the COMMIT statement. 10. Confirm that the row is now gone. 11. Try to roll back the committed transaction.

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 6

e

bl a r fe

3.

Solutions 8-2: Using Transaction Control Statements

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

Tasks 1. Determine whether any transactional storage engines are available on your system, and determine which one is the default engine, by using the SHOW ENGINES command. Enter the following in a terminal window, and receive the result shown below: $ mysql -uroot -poracle ... mysql> SHOW ENGINES\G ... *************************** 5. row *************************** Engine: MyISAM Support: YES Comment: MyISAM 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 ...

s

an r t n

o

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

− The order of the list may differ, per system. Regardless of the order, the InnoDB storage engine is indicated as the default, and includes transactions. 2. Enable AUTOCOMMIT by using the SET AUTOCOMMIT statement. Enter the following in a terminal window, and receive the results shown below: a. Set the AUTOCOMMIT mode to on: mysql> SET AUTOCOMMIT = 1; Query OK, 0 rows affected (0.06 sec)

b. Check the value to confirm: mysql> SELECT @@AUTOCOMMIT; +--------------+ | @@AUTOCOMMIT | +--------------+ | 1 | +--------------+ 1 row in set (0.02 sec)

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 7

e

bl a r fe

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

3. Prepare to use the world_innodb database, and confirm that the City table does use the transactional storage engine, InnoDB. Enter the following in a terminal window, and receive the results shown below: a. Change to the world_innodb database: mysql> USE world_innodb ... Database changed

b. Display the City table structure, and confirm that the value of ENGINE is InnoDB: 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`), CONSTRAINT `city_ibfk_1` FOREIGN KEY (`CountryCode`) REFERENCES `Country` (`Code`) ) ENGINE=InnoDB AUTO_INCREMENT=4080 DEFAULT CHARSET=latin1 1 row in set (0.00 sec)

s

an r t n

Sa

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ theisSTART TRANSACTION statement. Enter the n 4. Explicitly start a new transaction by usingth a e the result shown below: ฺkh andusreceive following in a terminal window, r e feTRANSACTION; to mysql> START a e s ( rows ns affected (0.00 sec) Query OK, 0 e n a c ha row. Enter li the following in a terminal window, and receive the results shown below: K 5. Delete r fee a. Select the row that contains the city named “Manta”: mysql> SELECT * FROM City WHERE Name = 'Manta'; +-----+-------+-------------+----------+------------+ | ID | Name | CountryCode | District | Population | +-----+-------+-------------+----------+------------+ | 600 | Manta | ECU | Manabí | 164739 | +-----+-------+-------------+----------+------------+ 1 row in set (0.06 sec)

b. Select the row that contains the city named “Manta”: mysql> DELETE FROM City WHERE Name = 'Manta'; Query OK, 1 row affected (0.02 sec)

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 8

e

bl a r fe

c. Select the row that contains the city named “Manta”:

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

mysql> SELECT * FROM City WHERE Name = 'Manta'; Empty set (0.00 sec)

− The first SELECT confirms the existence of the city of Manta. The delete returns OK, indicating that one row was affected. The second SELECT shows that the row is now empty. 6. Roll back the open transaction by using the ROLLBACK statement. Enter the following in a terminal window, and receive the results shown below: a. Roll back the open transaction: mysql> ROLLBACK; Query OK, 0 rows affected (0.05 sec)

b. Confirm that the row is now back to its original state: mysql> SELECT * FROM City WHERE Name = 'Manta'; +-----+-------+-------------+----------+------------+ | ID | Name | CountryCode | District | Population | +-----+-------+-------------+----------+------------+ | 600 | Manta | ECU | Manabí | 164739 | +-----+-------+-------------+----------+------------+ 1 row in set (0.06 sec)

Sa

e

bl a r fe

s

an r t n

no a s ฺ a − The result shows that the row is now back. h ) window, de and receive the i m 7. Start another new transaction. Enter the following in o a terminal u ฺc nt G result shown below: n e mysql> START TRANSACTION; ate Stude w Query OK, 0 rows affected @(0.00 issec) n h a t 8. Delete the same row again. ฺkhEnteruthe sefollowing in a terminal window, and receive the results r e shown below: to WHERE Name = 'Manta'; afe FROM e mysql> (DELETE City s nsaffected (0.02 sec) n e Query OK, 1 row a c h li Kand r 9. eStop commit the transaction by using the COMMIT statement. Enter the following in a fe terminal window, and receive the result shown below: mysql> COMMIT; Query OK, 0 rows affected (0.04 sec)

10. Confirm that the row is now gone. Enter the following in a terminal window, and receive the result shown below: mysql> SELECT * FROM City WHERE Name = 'Manta'; Empty set (0.00 sec)

− The final SELECT shows that the row does not exist anymore, and that this DELETE cannot be undone. 11. Try to roll back the committed transaction. Enter the following in a terminal window, and receive the results shown below: a. Roll back the open transaction: mysql> ROLLBACK; Query OK, 0 rows affected (0.05 sec)

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 9

b. Confirm the current status of the row: mysql> SELECT * FROM City WHERE Name = 'Manta'; Empty set (0.00 sec)

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

− The result shows that the row is still empty because the transaction was committed before this rollback took place.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 10

Practice 8-3: Additional Practice with Transactions and Locking Overview

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

In this practice, you use transaction and locking statements.

Duration This practice should take approximately 30 minutes to complete.

Tasks 1. From a mysql client session, check the current isolation level. 2. Using the PROMPT statement, change the prompt to t1 in the mysql session opened in the preceding step, to differentiate between this and future client sessions. 3. Start a new transaction in the t1 mysql session. 4. In the t1 session, select all rows from the City table where the ID > 4070.

e

S

bl a r 5. In a separate terminal window, open a second mysql session. Change the prompt to ft2e in s n the mysql session. tra n 6. Start a transaction in the t2 mysql session. no a 7. In the t2 session, from the world_innodb database, select all s rows from the City table a h where the ID > 4070. eฺ ) d i m u the new row has been oConfirmGthat 8. In the t2 session, insert a new row to the City table. c ฺ t n added. Enter the following in the t2 terminal window: e den e t a Stu VALUES ('New City', 'ATA'); t2> INSERT INTO City (Name, wCountryCode) @ is again. Do you now see the row? n 9. In the t1 session, select the city with ID t>h4070 a h transaction. ฺkthe se 10. In the t2 session, commit r u e e ethetotransaction. Select the city with ID > 4070 again. fcommit 11. In the t1 session, a s ( enins the t1 mysql session. n 12. Start a new transaction a ht1 session,licremove the row that was inserted to the City table. Confirm the removal K 13. Inr the e afe of the row. Isolation level change: 14. In the t2 session, change the isolation level to READ UNCOMMITTED by using the SET SESSION tx_isolation command, and confirm the change.

15. Start a new transaction in the t2 session. Select the city with ID > 4070. What is the problem with this read? 16. In the t1 session, cancel the transaction by using the ROLLBACK statement. Select the city with ID > 4070 again. 17. In the t2 session, select the city with ID > 4070. Are the results the same as in the same query to the t1 session in the previous step? 18. In the t2 session, cancel any transaction that was registered by this session. 19. In preparation for the next practice, exit the both mysql sessions, as well as both terminal windows.

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 11

Solutions 8-3: Additional Practice with Transactions and Locking Tasks

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

1. From a mysql client session, check the current Isolation level. Enter the following in a terminal window, and receive the results shown below: $ mysql -uroot -poracle ... mysql> SELECT @@global.tx_isolation; +-----------------------+ | @@global.tx_isolation | +-----------------------+ | REPEATABLE-READ | +-----------------------+ 1 row in set (0.00 sec)

e

S

bl a r 2. Change the prompt to t1 in the mysql session opened in the preceding step, to differentiate sfe n between this and future client sessions. Enter the following in a terminal window,aand -tr receive the result shown below: n o n mysql> PROMPT t1> ; a s PROMPT set to 't1> ' ha deฺ ) t1> m ui o c G ฺ 3. Start a new transaction in the t1 mysql session. the tfollowing in the t1 terminal n en Enter e e window, and receive the result shown below: t a Stud a. Start the new transaction: @w is n h a t t1> START TRANSACTION; h se ฺkaffected r Query OK, 0 rows e e e to u (0.00 sec) f a 4. In the t1 session, the s world_innodb database, select all rows from the City table (s from n n e wherehthe a ID > 4070. lic Enter the following in the t1 terminal window, and receive the results K shown below: er t1> USE world_innodb e f a ... Database changed t1> SELECT * FROM City WHERE ID > 4070; +------+--------------+-------------+------------+------------+ | ID | Name | CountryCode | District | Population | +------+--------------+-------------+------------+------------+ | 4071 | Mount Darwin | ZWE | Harare | 164362 | | 4072 | Mutare | ZWE | Manicaland | 131367 | | 4073 | Gweru | ZWE | Midlands | 128037 | | 4074 | Gaza | PSE | Gaza | 353632 | | 4075 | Khan Yunis | PSE | Khan Yunis | 123175 | | 4076 | Hebron | PSE | Hebron | 119401 | | 4077 | Jabaliya | PSE | North Gaza | 113901 | | 4078 | Nablus | PSE | Nablus | 100231 | | 4079 | Rafah | PSE | Rafah | 92020 | +------+--------------+-------------+------------+------------+ 9 rows in set (0.00 sec)

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 12

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

5. In a separate terminal window, open a second mysql session. Change the prompt to t2 in the mysql session. Enter the following in a terminal window, and receive the results shown below: $ mysql -uroot -poracle ... mysql> PROMPT t2> ; PROMPT set to 't2> ' t2>

6. Start a transaction in the t2 mysql session. Enter the following in the t2 terminal window, and receive the result shown below: t2> START TRANSACTION; Query OK, 0 rows affected (0.00 sec)

7. In the t2 session, from the world_innodb database, select all rows from the City table where the ID > 4070. Enter the following in the t2 terminal window, and receive the result shown below: t2> USE world_innodb Database changed

S

er e f a

s

an r t n

no a s ฺ a t2> SELECT * FROM City WHERE ID > 4070; h ) de +------+--------------+-------------+------------+------------+ i m u o | ID | Name | CountryCode ฺ|cDistrict G | Population | t n n e +------+--------------+-------------+------------+------------+ e |uHarare de | 4071 | Mount Darwin | ZWE at | 164362 | t w S | 4072 | Mutare |@ ZWE | Manicaland | 131367 | s i n | 4073 | Gweru | ZWE | MIDlands | 128037 | h a et | 4074 | Gaza rฺkh | PSE | Gaza | 353632 | s u e | 4075 | Khan Yunis | PSE | Khan Yunis | 123175 | e o f t | PSE | 4076 |sa Hebron e | Hebron | 119401 | s (| Jabaliya n | 4077 | PSE | North Gaza | 113901 | n e a | Nablus c i h | 4078 l | PSE | Nablus | 100231 | K | 4079 | Rafah | PSE | Rafah | 92020 | +------+--------------+-------------+------------+------------+ 9 rows in set (0.00 sec)

8. In the t2 session, insert a new row to the City table. Confirm that the new row has been added. a. Enter the following in the t2 terminal window, and receive the results shown below: t2> INSERT INTO City (Name, CountryCode) VALUES ('New City', 'ATA'); Query OK, 1 row affected (0.00 sec)

− The insert completed and shows that it affected one row.

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 13

e

bl a r fe

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

b. Select the cities with ID > 4070: t2> SELECT * FROM City WHERE ID > 4070; +------+--------------+-------------+------------+------------+ | ID | Name | CountryCode | District | Population | +------+--------------+-------------+------------+------------+ | 4071 | Mount Darwin | ZWE | Harare | 164362 | | 4072 | Mutare | ZWE | Manicaland | 131367 | | 4073 | Gweru | ZWE | MIDlands | 128037 | | 4074 | Gaza | PSE | Gaza | 353632 | | 4075 | Khan Yunis | PSE | Khan Yunis | 123175 | | 4076 | Hebron | PSE | Hebron | 119401 | | 4077 | Jabaliya | PSE | North Gaza | 113901 | | 4078 | Nablus | PSE | Nablus | 100231 | | 4079 | Rafah | PSE | Rafah | 92020 | | 4080 | New City | ATA | | 0 | +------+--------------+-------------+------------+------------+ 10 rows in set (0.00 sec)

9. In the t1 session, select the city with ID > 4070 again.

e

bl a r fe

s

an r t n

a. Enter the following in the t1 terminal window, and receive the result shown below:

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a t is still not there. This occurs due to the b. Do you now see the row hrow? The e k ฺ s r REPEATABLE eREAD isolation e e to u level. f a 10. In the t2 session, commit transaction. Enter the following in the t2 terminal window, s thebelow: (sresult n n e and receive the shown ha COMMIT; lic K t2> er Query OK, 0 rows affected (0.01 sec) e f a t1> SELECT * FROM City WHERE ID > 4070; +------+--------------+-------------+------------+------------+ | ID | Name | CountryCode | District | Population | +------+--------------+-------------+------------+------------+ ... | 4079 | Rafah | PSE | Rafah | 92020 | +------+--------------+-------------+------------+------------+ 9 rows in set (0.00 sec)

S

11. In the t1 session, commit the transaction. Select the city with ID > 4070 again. Enter the following in the t1 terminal window, and receive the results shown below: t1> COMMIT; Query OK, 0 rows affected (0.01 sec) t1> SELECT * FROM City WHERE ID > 4070; +------+--------------+-------------+------------+------------+ | ID | Name | CountryCode | District | Population | +------+--------------+-------------+------------+------------+ ... | 4080 | New City | ATA | | 0 | +------+--------------+-------------+------------+------------+ 10 rows in set (0.00 sec)

− Note that the row that was inserted in the t2 session is now available to the t1 session due to the transactions being committed in each session.

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 14

12. Start a new transaction in the t1 mysql session. Enter the following in the t1 terminal window, and receive the result shown below:

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

t1> START TRANSACTION; Query OK, 0 rows affected (0.00 sec)

13. In the t1 session, remove the row that was inserted to the City table. Confirm the removal of the row. Enter the following in the t1 terminal window, and receive the results shown below: t1> DELETE FROM City WHERE ID = 4080; Query OK, 1 row affected (0.00 sec) t1> SELECT * FROM City WHERE ID > 4070; +------+--------------+-------------+------------+------------+ | ID | Name | CountryCode | District | Population | +------+--------------+-------------+------------+------------+ ... | 4079 | Rafah | PSE | Rafah | 92020 | +------+--------------+-------------+------------+------------+ 9 rows in set (0.00 sec)

s

an r t n

o

an s ha deฺ ) om Gui c ฺ en dent e t tu wa= 'READ-UNCOMMITTED'; t2> SET SESSION tx_isolation S @ s n (0.00 Query OK, 0 rows affected hi sec) a t h e rฺk o us e e t t2> SELECT af@@tx_isolation; e s s ( +-----------------------+ an licen |h@@global.tx_isolation K+-----------------------+|

e

bl a r fe

− The row has been removed. Isolation level change: 14. In the t2 session, change the isolation level to READ UNCOMMITTED by using the SET SESSION tx_isolation command, and confirm the change. Enter the following in the t1 terminal window, and receive the results shown below:

S

er e f a

| READ-UNCOMMITTED | +-----------------------+ 1 row in set (0.00 sec)

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 15

15. Start a new transaction in the t2 session. Select the city with ID > 4070. Enter the following in the t2 terminal window, and receive the results shown below:

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

t2> START TRANSACTION; Query OK, 0 rows affected (0.00 sec) t2> SELECT * FROM City WHERE ID > 4070; +------+--------------+-------------+------------+------------+ | ID | Name | CountryCode | District | Population | +------+--------------+-------------+------------+------------+ ... | 4079 | Rafah | PSE | Rafah | 92020 | +------+--------------+-------------+------------+------------+ 9 rows in set (0.00 sec)

a. What is the problem with this read? It is a dirty read. Due to the READ UNCOMMITTED isolation level, the SELECT result reflects the uncommitted transaction in the t1 session.

e

bl a r fe

s

an r t n

16. In the t1 session, cancel the transaction by using the ROLLBACK statement. Select the city with ID > 4070 again. Enter the following in the t1 terminal window, and receive the results shown below:

S

er e f a

no a s ฺ a t1> ROLLBACK; h ) de Query OK, 0 rows affected (0.01 sec) i m u o ฺc nt G n e t1> SELECT * FROM City WHERE ID 4070;de ate> S tu +------+--------------+-------------+------------+------------+ w @ s | ID | Name n| CountryCode hi | District | Population | a t +------+--------------+-------------+------------+------------+ h e rฺk o us ... e e f Citye t | ATA | 4080 | a New | | 0 | s s ( +------+--------------+-------------+------------+------------+ n inicset en(0.00 sec) arows 10 h l K

− The DELETE transaction was rolled back. Therefore, the row that was inserted earlier still exists. 17. In the t2 session, select the city with ID > 4070. Enter the following in the t2 terminal window, and receive the results shown below: t2> SELECT * FROM City WHERE ID > 4070; +------+--------------+-------------+------------+------------+ | ID | Name | CountryCode | District | Population | +------+--------------+-------------+------------+------------+ ... | 4080 | New City | ATA | | 0 | +------+--------------+-------------+------------+------------+ 10 rows in set (0.00 sec)

a. Are the results the same as in the same query to the t1 session in the previous step? Yes, the table contents remain as they were prior to the DELETE.

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 16

18. In the t2 session, cancel any transaction that was registered by this session. Enter the following in the t2 terminal window, and receive the results shown below:

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

t2> ROLLBACK; Query OK, 0 rows affected (0.01 sec)

19. In preparation for the next practice, exit the both mysql sessions, as well as both terminal windows: t1> EXIT Bye $ exit t2> EXIT Bye $ exit

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 17

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

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 8: Transactions and Locking Chapter 8 - Page 18

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

e

s

bl a r fe

an r t n

er e f a

no a s ฺ 9: a Practices for Lesson h ) de i m Storage Engines u o ฺc nt G n e e u9 de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 9: Storage Engines Chapter 9 - Page 1

Practices for Lesson 9: Overview

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

Practices Overview In these practices, you test your knowledge of InnoDB and other storage engines in MySQL. The hands-on practices are written for the Oracle Linux operating system environment, which is provided in Oracle classrooms. For non-Oracle classrooms, some adjustments may need to be made regarding file locations.

Assumptions •

The MySQL server installation has been completed prior to these practices.



You are logged in as oracle user in a terminal window.



You can access the mysql client from a command line prompt.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 9: Storage Engines Chapter 9 - Page 2

Practice 9-1: Quiz – InnoDB Storage Engine Overview

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

In this practice, you answer questions about the InnoDB storage engine.

Duration This practice should take approximately 6 minutes to complete.

Quiz Questions Choose the best answer from those provided for each multiple choice or True/False question. 1. How can the InnoDB storage engine be disabled? a. Only when compiling MySQL from source, by using the --without-innodb option. b. By starting the server with the --skip-innodb option.

s

2.

3.

4.

er e f a

S

5.

o

an r t n

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

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

Practices for Lesson 9: Storage Engines Chapter 9 - Page 3

e

bl a r fe

c. By issuing the statement SET GLOBAL have_innodb = 0. You need the SUPER privilege to do this. d. Storage engines cannot be disabled. In the default InnoDB configuration, the number of .ibd files is equal to the number of InnoDB tables. a. True b. False ________________ is possible because InnoDB does not acquire locks during a transaction until they are needed. a. Row-level locking b. Deadlock c. Phantom read d. All of the above. You can remove a data file from the system tablespace to decrease its size. a. True b. False InnoDB provides referential integrity by using the __________ and __________ keys to enforce table relationships. a. candidate and unique b. primary and unique c. primary and foreign d. unique and foreign

Solutions 9-1: Quiz – InnoDB Storage Engine Quiz Solutions

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

1. b. By starting the server with the --skip-innodb option.

2. 3. 4. 5.

Note: When you use the --skip-innodb option, the default-storage-engine option should be set to an engine other than InnoDB. InnoDB is the default engine starting from version 5.5. If no default-storage-engine is configured, the server does not start when the --skip-innodb option is used a. True c. Deadlock b. False c. primary and foreign

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 9: Storage Engines Chapter 9 - Page 4

Practice 9-2: Setting and Confirming InnoDB Settings Overview

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

In this practice, use a variety of methods to set and display InnoDB settings for the current MySQL session.

Duration This practice should take approximately 30 minutes to complete.

Tasks 1. Edit the [mysqld] section of the current configuration file (my.cnf, from the preceding practices) to set the InnoDB buffer pool to approximately 50% of your physical RAM and create one buffer pool instance per GB of RAM in the buffer pool. 2. Stop and restart the MySQL server to implement the config file changes. 3. Start the mysql client in a new terminal window, and use the SELECT statement to confirm the default storage engine for the current session. 4. Confirm that the INFORMATION_SCHEMA database contains tables related to InnoDB. 5. List the settings for all InnoDB-related variables. a. Is the multiple tablespace (file-per-table) setting ON or OFF? b. What is the auto-extend increment setting? c. What is the InnoDB data file path? d. Is there any purge lag? e. What is the buffer pool size? f. How many buffer pool instances are there? 6. Edit the existing config file (/etc/my.cnf) to change the auto-extend increment to 128 MB. 7. Confirm the changes made to the config file by listing the settings for all InnoDB-related variables again. Compare the results to the previous list. a. What is the auto-extend increment setting? 8. Create a new table called CityLanguage with the storage engine set to MEMORY.

s

an r t n

o

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

− This uses the method for creating a new table with a specific storage engine setting. a. Use the following CREATE TABLE statement to create the table with the columns; City, Country, CountryCode, Language: mysql> -> -> -> -> ->

CREATE TABLE CityLanguage ( City CHAR(35), Country CHAR(35), CountryCode CHAR(3), Language CHAR(30) ) ENGINE=MEMORY;

b. Confirm the storage engine setting. 9. Alter the new CityLanguage table such that it uses the InnoDB storage engine, and confirm that it has changed.

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

Practices for Lesson 9: Storage Engines Chapter 9 - Page 5

e

bl a r fe

Solutions 9-2: Setting and Confirming InnoDB Settings

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

Tasks 1. Edit the [mysqld] section of the current configuration file (my.cnf, from the preceding practices) to set the InnoDB buffer pool to approximately 50% of your physical RAM and create one buffer pool instance per GB of RAM in the buffer pool. a. To find the total physical memory, enter the following in a terminal window: $ su Password: oracle # head -1 /proc/meminfo MemTotal: 4059764 kB

The total memory shown in the preceding output is approximately 4 GB. If your server has 4 GB RAM, set the buffer pool size to 2 GB and the number of buffer pool instances to two in the following steps. Choose different values as appropriate. For example, if your server has 8 GB RAM, choose a buffer pool size of 4 GB, and four buffer pool instances. b. Open the my.cnf configuration file in gedit (or your preferred text editor).

s

an r t n

no a s ฺ a h ) de i m [mysqld] u o ฺc nt G innodb_buffer_pool_size=2GB n e innodb_buffer_pool_instances=2 ate Stude w ... @ his n a t h file. d. Save and close thekconfig e ฺ s r u to implement the config file changes. Enter the following e server 2. Stop and restart the MySQL e o f t a in a terminal ( window, s and sereceive the results shown below: n n e #hservice a c restart limysql K Shutting down MySQL...... [ OK ] r e e f Starting MySQL...... [ OK ] # gedit /etc/my.cnf

c. Add the following lines to the [mysqld] section. Choose values appropriate to your system as found in step 1a:

Sa 3.

Start the mysql client in a new terminal window, and use a SELECT statement to confirm the default storage engine for the current session. Enter the following in a terminal window, and receive the results shown below: $ mysql -uroot -poracle ... mysql> SELECT @@default_storage_engine; +--------------------------+ | @@default_storage_engine | +--------------------------+ | InnoDB | +--------------------------+ 1 row in set (0.00 sec)

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

Practices for Lesson 9: Storage Engines Chapter 9 - Page 6

e

bl a r fe

4. Confirm that the INFORMATION_SCHEMA database contains tables related to InnoDB. Enter the following in a terminal window, and receive the result shown below:

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

mysql> USE INFORMATION_SCHEMA ... Database changed

S

er e f a

mysql> SHOW TABLES LIKE 'INNODB%'; +----------------------------------------+ | Tables_in_information_schema (INNODB%) | +----------------------------------------+ | INNODB_LOCKS | | INNODB_TRX | | INNODB_SYS_DATAFILES | | INNODB_LOCK_WAITS | | INNODB_SYS_TABLESTATS | | INNODB_CMP | | INNODB_FT_BEING_DELETED | | INNODB_CMP_RESET | | INNODB_CMP_PER_INDEX | | INNODB_CMPMEM_RESET | | INNODB_FT_DELETED | | INNODB_BUFFER_PAGE_LRU | | INNODB_FT_INSERTED | | INNODB_CMPMEM | | INNODB_SYS_INDEXES | | INNODB_SYS_TABLES | | INNODB_SYS_FIELDS | | INNODB_CMP_PER_INDEX_RESET | | INNODB_BUFFER_PAGE | | INNODB_FT_DEFAULT_STOPWORD | | INNODB_FT_INDEX_TABLE | | INNODB_FT_INDEX_CACHE | | INNODB_SYS_TABLESPACES | | INNODB_METRICS | | INNODB_SYS_FOREIGN_COLS | | INNODB_FT_CONFIG | | INNODB_BUFFER_POOL_STATS | | INNODB_SYS_COLUMNS | | INNODB_SYS_FOREIGN | +----------------------------------------+ 29 rows in set (0.01 sec)

e

s

Practices for Lesson 9: Storage Engines Chapter 9 - Page 7

an r t n

o

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

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

bl a r fe

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

5. List the settings for all InnoDB-related variables. Enter the following in a terminal window, and receive the result shown below: mysql> SHOW VARIABLES LIKE '%innodb%'; +------------------------------------------+------------------------+ | Variable_name | Value | +------------------------------------------+------------------------+ | ignore_builtin_innodb | OFF | ... | innodb_api_trx_level | 0 | | innodb_autoextend_increment | 64 | | innodb_autoinc_lock_mode | 1 | | innodb_buffer_pool_dump_at_shutdown | OFF | | innodb_buffer_pool_dump_now | OFF | | innodb_buffer_pool_filename | ib_buffer_pool | | innodb_buffer_pool_instances | 2 | | innodb_buffer_pool_load_abort | OFF | | innodb_buffer_pool_load_at_startup | OFF | | innodb_buffer_pool_load_now | OFF | | innodb_buffer_pool_size | 2147483648 | | innodb_change_buffer_max_size | 25 | ... | innodb_concurrency_tickets | 5000 | | innodb_data_file_path | ibdata1:12M:autoextend | | innodb_data_home_dir | | ... | innodb_file_format_max | Antelope | | innodb_file_per_table | ON | | innodb_flush_log_at_timeout | 1 | ... | innodb_max_dirty_pages_pct_lwm | 0 | | innodb_max_purge_lag | 0 | | innodb_max_purge_lag_delay | 0 | ... | innodb_version | 1.2.10 | | innodb_write_io_threads | 4 | +------------------------------------------+------------------------+ 115 rows in set (0.01 sec)

s

an r t n

o

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

a. Is the multiple tablespace (file-per-table) setting ON or OFF? ON b. What is the auto-extend increment setting? 64 c. What is the InnoDB data file path? ibdata1:12M:autoextend d. Is there any purge lag? No; the values of innodb_max_purge_lag is 0. e. What is the buffer pool size? 2147483648 bytes in the preceding output. The answers to this and the following question depend on the values used in step 1c.

f.

How many buffer pool instances are there? Two in the preceding output.

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

Practices for Lesson 9: Storage Engines Chapter 9 - Page 8

e

bl a r fe

6. Edit the existing config file (/etc/my.cnf) to change the auto-extend increment to 128 MB. Note: You must launch the editor from your terminal logged in as root.

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

a. Edit the /etc/my.cnf file as follows: [mysqld] innodb_autoextend_increment=128 innodb_buffer_pool_size=2GB ...

b. Save and close the config file. c. Stop and restart the server to implement the change. Enter the following in a terminal window, and receive the results shown below: − Be sure to exit any mysql client you currently have running prior to stopping the server.

e

# service mysql restart Shutting down MySQL...... Starting MySQL......

[ OK ] [ OK ]

bl a r fe

ns a r t 7. Confirm the changes made to the config file by listing the settings for all InnoDB-related n o variables again. Compare the results to the previous list. Enter the following n in a terminal a window, and receive the result shown below: s ฺ a h $ mysql -uroot -poracle ) de i m u o ... ฺc nt G n e mysql> SHOW VARIABLES LIKE '%innodb%'; ate Stude +---------------------------------+------------------------+ w | Variable_name | Value | @ s i n h +---------------------------------+------------------------+ ha se t | OFF k | ignore_builtin_innodb | ฺ r u e | innodb_adaptive_flushing | ON | e o f t a ... e s ( ens | innodb_autoextend_increment | 128 | n a c i h l ... K+---------------------------------+------------------------+ r e afe a. What is the auto-extend increment setting? 128

S

8. Create a new table called CityLanguage with the storage engine set to MEMORY and confirm the setting. Enter the following at a mysql prompt, and receive the results shown below: a. Use the following CREATE TABLE statement to create the table with the columns; City, Country, CountryCode, Language: mysql> USE world_innodb; ... Database changed mysql> CREATE TABLE CityLanguage ( -> City CHAR(35), -> Country CHAR(35), -> CountryCode CHAR(3), -> Language CHAR(30) -> ) ENGINE=MEMORY; Query OK, 0 rows affected (0.11 sec)

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

Practices for Lesson 9: Storage Engines Chapter 9 - Page 9

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

b. Confirm the storage engine setting: mysql> SHOW CREATE TABLE CityLanguage\G *************************** 1. row ********************* Table: CityLanguage Create Table: CREATE TABLE `citylanguage` ( `City` char(35) DEFAULT NULL, `Country` char(35) DEFAULT NULL, `CountryCode` char(3) DEFAULT NULL, `Language` char(30) DEFAULT NULL ) ENGINE=MEMORY DEFAULT CHARSET=latin1 1 row in set (0.00 sec)

9. Alter the new CityLanguage table such that it uses the InnoDB storage engine, and confirm that it has changed. Enter the following at a mysql prompt, and receive the results shown below: mysql> ALTER TABLE CityLanguage ENGINE=InnoDB; Query OK, 0 rows affected (0.80 sec) Records: 0 Duplicates: 0 Warnings: 0

e

s

o

an r t n

mysql> SHOW CREATE TABLE CityLanguage\G *************************** 1. row *************************** Table: CityLanguage Create Table: CREATE TABLE `CityLanguage` ( `City` char(35) DEFAULT NULL, `Country` char(35) DEFAULT NULL, `CountryCode` char(3) DEFAULT NULL, `Language` char(30) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 1 row in set (0.00 sec)

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 9: Storage Engines Chapter 9 - Page 10

bl a r fe

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

e

s

bl a r fe

an r t n

er e f a

no a s ฺ 10: a Practices for Lesson h ) de i m Partitioning u o ฺc nt G n e e u10de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 10: Partitioning Chapter 10 - Page 1

Practices for Lesson 10: Overview

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

Practices Overview In these practices, you test your knowledge of table partitioning in MySQL. The hands-on practices are written for the Oracle Linux operating system environment, which is provided in Oracle classrooms. For non-Oracle classrooms, some adjustments may need to be made regarding file locations.

Assumptions •

The MySQL server installation has been completed prior to these practices.



You are logged in as the oracle user in a terminal window.



You can access the mysql client from a command line prompt.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 10: Partitioning Chapter 10 - Page 2

Practice 10-1: Quiz – MySQL Partitioning Overview

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

In this quiz, you answer questions about MySQL partitioning.

Duration This practice should take approximately 10 minutes to complete.

Quiz Questions Choose the best answer from those provided for each multiple choice or True/False question. 1. The primary reason for using partitioning is to improve database performance. a. True b. False 2. Assigning different rows of a table to different physical partitions is called _________________ ___________________. a. partitioning databases b. physical partitioning c. horizontal partitioning d. none of the above 3. The statement used to determine whether or not your current MySQL server supports partitioning is executed as follows:

s

an r t n

Sa

no a s ฺ a h ) de i m u o ฺc nt G n e SHOW ENGINES; ate Stude w @ his a. True n a h se t k b. False ฺ r u type when selecting partitions based on columns ee e topartition 4. You use the _______________ f a matching one(s of a set n ofsdiscrete values. n e a c a. hLIST li K r fee b. subpartition c. RANGE d. LINEAR

5. You use the COLUMNS partitioning variant (with the RANGE and LIST types) to enable the use of multiple columns. These columns are then taken into account for placing rows in partitions, and for determining which partitions are to be checked for matching rows in partition pruning. a. True b. False

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

Practices for Lesson 10: Partitioning Chapter 10 - Page 3

e

bl a r fe

6. You can subpartition tables that are partitioned by the following partition type(s), to further divide each partition. a. LIST and LINEAR

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

b. HASH and KEY c. RANGE only d. LIST and RANGE 7. Query the PARTITIONS table of the INFORMATION_SCHEMA database to list the partition names (with respective partitioning descriptions) for a specific table (using the WHERE clause). a. True b. False

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 10: Partitioning Chapter 10 - Page 4

Solutions 10-1: Quiz – MySQL Partitioning

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

Quiz Solutions 1. a. True 2. c. horizontal partitioning 3. b. False. The statement is as follows: SHOW PLUGINS; 4. a. LIST 5. a. True 6. d. LIST and RANGE. The subpartitions themselves can use HASH, LINEAR HASH, KEY, or LINEAR KEY partitioning. 7. a. True

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 10: Partitioning Chapter 10 - Page 5

e

bl a r fe

Practice 10-2: Creating and Modifying a Partitioned Table Overview

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

In this practice, you create a partitioned table and modify that table.

Duration This practice should take approximately 15 minutes to complete.

Tasks 1. Start a new mysql client session. Verify that the global variable innodb_file_per_table is turned on (this is the default since MySQL 5.6). 2. Create a new table called City_part that has the same column definitions as City, within the world_innodb database.

s

an r t n

no a − p1 (values less than 2000) s ฺ a h − p2 (values less than 3000) ) de i m u o − p3 (values less than maximum value) ฺc nt G n e 5. Now that you have modified the new table,te the detable partitioning status again. Does it a display u t w indicate partitioning? S @ s i n 6. Complete the copy of the City table into City_part, by inserting all the rows from the h a et h k ฺ original table. r o us ewindow, e f 7. In a separate terminal a se t check the MySQL data directory for the new table files (.par s ( and .ibd). n number of .ibd files, and their file names and sizes. nNote ithe eexact a c h l Note: K The individual .ibd partition files are created due to the info_file_per_table r e being set to ON. fe − p0 (values less than 1000)

Sa 8.

Confirm the City_part table partitions by using EXPLAIN PARTITIONS to show which partitions are used for a query of all table data. List the partitions in the result. 9. Determine which partitions would be used for a query of City_part table data, where the ID value is less than 2000. Does it use all the partitions? If not, which partitions are used for this level of query? 10. Redefine the City_part table to use KEY partitioning with three separate partitions. 11. Confirm the table partition modifications by using EXPLAIN PARTITIONS to show partitions used for a query of all table data. 12. Check the MySQL data directory for the modified table files. Note the exact number of .ibd files, and their file names and sizes. What is the difference between these files and the previously RANGE partitioned table files? 13. Query the PARTITIONS table from the INFORMATION_SCHEMA database, for the partition names in the City_part table. How many partitions are listed, and what are their names? Note: Keep the current City_part table intact for use in the next practice.

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

Practices for Lesson 10: Partitioning Chapter 10 - Page 6

e

bl a r fe

3. Use the SHOW TABLE STATUS statement to determine whether the new table is partitioned. 4. Modify the new table to add four RANGE type partitions (using the ID column) by using an ALTER TABLE statement:

Solutions 10-2: Creating and Modifying a Partitioned Table

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

Tasks 1. Start a new mysql client session. Verify that the global variable innodb_file_per_table is turned on (this is the default since MySQL 5.6). a. Enter the following in a terminal window, and receive the results shown below: $ mysql --login-path=admin ... mysql> SHOW VARIABLES LIKE 'innodb_file_per_table'; +-----------------------+-------+ | Variable_name | Value | +-----------------------+-------+ | innodb_file_per_table | ON | +-----------------------+-------+ 1 row in set (0.00 sec)

e

bl a r fe

s

an r t n

2. Create a new table called City_part that has the same column definitions as City, within the world_innodb database. Enter the following in a terminal window, and receive the results shown below:

Sa

no a s ฺ a mysql> USE world_innodb h ) de ... i m u o ฺc nt G Database changed n e e City; mysql> CREATE TABLE City_partatLIKE de u t w S Query OK, 0 rows affected (0.00 sec) @ s i n h t to determine whether the new table is partitioned. 3. Use the SHOW TABLE STATUS ha statement e k ฺ s r u and receive the result shown below: Enter the following in e a terminal window, e o f t a mysql> (SHOW s TABLE seSTATUS LIKE1.'City_part'\G n n *************************** e ha licName: City_part row *************************** K r Engine: InnoDB fee Version: 10 Row_format: Compact Rows: 0 Avg_row_length: 0 Data_length: 16384 Max_data_length: 0 Index_length: 16384 Data_free: 0 Auto_increment: 1 Create_time: 2012-10-15 18:00:02 Update_time: NULL Check_time: NULL Collation: latin1_swedish_ci Checksum: NULL Create_options: Comment: 1 row in set (0.00 sec)

− There is no indication of partitioning in this table.

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

Practices for Lesson 10: Partitioning Chapter 10 - Page 7

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

4. Modify the new table to add four RANGE type partitions (using the ID column) by using an ALTER TABLE statement. Enter the following in a terminal window, and receive the result shown below: mysql> ALTER TABLE City_part PARTITION BY RANGE (ID) ( -> PARTITION p0 VALUES LESS THAN (1000), -> PARTITION p1 VALUES LESS THAN (2000), -> PARTITION p2 VALUES LESS THAN (3000), -> PARTITION p3 VALUES LESS THAN MAXVALUE -> ); Query OK, 0 rows affected (4.34 sec) Records: 0 Duplicates: 0 Warnings: 0

5. Now that you have modified the new table, display the table partitioning status again. a. Enter the following in a terminal window, and receive the result shown below: mysql> SHOW TABLE STATUS LIKE 'City_part'\G *************************** 1. row *************************** Name: City_part Engine: InnoDB Version: 10 Row_format: Compact Rows: 4 Avg_row_length: 16384 Data_length: 65536 Max_data_length: 0 Index_length: 65536 Data_free: 25165824 Auto_increment: 1 Create_time: NULL Update_time: NULL Check_time: NULL Collation: latin1_swedish_ci Checksum: NULL Create_options: partitioned Comment: 1 row in set (0.00 sec)

s

an r t n

o

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

b. Does it indicate partitioning? Yes 6. Complete the copy of the City table into City_part, by inserting all the rows from the original table. Enter the following in a terminal window, and receive the result shown below: mysql> INSERT INTO City_part SELECT * FROM City; Query OK, 4079 rows affected, 1 warning (1.63 sec) Records: 4079 Duplicates: 0 Warnings: 1

The statement issues a warning due to the fact you are using statement-based logging while inserting records from another table into a table that uses an auto-increment column. This combination is not guaranteed to be safe for replication. Because you are not using the binary log for replication, you can safely ignore this warning in this lesson.

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

Practices for Lesson 10: Partitioning Chapter 10 - Page 8

e

bl a r fe

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

7. In a separate terminal window, check the MySQL data directory for the new table files (.par and .ibd). a. Enter the following in a separate terminal window, and receive the result shown below: $ su – Password: oracle # cd /var/lib/mysql/world_innodb; ls ... -rw-rw---- 1 mysql mysql 8710 Feb -rw-rw---- 1 mysql mysql 32 Feb -rw-rw---- 1 mysql mysql 212992 Feb -rw-rw---- 1 mysql mysql 212992 Feb -rw-rw---- 1 mysql mysql 212992 Feb -rw-rw---- 1 mysql mysql 212992 Feb ...

-l 6 6 6 6 6 6

04:55 04:55 04:57 04:57 04:57 04:57

City_part.frm City_part.par City_part#P#p0.ibd City_part#P#p1.ibd City_part#P#p2.ibd City_part#P#p3.ibd

b. Note the exact number of .ibd files, and their file names and sizes: − The .frm and .par files are very small.

e

bl a r fe

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e e ate *SFROM tudCity_part\G mysql> EXPLAIN PARTITIONS SELECT w s *************************** *************************** n@ 1.thirow id: 1 ha ฺk use r select_type: SIMPLE e fe City_part to table: a e s partitions: s ( enp0,p1,p2,p3 n type: ALL a c h li NULL Kpossible_keys:

− Your file sizes may vary from those shown above. The most important thing is to note which files exist and the difference in their sizes. 8. Confirm the City_part table partitions by using EXPLAIN PARTITIONS to show which partitions are used for a query of all table data. Enter the following in the mysql window, and receive the result shown below:

S

er e f a

key: NULL key_len: NULL ref: NULL rows: 4079 Extra: 1 row in set (0.00 sec)

− EXPLAIN returns an estimate of the number of examine rows used for the query, which can be very different than the actual number of rows. 9. Determine which partitions would be used for a query of City_part table data, where the ID value is less than 2000. a. Enter the following in a terminal window, and receive the result shown below: mysql> EXPLAIN PARTITIONS SELECT * FROM City_part WHERE ID < 2000\G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: City_part partitions: p0,p1 type: range possible_keys: PRIMARY key: PRIMARY Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Partitioning Chapter 10 - Page 9

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

key_len: 4 ref: NULL rows: 1996 Extra: Using where 1 row in set (0.00 sec)

b. Does it use all the partitions? No. Only p0 and p1 appear in the partitions column. 10. Redefine the City_part table to use KEY partitioning with three separate partitions. Enter the following in a terminal window, and receive the result shown below: mysql> ALTER TABLE City_part -> PARTITION BY KEY (ID) PARTITIONS 3; Query OK, 4079 rows affected (5.24 sec) Records: 4079 Duplicates: 0 Warnings: 0

11. Confirm the table partition modifications by using EXPLAIN PARTITIONS to show partitions used for a query of all table data. Enter the following in a terminal window, and receive the result shown below:

s

an r t n

mysql> EXPLAIN PARTITIONS SELECT * FROM City_part\G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: City_part partitions: p0,p1,p2 type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 2734 Extra: 1 row in set (0.00 sec)

Sa

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a h se t k ฺ r ee e to u f a (s ens n a MySQLlicdata directory for the modified table files. Note the exact number of .ibd 12. Checkhthe K r and their file names and sizes. files, fee a. Enter the following in a terminal window logged in as root, and receive the result shown below: # cd /var/lib/mysql/world_innodb; ls ... -rw-rw---- 1 mysql mysql 8710 Feb -rw-rw---- 1 mysql mysql 32 Feb -rw-rw---- 1 mysql mysql 245760 Feb -rw-rw---- 1 mysql mysql 278528 Feb -rw-rw---- 1 mysql mysql 245760 Feb ...

-l 6 6 6 6 6

05:06 05:06 05:06 05:06 05:06

City_part.frm City_part.par City_part#P#p0.ibd City_part#P#p1.ibd City_part#P#p2.ibd

b. What is the difference between these files and the previously RANGE partitioned table files? There are now three .ibd files, each containing approximately one-third of the table data. − Your file sizes may vary from those shown above. The most important thing is to note which files exist and the difference in their sizes.

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

Practices for Lesson 10: Partitioning Chapter 10 - Page 10

e

bl a r fe

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

13. Query the PARTITIONS table from the INFORMATION_SCHEMA database, for the partition names in the City_part table. Enter the following in a mysql window, and receive the result shown below: mysql> SELECT TABLE_NAME, -> GROUP_CONCAT(PARTITION_NAME) -> FROM INFORMATION_SCHEMA.PARTITIONS -> WHERE TABLE_SCHEMA='world_innodb' -> AND TABLE_NAME='City_part'; +------------+------------------------------+ | TABLE_NAME | GROUP_CONCAT(PARTITION_NAME) | +------------+------------------------------+ | City_part | p0,p1,p2 | +------------+------------------------------+ 1 row in set (0.00 sec)

Note: Keep the current City_part table intact for use in the next practice.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 10: Partitioning Chapter 10 - Page 11

Practice 10-3: Removing Partitions from a Table Overview

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

In this practice, you drop partitions from a partitioned table and remove all partitioning from a table.

Duration This practice should take approximately 10 minutes to complete.

Tasks 1. Using the mysql client from the previous practice, drop the first partition (p0) from the City_part table. Did this operation work? If not, why did it not work? 2. Return the current City_part table back to the first RANGE-partitioned configuration: − p1 (values less than 2000)

s

an r t n

− p2 (values less than 3000)

no a 3. s ฺ a h ) 4. de i m u o ฺc nt G n e 5. ate Stude w @ his n a h se t k 6. ฺ r ee e to u f a (s toethensoutput results from Practice 10-2, step 7. − Compare n hapartitioning lic of the City_part table and return it to its original, non-partitioned 7. Remove K r feestatus.

− p3 (values less than maximum value) Verify the file sizes for each of the new partitions. Attempt to drop the first partition (p0) from the City_part table again. Did this operation work? Why? Confirm the modifications made to City_part table partitions by using EXPLAIN PARTITIONS to show which partitions are now being used for a query of all table data. Which partitions are left? Check the MySQL data directory. Does the dropped partition file still exist? Are the sizes of the remaining.ibd files the same as they were before the partition was dropped?

Sa 8.

Now that you have modified City_part again, display the table partitioning status again. Does the output indicate that the table is partitioned? 9. Verify that the City_part table partitions are now gone, by using EXPLAIN PARTITIONS. 10. One last time, check the MySQL data directory. What City_part files are left? What are their names and sizes?

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

Practices for Lesson 10: Partitioning Chapter 10 - Page 12

e

bl a r fe

− p0 (values less than 1000)

Solutions 10-3: Removing Partitions from a Table

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

Tasks 1. Using the mysql client from the previous practice, drop the first partition (p0) from the City_part table. a. Enter the following in a terminal window, and receive the result shown below: mysql> ALTER TABLE City_part DROP PARTITION p0; ERROR 1512 (HY000): DROP PARTITION can only be used on RANGE/LIST partitions

b. Did this operation work? No, because this is a KEY partitioned table. 2. Return the current City_part table back to the first RANGE-partitioned configuration. Enter the following in a terminal window, and receive the result shown below: mysql> ALTER TABLE City_part PARTITION BY RANGE (id) ( -> PARTITION p0 VALUES LESS THAN (1000), -> PARTITION p1 VALUES LESS THAN (2000), -> PARTITION p2 VALUES LESS THAN (3000), -> PARTITION p3 VALUES LESS THAN MAXVALUE -> ); Query OK, 4079 rows affected (7.73 sec) Records: 4079 Duplicates: 0 Warnings: 0

Sa

e

bl a r fe

s

an r t n

no a s ฺ a h ) de i m u o c thetfollowing G in a terminal window ฺEnter 3. Verify the file sizes for each of the new partitions. n n e te below: logged in as root, and receive the resultashown de u t w S # cd /var/lib/mysql/world_innodb; ls -l @ s i n h ... a et hmysql k ฺ -rw-rw---- 1 mysql r us 8710 Feb 6 05:31 City_part.frm e e o f t -rw-rw---32 Feb 6 05:31 City_part.par a 1 mysql e mysql s s ( n -rw-rw---1 mysql mysql 327680 Feb 6 05:31 City_part#P#p0.ibd n ice a h l K-rw-rw---- 1 mysql mysql 311296 Feb 6 05:31 City_part#P#p1.ibd r e -rw-rw---- 1 mysql mysql 360448 Feb 6 05:31 City_part#P#p2.ibd fe -rw-rw---- 1 mysql mysql 311296 Feb ...

6 05:31 City_part#P#p3.ibd

4. Attempt to drop the first partition (p0) from the City_part table again. a. Enter the following in a terminal window, and receive the result shown below: mysql> ALTER TABLE City_part DROP PARTITION p0; Query OK, 0 rows affected (0.02 sec) Records: 0 Duplicates: 0 Warnings: 0

b. Did this operation work? Yes. RANGE partitioned tables allow DROP PARTITION.

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

Practices for Lesson 10: Partitioning Chapter 10 - Page 13

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

5. Confirm the modifications made to City_part table partitions by using EXPLAIN PARTITIONS to show which partitions are now being used for a query of all table data. Enter the following in a terminal window, and receive the result shown below: mysql> EXPLAIN PARTITIONS SELECT * FROM City_part\G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: City_part partitions: p1,p2,p3 type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 3081 Extra: NULL 1 row in set (0.00 sec)

Sa

e

bl a r e Which partitions are left? Having deleted partition p0 in the preceding step, partitions fp1, s n p2, and p3 are left. ra t n 6. Check the MySQL data directory. o n a a. Enter the following in a terminal window logged in as root, and receive the result s ฺ a shown below: h ) de i # cd /var/lib/mysql/world_innodb; ls -lom u ฺc nt G ... n e e City_part.frm -rw-rw---- 1 mysql mysql 8710 teFeb tu6 d05:21 a w S 6 05:21 City_part.par -rw-rw---- 1 mysql mysql 32 Feb @ s i n h -rw-rw---- 1 mysqlhmysql 311296 Feb 6 05:12 City_part#P#p1.ibd a et k ฺ -rw-rw---- 1 mysql Feb 6 05:12 City_part#P#p2.ibd us360448 er mysql o -rw-rw---- f1emysql mysql 311296 Feb 6 05:12 City_part#P#p3.ibd t a se s ... ( en partition file still exist? No an theldropped c i h b. Does K r e fe c. Are the sizes of the remaining.ibd files the same as they were before the partition was dropped? Yes, these three partitions are the same as they were when the table was first altered to be a RANGE table. However, the p0 partition and all its contents are now gone. − Your file sizes may vary from those shown above. The most important thing is to note which files exist and the difference in their sizes. 7. Remove partitioning of the City_part table and return it to its original, non-partitioned status. Enter the following in a terminal window, and receive the result shown below: mysql> ALTER TABLE City_part REMOVE PARTITIONING; Query OK, 3080 rows affected (0.12 sec) Records: 3080 Duplicates: 0 Warnings: 0

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

Practices for Lesson 10: Partitioning Chapter 10 - Page 14

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

8. Now that you have modified City_part again, display the table partitioning status again. Enter the following in a terminal window, and receive the result shown below: mysql> SHOW TABLE STATUS LIKE 'City_part'\G *************************** 1. row *************************** Name: City_part Engine: InnoDB Version: 10 Row_format: Compact Rows: 3081 Avg_row_length: 101 Data_length: 311296 Max_data_length: 0 Index_length: 98304 Data_free: 0 Auto_increment: 4081 Create_time: 2013-02-06 05:35:01 Update_time: NULL Check_time: NULL Collation: latin1_swedish_ci Checksum: NULL Create_options: Comment: 1 row in set (0.00 sec)

e

s

an r t n

Sa

bl a r fe

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @the table is is partitioned? No. The Create_options a. Does the output indicate that n h a t econtain the string “partitioned” to indicate that column is emptyrand ฺkhdoesunot s e partitioningfe is enabled.to a s setable partitions are now gone, by using EXPLAIN PARTITIONS. 9. Verify that the( City_part n n e afollowing Enter h the licin a terminal window, and receive the result shown below: K r EXPLAIN PARTITIONS SELECT * FROM City_part\G fee mysql> *************************** 1. row *************************** id: 1 select_type: SIMPLE table: City_part partitions: NULL type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 3081 Extra: 1 row in set (0.00 sec)

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

Practices for Lesson 10: Partitioning Chapter 10 - Page 15

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

10. One last time, check the MySQL data directory. What City_part files are left? What are their names and sizes? Enter the following in a terminal window, and receive the result shown below: # cd /var/lib/mysql/world_innodb; ls -l ... -rw-rw---- 1 mysql mysql 8710 Mar 23 19:12 City_part.frm -rw-rw---- 1 mysql mysql 475136 Mar 23 19:12 City_part.ibd ...

− Your file sizes may vary from those shown above. The most important thing is to note which files exist and the difference in their sizes.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 10: Partitioning Chapter 10 - Page 16

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

e

bl a r fe

s

an r t n

er e f a

no a s ฺ 11: User a Practices for Lesson h ) de i m Management u o ฺc nt G n e e u11de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 11: User Management Chapter 11 - Page 1

Practices for Lesson 11: Overview

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

Practices Overview In these practices, you test your knowledge of MySQL user management. The hands-on practices are written for the Oracle Linux operating system environment, which is provided in Oracle classrooms. For non-Oracle classrooms, some adjustments may need to be made regarding file locations.

Assumptions •

The MySQL server installation has been completed prior to these practices.



You are logged in as the oracle user in a terminal window.



You can access the mysql client from a command line prompt.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 11: User Management Chapter 11 - Page 2

Practice 11-1: Quiz – MySQL User Management Overview

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

In this quiz, you answer questions about MySQL user management.

Duration This practice should take approximately five minutes to complete.

Quiz Questions Choose the best answer from those provided for each multiple choice or True/False question. 1. To determine which accounts can be used without specifying a password, use the following statement: SELECT Host, User FROM mysql.user WHERE Password = '';

s

an r t n

Sa

no a s ฺ a mysql> SELECT Host, User, Select_priv FROM mysql.user h ) de i -> WHERE User = 'Sasha'; m u o +--------------+-------+-------------+ ฺc nt G n e | Host | User | Select_priv te tu| de a +--------------+-------+-------------+ w sS| | 62.220.12.66 | Sasha | N @ i n | 62.220.12.% | Sasha | Y th | a h e k | 62.220.% | Sasha | N | ฺ r o us e +--------------+-------+-------------+ e af se t s ( Note: The Select_priv column indicates that the SELECT privilege for the second entry ena global angranted c i h has been on scope (*.*). Assume that the Sasha accounts are not l K r granted privileges in any of the other grant tables. fee

Can user Sasha select data from any table on the MySQL server when connecting from the following hosts? a. 62.220.12.66 b. 62.220.12.43

c. 62.220.42.43 d. localhost 3. Which of the following user manipulation statements is true? a. To grant additional privileges to an existing user, you can use either an ALTER USER or a GRANT statement. b. To remove a user, you can use either a DROP USER or a REVOKE statement. c. To create a user, you can use either a CREATE USER statement or a GRANT statement.

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

Practices for Lesson 11: User Management Chapter 11 - Page 3

e

bl a r fe

a. True b. False 2. Consider the following privilege settings for the accounts associated with a given MySQL username, where the Select_priv column indicates the setting for the global SELECT privilege:

4. Assume that a new user has been created, but that user account has not been granted any privileges yet. What can that user do at this point? a. Connect to the server b. Issue statements like SELECT

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

c. Issue statements like SHOW DATABASES 5. Which of the following statements about the effects of privilege changes for existing connections are true? a. When a user is dropped, connections to the server by that user are terminated automatically. b. Global privilege changes do not affect existing connections of a user. They take effect only the next time the user attempts to connect. c. Database privilege changes take effect only at the time that a user next attempts to connect. d. Database privilege changes take effect only at the time that a user next issues a USE statement. e. Table and column privileges take immediate effect. 6. A server that has the privileges of the root operating system login account has more file system access than necessary and constitutes a security risk. a. True b. False 7. To disable TCP/IP connection, start the server with the ______________ option. a. --skip-tcp_ip b. --skip-networking

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e c. --tcp-ip_skip rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 11: User Management Chapter 11 - Page 4

e

bl a r fe

Solutions 11-1: Quiz – MySQL User Management Quiz Solutions

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

1. 2.

a. True Can user Sasha select data from any table on the MySQL server when connecting from the following hosts? a. No. 62.220.12.66 is the most specific entry that matches the host that user Sasha is trying to connect from. Because the SELECT privilege for that entry is N, Sasha cannot select from any table on the server. b. Yes. The most specific entry that matches 62.220.12.43 is 62.220.12.%. Because the SELECT privilege for that entry is Y, user Sasha can select from any table on the server. c. No. The most specific entry that matches 62.220.42.43 is 62.220.%. Because the SELECT privilege for that entry is N, user Sasha cannot select from any table on the server. d. No. There is no entry that would match Sasha@localhost. Therefore, user Sasha cannot even connect to the server from the localhost.

s

3.

o

4.

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu mysql> SHOW GRANTS FOR 'lennart'; @ n +-------------------------------------+ hi a t h | Grants for lennart@% | e ฺk us r +-------------------------------------+ e fe ON e*.*toTO 'lennart'@'%' | | GRANT USAGE a s ( ens +-------------------------------------+ n a h REVOKE lic usage ON *.* FROM 'lennart'; Kmysql>

c. To create a user, you can use either a CREATE USER statement or a GRANT statement. ALTER USER can only be used to expire a user’s password; if you want to grant additional privileges, you should use GRANT. You can remove a user completely with a DROP USER statement. Using REVOKE, you might be able to revoke all of the user’s privileges, but the user account remains, as this example illustrates:

er e f a

S

an r t n

mysql> SHOW GRANTS FOR 'lennart'; +-------------------------------------+ | Grants for lennart@% | +-------------------------------------+ | GRANT USAGE ON *.* TO 'lennart'@'%' | +-------------------------------------+ mysql> DROP USER 'lennart'; mysql> SHOW GRANTS FOR 'lennart'; ERROR 1141 (42000): There is no such grant defined for user 'lennart' on host '%'

a. Connect to the server. The user account can be used to connect to and look around on the server. Like any other user, that user gets the full output from statements that display information about the server, like SHOW VARIABLES or SHOW STATUS. The user cannot get information about database objects, because the account does not have any privileges on them. SHOW DATABASES displays only the INFORMATION_SCHEMA database (which is a database that does not have a physical representation in the file system).

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

Practices for Lesson 11: User Management Chapter 11 - Page 5

e

bl a r fe

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

5.

6. 7.

Which of the following statements about the effects of privilege changes for existing connections are true? a. False. When a user is dropped, connections to the server by that user are not terminated automatically. b. True. Global privilege changes do not affect existing connections of a user. They take effect only the next time the user attempts to connect. c. False. See the next item. d. True. Database privilege changes take effect only at the time that a user next issues a USE statement. e. True. Table and column privileges take immediate effect. a. True b. --skip-networking

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 11: User Management Chapter 11 - Page 6

Practice 11-2: Creating, Verifying, and Dropping a User Overview

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

In this practice, you create, verify, and drop an anonymous user.

Duration This practice should take approximately five minutes to complete.

Tasks 1. Verify that there are no anonymous accounts on the server by using a SELECT statement. 2. Create an anonymous account by using the CREATE USER statement on the local host. 3. Confirm that the anonymous account now exists by re-running the previous SELECT statement. 4. Delete the anonymous account by using the DROP USER statement. Confirm that the anonymous account no longer exists.

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 11: User Management Chapter 11 - Page 7

e

bl a r fe

Solutions 11-2: Creating, Verifying, and Dropping a User Tasks

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

1.

Verify that there are no anonymous accounts on the server by using a SELECT statement. Enter the following in a terminal window, and receive the result shown below: $ mysql --login-path=admin ... mysql> SELECT user, host, password FROM mysql.user -> WHERE user = ''; Empty set (0.00 sec)

2.

Create an anonymous account by using the CREATE USER statement on the local host. mysql> CREATE USER ''@'localhost'; Query OK, 0 rows affected (0.00 sec)

Sa

ns a r t -SELECT 3. Confirm that the anonymous account now exists by re-running the previous n o statement. an s Enter the following at a mysql prompt, and receive the result below: ฺ hashown e ) d i m mysql> SELECT user, host, password FROMo mysql.user u c G ฺ t -> WHERE user = ''; n e den e +------+-----------+----------+ t | user | host | password wa| s Stu @ +------+-----------+----------+ n h|i t | | localhosth|a e rฺk o us +------+-----------+----------+ e e t by using the DROP USER statement. af account e 4. Delete the anonymous s s ( en at a mysql prompt, and receive the result shown below: anthe following a. Enter c i h l Kmysql> DROP USER ''@'localhost'; r e fe Query OK, 0 rows affected (0.00 sec)

b.

Confirm that the anonymous account no longer exists: mysql> SELECT user, host, password FROM mysql.user -> WHERE user = ''; Empty set (0.00 sec)

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

Practices for Lesson 11: User Management Chapter 11 - Page 8

e

bl a r fe

Enter the following at a mysql prompt, and receive the result shown below:

Practice 11-3: Setting Up a User for the world_innodb Database

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

Overview In this practice, you create, drop, and verify a new user specifically for the world_innodb database.

Duration This practice should take approximately 10 minutes to complete.

Tasks 1. Create a new user called student at the host pc.example.com by using the mysql client session from the previous practice. 2. Confirm that the new user is now included in the mysql database by using a SELECT statement. 3. Assign the user student a password and privileges (SELECT, INSERT, DELETE, UPDATE) for the world_innodb database by using a GRANT statement. 4. Show the grants set for the user student on the pc.example.com host by using the SHOW GRANT statement. 5. Revoke the DELETE and UPDATE privileges currently given to student on the pc.example.com host. Confirm the updated grants now set for the user student on the pc.example.com host.

s

an r t n

Sa

no a s ฺ a h ) de i m u o ฺc nt G n e e pc.example.com de 6. Change the password for the student on host to NewPass by using atthe u t w S a GRANT statement. @ his n a 7. Grant ALL privileges to the hstudentseontthe pc.example.com host with password k ฺ r u connections per hour. Confirm the updated grants NewPass, and allow only e 10 maximum o festudent t a now set for thesuser on e the pc.example.com host. s ( n n student 8. Drop theauser ce at the host pc.example.com. Confirm that the account no longer i h l K exists. r e e f

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

Practices for Lesson 11: User Management Chapter 11 - Page 9

e

bl a r fe

Solutions 11-3: Setting Up a User for the world_innodb Database Tasks

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

1.

Create a new user called student at the host pc.example.com by using the mysql client session from the previous practice. Enter the following at a mysql prompt, and receive the result shown below: mysql> CREATE USER 'student'@'pc.example.com'; Query OK, 0 rows affected (0.00 sec)

2.

Confirm that the new user is now included in the mysql database by using a SELECT statement. Enter the following at a mysql prompt, and receive the result shown below: mysql> SELECT user, host, password -> FROM mysql.user WHERE user = 'student'; +---------+----------------+----------+ | user | host | password | +---------+----------------+----------+ | student | pc.example.com | | +---------+----------------+----------+ 1 row in set (0.00 sec)

Sa

e

bl a r fe

s

an r t n

no a s ฺ a h ) INSERT, 3. Assign the user student a password and privileges (SELECT, de DELETE, i m u o UPDATE) for the world_innodb database by using a GRANT statement. ฺc nt G n e Enter the following at a mysql prompt, and receive eresult shown below: te tuthe d a w DELETE, mysql> GRANT SELECT, INSERT, S UPDATE ON world_innodb.* @ s i n -> TO 'student'@'pc.example.com' a e th h k ฺ -> IDENTIFIED us (0.00 sec) er BYto'student_pass'; Query OK,a0fe rows affected sthee user student on the pc.example.com host by using the (s setefor n n 4. Show the grants a hGRANTS lic SHOW statement. K r feeEnter the following at a mysql prompt, and receive the result shown below: mysql> SHOW GRANTS FOR 'student'@'pc.example.com'\G *************************** 1. row *************************** Grants for [email protected]: GRANT USAGE ON *.* TO 'student'@'pc.example.com' IDENTIFIED BY PASSWORD '*832CA3798551FEA378AD34E02713320E28194DA2' *************************** 2. row *************************** Grants for [email protected]: GRANT SELECT, INSERT, UPDATE, DELETE ON `world_innodb`.* TO 'student'@'pc.example.com' 2 rows in set (0.00 sec)

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

Practices for Lesson 11: User Management Chapter 11 - Page 10

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

5.

Revoke the DELETE and UPDATE privileges currently given to the student user on the pc.example.com host. Confirm the updated grants now set for the user student on the pc.example.com host. Enter the following at a mysql prompt, and receive the results shown below: mysql> REVOKE DELETE, UPDATE ON world_innodb.* -> FROM 'student'@'pc.example.com'; Query OK, 0 rows affected (0.00 sec) mysql> SHOW GRANTS for 'student'@'pc.example.com'\G *************************** 1. row *************************** Grants for [email protected]: GRANT USAGE ON *.* TO 'student'@'pc.example.com' IDENTIFIED BY PASSWORD '*832CA3798551FEA378AD34E02713320E28194DA2' *************************** 2. row *************************** Grants for [email protected]: GRANT SELECT, INSERT ON `world_innodb`.* TO 'student'@'pc.example.com' 2 rows in set (0.00 sec)

s

an r t n

no a s ฺ a h ) de i m u o mysql> GRANT USAGE ON *.* TO 'student'@'pc.example.com' ฺc nt G -> IDENTIFIED BY 'NewPass'; en de atesec) u Query OK, 0 rows affected (0.00 t w S @ s i n 7. Grant ALL privileges to the student user on the pc.example.com host with password h a et h k NewPass, and allow only 10 maximum connections per hour. Confirm the updated grants ฺ s r oonuthe e e now set for the user student pc.example.com host. f t a e s ( eatna smysql prompt, and receive the results shown below: Enter then following a h GRANT lic ALL ON world_innodb.* TO 'student'@'pc.example.com' mysql> K r -> IDENTIFIED BY 'NewPass' fee 6.

Sa

e

bl a r fe

Change the password for the student user on the pc.example.com host to NewPass by using a GRANT statement. Enter the following at a mysql prompt, and receive the result shown below:

-> WITH MAX_CONNECTIONS_PER_HOUR 10; Query OK, 0 rows affected (0.00 sec)

mysql> SHOW GRANTS for 'student'@'pc.example.com'\G *************************** 1. row *************************** Grants for [email protected]: GRANT USAGE ON *.* TO 'student'@'pc.example.com' IDENTIFIED BY PASSWORD '*9EE65E227E34770F6F707EC991CFF926CB294BC7' WITH MAX_CONNECTIONS_PER_HOUR 10 *************************** 2. row *************************** Grants for [email protected]: GRANT ALL PRIVILEGES ON `world_innodb`.* TO 'student'@'pc.example.com'

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

Practices for Lesson 11: User Management Chapter 11 - Page 11

8.

Drop the user student at the host pc.example.com. Confirm that the account no longer exists. a. Enter the following at a mysql prompt, and receive the result shown below:

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

mysql> DROP USER 'student'@'pc.example.com'; Query OK, 0 rows affected (0.00 sec)

b.

Confirm that the account no longer exists: mysql> SELECT user, host, password FROM mysql.user -> WHERE user='student'; Empty set (0.00 sec)

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 11: User Management Chapter 11 - Page 12

Practice 11-4: Using the PAM Authentication Plugin Overview

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

In this practice, you enable the PAM authentication plugin and log in to MySQL using operating system credentials.

Duration This practice should take approximately 20 minutes to complete.

Tasks

1.

Note: This practice requires the use of multiple terminal windows for multiple mysql client sessions. Execute the following commands at a terminal window logged in as root to create the Linux user pamuser1 with the password oracle1. useradd pamuser1 passwd pamuser1

Sa

ns a r t n 2. Using a text editor, create a file in the /etc/pam.d/ directory called mysql-dba-course o containing the following text: an s #%PAM-1.0 ha deฺ ) auth include password-auth om Gui c ฺ account include password-auth en dent e t a and 3. Make the file /etc/shadow group-readable, tuset its group to mysql so the MySQL wPAM. S @ server process can authenticate using Use the following Linux commands: s i n h a t chmod 440 /etc/shadow kh use ฺ r e chgrp mysqlfe /etc/shadow to a e s ( ens 4. Install thenauthentication_pam plugin. a c hall pluginslito verify that the PAM authentication plugin is enabled. 5. Show K r f6.eeCreate a MySQL user called pamuser1 that can log in from the local host. Ensure that it is 7. 8.

e

bl a r fe

identified with PAM authentication, using the PAM service mysql-dba-course. Grant the SELECT privilege on the world_innodb.City table to the newly created pamuser1 user.

At a new terminal window, attempt to log in to MySQL as pamuser1, using the cleartext plugin and the password oracle1.

9. Execute a statement to display the value of the CURRENT_USER() function. 10. Exit the mysql prompt logged in as pamuser1. 11. Create a Linux user pamuser2 with the password oracle2, using the same technique as at the beginning of this practice. 12. Create a Linux group dba, and add the new pamuser2 user to that group by using the following commands at a root terminal prompt: groupadd dba usermod -G dba pamuser2

13. Create a mysql user called world_admin that can log in from the local host. Give it a cryptic password. Grant all privileges on the world_innodb database to the new user. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: User Management Chapter 11 - Page 13

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

14. Create a default proxy account with an empty user name and host name that is identified with PAM authentication, using the PAM service mysql-dba-course and the mapping dba=world_admin. 15. Grant the default proxy account the PROXY privilege on the world_admin@localhost account created previously. 16. At a new terminal window, attempt to log in to MySQL as pamuser2, using the cleartext plugin and the password oracle2. 17. Execute a statement to display the value of the CURRENT_USER() function. 18. Exit all mysql prompts.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 11: User Management Chapter 11 - Page 14

Solutions 11-4: Using the PAM Authentication Plugin

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

Tasks

1.

Note: This practice requires the use of multiple terminal windows for multiple mysql client sessions. Execute the following commands at a terminal window logged in as root to create the Linux user pamuser1 with the password oracle1. Enter the following at a terminal window, and receive the results shown below: $ su – Password: oracle # useradd pamuser1 # passwd pamuser1 Changing password for user pamuser1. New password: oracle1 BAD PASSWORD: it is based on a dictionary word Retype new password: oracle1 passwd: all authentication tokens updated successfully.

Sa

e

bl a r fe

s

an r t n

no a 2. Using a text editor, create a file in the /etc/pam.d/ directory called mysql-dba-course s a h containing the following text: eฺ ) d i m u #%PAM-1.0 o c G ฺ t n auth include password-auth e den e t account include tu wa spassword-auth S @ i in the preceding step, and add the Enter the following at the terminal n window hused a t h preceding contents to the file, before saving it as /etc/pam.d/mysql-dba-course: e ฺk us r e # gedit /etc/pam.d/mysql-dba-course fe e to a s ( texteeditor Note: Use any ns that you feel comfortable with, but ensure that you are running the n a c has root so li you can save the file to the correct location. editor K r f3.eeMake the file /etc/shadow group-readable, and set its group to mysql so the MySQL server process can authenticate using PAM. Enter the following at the terminal window used in the preceding step, and receive the results shown below: # chmod 440 /etc/shadow # chgrp mysql /etc/shadow

4.

Install the authentication_pam plugin. Enter the following at a mysql prompt and receive the results shown below: mysql> INSTALL PLUGIN authentication_pam -> SONAME 'authentication_pam.so'; Query OK, 0 rows affected (0.00 sec)

Note: To keep the plugin loaded across server restarts, load the plugin in an option file.

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

Practices for Lesson 11: User Management Chapter 11 - Page 15

5.

Show all plugins to verify that the PAM authentication plugin is enabled. Enter the following at a mysql prompt, and receive the results shown below: mysql> SHOW PLUGINS; +---------------------------+----------+--------------------+-----------------------+-------------+

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

| Name

| Status

| Type

| Library

| License

|

+---------------------------+----------+--------------------+-----------------------+-------------+ | binlog

| ACTIVE

| STORAGE ENGINE

| NULL

| PROPRIETARY |

| mysql_native_password

| ACTIVE

| AUTHENTICATION

| NULL

| PROPRIETARY | | PROPRIETARY |

... | daemon_memcached

| ACTIVE

| DAEMON

| libmemcached.so

| authentication_pam

| ACTIVE

| AUTHENTICATION

| authentication_pam.so | PROPRIETARY |

+---------------------------+----------+--------------------+-----------------------+-------------+ 45 rows in set (0.00 sec)

6.

Create a MySQL user called pamuser1 that can log in from the local host. Ensure that it is identified with PAM authentication, using the PAM service mysql-dba-course. Enter the following at a mysql prompt, and receive the results shown below:

s

mysql> CREATE USER pamuser1@localhost -> IDENTIFIED WITH authentication_pam AS 'mysql-dba-course'; Query OK, 0 rows affected (0.00 sec)

an r t n

Sa

o n a Note that you have not provided a password for this user to MySQL. note that you s Also a must add quotes around names that have special characters, but it is not required if the ฺ h ) delocalhost. i user or host does not have special characters, as with pamuseruand m o G to the newly created ฺc nttable 7. Grant the SELECT privilege on the world_innodb.City n e pamuser1 user. ate Stude w Enter the following at a mysql prompt, @ and isreceive the results shown below: n h a t mysql> GRANT SELECT TO pamuser1@localhost; e kh ON uworld_innodb.City ฺ s r e Query OK, 0fe rows affected to (0.00 sec) a e s ( window, 8. At a new n terminal ns attempt to log in to MySQL as pamuser1, using the cleartext e a c pluginhand the password oracle1. li K r feeEnter the following at a new terminal window, and receive the results shown below: $ mysql --enable-cleartext-plugin -upamuser1 -p Enter password: oracle1 Welcome to the MySQL monitor. Commands end with ; or \g. ...

9.

Execute a statement to display the value of the CURRENT_USER() function. Enter the following at the mysql prompt launched in the preceding step, and receive the results shown below: mysql> SELECT CURRENT_USER(); +--------------------+ | CURRENT_USER() | +--------------------+ | pamuser1@localhost | +--------------------+ 1 row in set (0.00 sec)

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

Practices for Lesson 11: User Management Chapter 11 - Page 16

e

bl a r fe

10. Exit the mysql prompt logged in as pamuser1. Enter the following at the mysql prompt used in the preceding step, and receive the results shown below:

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

mysql> EXIT Bye

11. Create a Linux user pamuser2 with the password oracle2, using the same technique as at the beginning of this practice. Enter the following at the root terminal window used earlier, and receive the results shown below: # useradd pamuser2 # passwd pamuser2 Changing password for user pamuser2. New password: oracle2 BAD PASSWORD: it is based on a dictionary word Retype new password: oracle2 passwd: all authentication tokens updated successfully.

e

bl a r fe

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e # groupadd dba te tude # usermod -G dba pamuser2 wa S @ s i n 13. Create a mysql user called world_admin that can log in from the local host. Give it a h a et h k cryptic password. Grant all privileges on the world_innodb database to the new user. ฺ r o us e e t prompt logged in as root, and receive the results shown Enter the following af at a smysql e s ( below: n n e a c i h l Kmysql> CREATE USER world_admin@localhost IDENTIFIED BY 'u=aX;yö#Qq'; r e Query OK, 0 rows affected (0.00 sec) fe

12. Create a Linux group dba, and add the new pamuser2 user to that group by using the following commands at a root terminal prompt: Enter the following at the root terminal window used in the preceding step, and receive the results shown below:

Sa

mysql> GRANT ALL PRIVILEGES ON world_innodb.* -> TO world_admin@localhost; Query OK, 0 rows affected (0.00 sec)

The account is not used directly, so use a password that is as cryptic as you can make it. 14. Create a default proxy account with an empty user name and host name that is identified with PAM authentication, using the PAM service mysql-dba-course and the mapping dba=world_admin. Enter the following at the mysql prompt, and receive the results shown below: mysql> CREATE USER ''@'' -> IDENTIFIED WITH authentication_pam -> AS 'mysql-dba-course, dba=world_admin'; Query OK, 0 rows affected (0.00 sec)

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

Practices for Lesson 11: User Management Chapter 11 - Page 17

15. Grant the default proxy account the PROXY privilege on the world_admin@localhost account created previously.

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

mysql> GRANT PROXY ON world_admin@localhost TO ''@''; Query OK, 0 rows affected (0.00 sec)

16. At a new terminal window, attempt to log in to MySQL as pamuser2, using the cleartext plugin and the password oracle2. Enter the following at a new terminal window, and receive the results shown below: $ mysql --enable-cleartext-plugin -upamuser2 -p Enter password: oracle2 Welcome to the MySQL monitor. Commands end with ; or \g. ...

17. Execute a statement to display the value of the CURRENT_USER() function.

mysql> SELECT CURRENT_USER(); +-----------------------+ | CURRENT_USER() | +-----------------------+ | world_admin@localhost | +-----------------------+ 1 row in set (0.00 sec)

Sa

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e e ate Sauthenticated tud Having logged in as pamuser2, you w have been using PAM with the Linux @ s i n password, and mapped to theaworld_admin th MySQL user using the default proxy account. h e k ฺ 18. Exit all mysql prompts. er to us e f a se s ( an licen h K r e fe

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

Practices for Lesson 11: User Management Chapter 11 - Page 18

e

bl a r fe

Enter the following at the mysql prompt launched in the preceding step, and receive the results shown below:

Practice 11-5: Additional Practice Overview

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

In this practice, you use the information covered in this lesson to implement user accounts and privileges by using the mysql client with the world_innodb database.

Duration This practice should take approximately 15 minutes to complete.

Tasks Note: This practice requires the use of multiple terminal windows for multiple mysql client sessions. 1. Log in to the mysql client with the root user account. Verify whether any anonymous accounts exist on the server. If there are any, remove them now. 2. Create a new user account called Stefan who can only connect locally, with a password of weak. Confirm that the new user is now included in the mysql database. 3. Give Stefan all privileges to the world_innodb database. Confirm the updated privileges. 4. Open a second terminal window, and log in to mysql as Stefan. Verify that the new account works. 5. The password for the Stefan account is weak. Set a new password of ‘new_pass’. Log out of this Stefan session 6. Using the mysql client session logged in as root, revoke all privileges on the City table previously granted to the Stefan account. 7. Allow Stefan to SELECT all columns in the City table. Log out of this root session. Confirm the updated privileges. 8. Using the second terminal window (opened earlier for the user Stefan), log in as Stefan again and verify that it still works as it should by executing a SELECT on each world_innodb table. Log out of this Stefan session. 9. From the previous root session window, create a new user called UserGroup4_01 who has the same privileges as Stefan, with a password of 0004nq2. Confirm that the new user exists. 10. Remove the new user UserGroup4_01. Confirm that the user no longer exists by attempting to show the grants for this user. 11. Start two separate queries in different terminal windows, and use a third to show the processes as they are running. Note: For this exercise to work properly, observe the order and timing of the following instructions exactly. Read over the entire set of instructions and execute the instructions in quick succession. a. From the previous root session window, change the prompt to t1 to distinguish it from the other two windows. Execute an initial SHOW PROCESSLIST statement that shows only the statement itself. b. Open a second terminal window. Launch the mysql client by using the newly created user, Stefan (username: Stefan, password: new_pass). Change this mysql session prompt to t2. Change the database to use the world_innodb database.

s

o

an r t n

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

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

Practices for Lesson 11: User Management Chapter 11 - Page 19

e

bl a r fe

Open a third terminal window. Launch the mysql client by using the admin login path. Change this mysql session prompt to t3. Change the database to use the world_innodb database. 12. Start the queries from the separate windows. a. In the t1 session, execute the following SELECT statement:

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

c.

t1> SELECT SLEEP(60); b.

In the t2 session, send the following SELECT statement: t2> SELECT * FROM City, Country, CountryLanguage -> LIMIT 10000000;

c. d.

In the t3 session, within a few seconds resend the SHOW PROCESSLIST statement and note the existence of the two new processes. In the t3 session, within several more seconds resend SHOW PROCESSLIST again (with the \G terminator for easy-to-read results) and note the difference in the Time column, indicating the number of seconds the processes have been running.

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 11: User Management Chapter 11 - Page 20

e

bl a r fe

Solutions 11-5: Additional Practice

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

Tasks

1.

Note: This practice requires the use of multiple terminal windows for multiple mysql client sessions. Log in to the mysql client with the root user account. Verify whether any anonymous accounts exist on the server. If there are any, remove them now. Enter the following at a terminal window, and receive the result shown below: $ mysql --login-path=admin ... mysql> SELECT user, host, password FROM mysql.user -> WHERE user=''; +------+------+----------+ | user | host | password | +------+------+----------+ | | | | +------+------+----------+ 1 row in set (0.00 sec) mysql> DROP USER ''@''; Query OK, 0 rows affected (0.00 sec)

e

bl a r fe

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e e connect locally, with a password of tewho can 2. Create a new user account called Stefan donly a u t w S weak. @ s i n h a prompt, t and receive the results shown below: a. Enter the following at ahmysql e k ฺ s r u mysql> CREATE eUSER 'Stefan'@'localhost' e o f t a -> (IDENTIFIED s nseBY 'weak'; n Query OK, ha li0cerows affected (0.00 sec) K eb.r Confirm that the new user is now included in the mysql database: e f a mysql> SELECT user, host, password FROM mysql.user

S

-> WHERE user = 'Stefan'; +--------+-----------+-------------------------------------------+ | user | host | password | +--------+-----------+-------------------------------------------+ | Stefan | localhost | *2924FCAB604BD710DD8B0B223B67ABEBF826D10D | +--------+-----------+-------------------------------------------+

3.

Give Stefan all privileges to the world_innodb database. a. Enter the following at a mysql prompt, and receive the results shown below: mysql> GRANT ALL ON world_innodb.* TO 'Stefan'@'localhost'; Query OK, 0 rows affected (0.00 sec)

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

Practices for Lesson 11: User Management Chapter 11 - Page 21

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

b.

Confirm the updated privileges: mysql> SHOW GRANTS FOR 'Stefan'@'localhost'\G *************************** 1. row *************************** Grants for Stefan@localhost: GRANT USAGE ON *.* TO 'Stefan'@'localhost' IDENTIFIED BY PASSWORD '*2924FCAB604BD710DD8B0B223B67ABEBF826D10D' *************************** 2. row *************************** Grants for Stefan@localhost: GRANT ALL PRIVILEGES ON `world_innodb`.* TO 'Stefan'@'localhost' 2 rows in set (0.00 sec)

4.

Open a second terminal window, and log in to mysql as Stefan. Enter the following at a mysql prompt, and receive the results shown below: $ mysql -uStefan –pweak Welcome to the MySQL monitor. ... mysql>

5.

Sa

e

Commands end with ; or \g.

bl a r fe

s

an r t n

The password for the Stefan account is weak. Set a new password of new_pass. Log out of this Stefan session.

o n a a. Enter the following at a mysql prompt, and receive the result shown below: s ฺ a h mysql> SET PASSWORD FOR 'Stefan'@'localhost' = PASSWORD('new_pass'); ) de i Query OK, 0 rows affected (0.00 sec) om u ฺc nt G n e mysql> EXIT ate Stude w Bye @ his n a t h works: b. Verify that the new password e k ฺ s r u e -pnew_pass $ mysql -uStefan e o f t a Welcome sto the MySQL ( ense monitor. Commands end with ; or \g. ... n ha EXIT lic mysql> K r Bye fee

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

Practices for Lesson 11: User Management Chapter 11 - Page 22

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

6.

Using the mysql client session logged in as root, revoke all privileges on the City table previously granted to the Stefan account. Note: You must have the privilege being granted, along with the GRANT OPTION privilege to grant or revoke privileges. That is why you use the root account. a. Enter the following at a terminal window and receive the results shown below: $ mysql -uroot -p Enter password: oracle ... mysql> REVOKE ALL ON world_innodb.* FROM 'Stefan'@'localhost'; Query OK, 0 rows affected (0.00 sec) mysql> GRANT ALL ON world_innodb.Country TO 'Stefan'@'localhost'; Query OK, 0 rows affected (0.00 sec) mysql> GRANT ALL ON world_innodb.CountryLanguage -> TO 'Stefan'@'localhost'; Query OK, 0 rows affected (0.00 sec)

Sa

s

an r t n

no a s ฺ a b. Confirm the updated privileges: h ) de i m mysql> SHOW GRANTS FOR 'Stefan'@'localhost'\G u o ฺc nt G n *************************** 1. row *************************** e te USAGE deON *.* TO Grants for Stefan@localhost: a GRANT u t w 'Stefan'@'localhost' IDENTIFIED BYS PASSWORD @ s i n '*B6408F4D32E8BEC631EF224B6F743F3340E6E744' h ha se 2.t row *************************** k ฺ *************************** r ee e to u GRANT ALL PRIVILEGES ON Grants for Stefan@localhost: f a `world_innodb`.`CountryLanguage` TO 'Stefan'@'localhost' (s ens n a c *************************** 3. row *************************** h li K r Grants for Stefan@localhost: GRANT ALL PRIVILEGES ON fee `world_innodb`.`Country` TO 'Stefan'@'localhost' 3 rows in set (0.00 sec)

The user has privileges for all the world_innodb tables, except for City. 7.

Allow Stefan to SELECT all columns in the City table. Log out of this root session. a. Enter the following at a mysql prompt, and receive the results shown below: mysql> GRANT SELECT (Name, Population) ON world_innodb.City -> TO 'Stefan'@'localhost'; Query OK, 0 rows affected (0.00 sec)

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

Practices for Lesson 11: User Management Chapter 11 - Page 23

e

bl a r fe

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

b.

Confirm the updated privileges: mysql> SHOW GRANTS FOR 'Stefan'@'localhost'\G *************************** 1. row *************************** Grants for Stefan@localhost: GRANT USAGE ON *.* TO 'Stefan'@'localhost' IDENTIFIED BY PASSWORD '*B6408F4D32E8BEC631EF224B6F743F3340E6E744' *************************** 2. row *************************** Grants for Stefan@localhost: GRANT ALL PRIVILEGES ON `world_innodb`.`CountryLanguage` TO 'Stefan'@'localhost' *************************** 3. row *************************** Grants for Stefan@localhost: GRANT SELECT (Population, Name) ON `world_innodb`.`City` TO 'Stefan'@'localhost' *************************** 4. row *************************** Grants for Stefan@localhost: GRANT ALL PRIVILEGES ON `world_innodb`.`Country` TO 'Stefan'@'localhost' 4 rows in set (0.00 sec)

s

an r t n

mysql> EXIT Bye

Sa

e

bl a r fe

no a s ฺ the Name and The user now has privileges for all the world_innodb tables, including a h ) Population columns of the City table. de i m u o GStefan), log in as Stefan ฺcfor thenuser 8. Using the second terminal window (opened earlier t n e again and verify that it still works as it should, ate byStexecuting ude a SELECT on each w world_innodb table. s receive the results shown below: iand n@prompt, h a a. Enter the following at ahmysql t ฺk-pnew_pass se r $ mysql -uStefan u e e MySQL fthe tomonitor. Commands end with ; or \g. Welcome sto a e ( ens n ... a h lic K r fee

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

Practices for Lesson 11: User Management Chapter 11 - Page 24

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

b.

Test the access to the Country table: mysql> USE world_innodb ... Database changed mysql> SELECT * from Country\G ... *************************** 239. row *************************** Code: ZWE Name: Zimbabwe Continent: Africa Region: Eastern Africa SurfaceArea: 390757.00 IndepYear: 1980 Population: 11669000 LifeExpectancy: 37.8 GNP: 5951.00 GNPOld: 8670.00 LocalName: Zimbabwe GovernmentForm: Republic HeadOfState: Robert G. Mugabe Capital: 4068 Code2: ZW 239 rows in set (0.00 sec)

s

an r t n

Sa

no a s ฺ a h ) de i m u o c. Test the access to the CountryLanguage table: ฺc nt G n e mysql> SELECT * from CountryLanguage; ate Stude ... w @ his n | ZMB | Bemba | F | a t h e | ZMB | ฺChewa | F | k s r e | ZMB | Lozi o u | F | e f | Nsenga t | ZMB sa | F | e s ( n | ZMB | Nyanja | F | an lice | Tongan |hZMB | F | K r | ZWE | English | T | e

29.7 | 5.7 | 6.4 | 4.3 | 7.8 | 11.0 | 2.2 | | ZWE | Ndebele | F | 16.2 | | ZWE | Nyanja | F | 2.2 | | ZWE | Shona | F | 72.1 | +-------------+---------------------------+------------+------------+ 984 rows in set (0.01 sec)

fe

d.

Test the access to the City table: mysql> SELECT * FROM City; ERROR 1143 (42000): SELECT command denied to user 'Stefan'@'localhost' for column 'ID' in table 'city' mysql> SELECT Name FROM City; ... | Nablus | | Rafah | | New City | +-----------------------------------+ 4079 rows in set (0.00 sec)

Note that you cannot select all columns (*) from City, given the privileges granted.

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

Practices for Lesson 11: User Management Chapter 11 - Page 25

e

bl a r fe

e.

Log out of this Stefan session: mysql> EXIT Bye

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

9.

From the previous root session window, create a new user called UserGroup4_01 who has the same privileges as Stefan, with a password of 0004nq2. a. Enter the following at the mysql prompt logged in as root, and receive the results shown below: mysql> CREATE USER 'UserGroup4_01'@'localhost' -> IDENTIFIED BY '0004nq2'; Query OK, 0 rows affected (0.00 sec) mysql> GRANT ALL ON world_innodb.Country -> TO 'UserGroup4_01'@'localhost'; Query OK, 0 rows affected (0.00 sec) mysql> GRANT ALL ON world_innodb.CountryLanguage -> TO 'UserGroup4_01'@'localhost'; Query OK, 0 rows affected (0.00 sec)

Sa

e

an r t n

no a s ฺ a h ) de i m mysql> GRANT SELECT ON world_innodb.City u o ฺc nt G -> TO 'UserGroup4_01'@'localhost'; n e de Query OK, 0 rows affected (0.00 atesec) u t w S @ b. Confirm that the new user n exists: s i h a 'UserGroup4_01'@'localhost'\G t hFOR mysql> SHOW GRANTS e k ฺ s r *************************** ee e to u 1. row *************************** f a s UserGroup4_01@localhost: Grants (for GRANT USAGE ON *.* TO s n n e 'UserGroup4_01'@'localhost' IDENTIFIED BY PASSWORD ha lic '*926ED64069CED09E0AAAED7677CAE9C44CF5C469' K r fee *************************** 2. row ***************************

Grants for UserGroup4_01@localhost: GRANT ALL PRIVILEGES ON `world_innodb`.`Country` TO 'UserGroup4_01'@'localhost' *************************** 3. row *************************** Grants for UserGroup4_01@localhost: GRANT SELECT ON `world_innodb`.`City` TO 'UserGroup4_01'@'localhost' *************************** 4. row *************************** Grants for UserGroup4_01@localhost: GRANT ALL PRIVILEGES ON `world_innodb`.`CountryLanguage` TO 'UserGroup4_01'@'localhost' 4 rows in set (0.00 sec)

10. Remove the new user UserGroup4_01. a.

Enter the following at a mysql prompt, and receive the results shown below: mysql> DROP USER 'UserGroup4_01'@'localhost'; Query OK, 0 rows affected (0.00 sec)

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

Practices for Lesson 11: User Management Chapter 11 - Page 26

s

bl a r fe

b.

Confirm that the user no longer exists by attempting to show the grants for this user:

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

mysql> SHOW GRANTS FOR 'UserGroup4_01'@'localhost'\G ERROR 1141 (42000): There is no such grant defined for user 'UserGroup4_01' on host 'localhost'

11. Start two separate queries in different terminal windows, and use a third to show the processes as they are running. Note: The order and timing of the instructions below must be followed exactly for this exercise to work properly. Read over the entire set of instructions and execute the instructions in quick succession. a. From the previous root session window, change the prompt to t1 to distinguish it from the other two windows. Execute an initial SHOW PROCESSLIST statement that shows only the statement itself. mysql> PROMPT t1> ; PROMPT set to 't1> ' t1> SHOW PROCESSLIST;

e

bl a r fe

s

an r t n

+----+------+-----------+------+---------+------+-------+------------------+ | Id | User | Host | db | Command | Time | State | Info | +----+------+-----------+------+---------+------+-------+------------------+ | 4 | root | localhost | NULL | Query | 0 | init | SHOW PROCESSLIST | +----+------+-----------+------+---------+------+-------+------------------+ 1 row in set (0.00 sec)

Sa

no a s ฺ a h ) de i m u o Gby using the newly created ฺcmysqlnclient t n b. Open a second terminal window. Launchethe te tunew_pass). de user, Stefan (username: Stefan,apassword: Change this mysql w S session prompt to t2. Change @the database is to use the world_innodb database. n h a t h se $ mysql -uStefan k -pnew_pass ฺ r e ... e e to u f a mysql> (PROMPT s nt2> s; n e PROMPT ha USEset licto 't2> ' K t2> world_innodb; er

fe

... Database changed

c.

Open a third terminal window. Launch the mysql client by using the admin login path. Change this mysql session prompt to t3. Change the database to use the world_innodb database. Enter the following, and receive the results shown below: $ mysql --login-path=admin ... mysql> PROMPT t3> ; PROMPT set to 't3> ' t3> USE test; ... Database changed

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

Practices for Lesson 11: User Management Chapter 11 - Page 27

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

12. Start the queries from the separate windows. Enter the following, and receive the results shown below: a. In the t1 session, execute a SELECT SLEEP(60); statement: t1> SELECT SLEEP(60); (pauses while processing for one minute) +-----------+ | SLEEP(60) | +-----------+ | 0 | +-----------+ 1 row in set (1 min 0.08 sec)

b.

In the t2 session, execute the following statement: t2> SELECT Code FROM City, Country, CountryLanguage -> LIMIT 10000000;

e

bl a r fe

(The output pauses while processing for approximately 40 seconds) ... 10000000 rows in set (41.91 sec)

ns a r t - statement c. In the t3 session, within a few seconds resend the SHOW PROCESSLIST n o and note the existence of the two new processes: an s t3> SHOW PROCESSLIST; ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af isstruncated e t to fit the page. Note that the Time column value depends s ( The preceding outputn an you lexecute uponh when ice this statement. K r fee +----+--------+-----------+--------------+---------+------+--------------+---------------+ | Id | User

| Host

| db

| Command | Time | State

| Info

|

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

| Query

|

4 | User sleep

| 10 | Stefan | localhost | world_innodb | Query

4 | root

| localhost | NULL

|

2 | Sending data | SELECT Code F…|

| 12 | root

|

0 | init

| localhost | test

| Query

| SELECT SLEEP… | | SHOW PROCESSL…|

+----+--------+-----------+--------------+---------+------+--------------+---------------+ 3 rows in set (0.00 sec)

Sa

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

Practices for Lesson 11: User Management Chapter 11 - Page 28

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

d.

In the t3 session, within several more seconds resend SHOW PROCESSLIST again (with the \G terminator for easy-to-read results) and note the difference in the Time column, indicating the number of seconds the processes have been running: t3> SHOW PROCESSLIST\G *************************** 1. row *************************** Id: 8 User: root Host: localhost db: NULL Command: Query Time: 22 State: User sleep Info: SELECT SLEEP(60) *************************** 2. row *************************** Id: 10 User: Stefan Host: localhost db: world_innodb Command: Sleep Time: 20 State: Info: NULL *************************** 3. row *************************** Id: 12 User: root Host: localhost db: test Command: Query Time: 0 State: init Info: SHOW PROCESSLIST 3 rows in set (0.00 sec)

e

bl a r fe

s

an r t n

o

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

You can now exit each of the terminal mysql clients and close the windows. Do not remove the Stefan user account, because you use it in a later practice.

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

Practices for Lesson 11: User Management Chapter 11 - Page 29

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

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 11: User Management Chapter 11 - Page 30

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

e

s

bl a r fe

an r t n

er e f a

no a s ฺ 12: a Practices for Lesson h ) de i m Security u o ฺc nt G n e e u12de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 12: Security Chapter 12 - Page 1

Practices for Lesson 12: Overview

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

Practices Overview In these practices, you test your knowledge of MySQL security. The hands-on practices are written for the Oracle Linux operating system environment, which is provided in Oracle classrooms. For non-Oracle classrooms, some adjustments may need to be made regarding file locations.

Assumptions •

The MySQL server installation has been completed prior to these practices.



You are logged in as root user in a terminal window.



You can access the mysql client from a command line prompt.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 12: Security Chapter 12 - Page 2

Practice 12-1: Quiz – MySQL Security Overview

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

In this quiz, you answer questions about MySQL security.

Duration This practice should take approximately eight minutes to complete.

Quiz Questions Choose the best answer from those provided for each multiple choice or True/False question. 1. A root account has full privileges to perform any database operation, so you should not give it access to the user table in the mysql database. a. True b. False 2. The following are the types of MySQL server and data security risks. a. Eavesdropping b. Altering c. Playback d. Denial of service e. All of the above 3. MySQL uses security based on ____________________ for all connections, queries, and other operations. a. atomic control lines b. access control lists c. data access security 4. The most common MySQL installation security risks fall in the following categories: a. networks, operating systems, and file systems b. networks, secure connections, and users c. users and data 5. Protect your data from unauthorized access by using single quotation marks around numeric and string values. a. True b. False 6. Unencrypted connections are acceptable for moving data securely over a network, as long as users have passwords. a. True b. False 7. MySQL supports _____________________ connections between MySQL clients and the server for encryption of data. a. SSL-only b. SSL and SSH c. --compress

s

o

an r t n

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

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

Practices for Lesson 12: Security Chapter 12 - Page 3

e

bl a r fe

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

8. All MySQL installations support SSL connections. a. True b. False

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 12: Security Chapter 12 - Page 4

Solutions 12-1: Quiz – MySQL Security

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

Quiz Solutions 1. b. False. Do not ever give anyone (except MySQL root accounts) access to the user table in the mysql database! 2. e. All of the above 3. b. access control lists 4. a. networks, operating systems, and file systems 5. a. True 6. b. False. If you use unencrypted connections between the client and the server, a user with access to the network can watch all the traffic and look at (and modify) the data being sent or received. 7. b. SSL (secure socket layer) and SSH (secure shell, specifically for Windows OS) protocols 8. b. False. To use SSL connections, your system must support OpenSSL or yaSSL (which comes bundled with MySQL standard installation), but not all forms of the MySQL binaries include the necessary setup.

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 12: Security Chapter 12 - Page 5

e

bl a r fe

Practice 12-2: Determining the Status of SSL Connectivity Overview

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

In this practice, you use specific SQL statements to determine whether the MySQL server supports SSL connections.

Duration This practice should take approximately seven minutes to complete.

Tasks 1. Within the mysql client, check whether a running mysqld server supports SSL; do this by displaying the value of the have_ssl system variable. 2. Check whether the current server connection uses SSL; do this by examining the value of the Ssl_cipher status variable. Then shut down the mysql client.

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 12: Security Chapter 12 - Page 6

e

bl a r fe

Solutions 12-2: Determining the Status of SSL Connectivity

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

Tasks 1. Within the mysql client, check whether your MySQL server supports SSL; do this by displaying the value of the have_ssl system variable. Enter the following in a terminal window, and receive the result shown below: $ mysql --login-path=admin Welcome to the MySQL monitor. ...

Commands end with ; or \g.

mysql> SHOW VARIABLES LIKE 'have_ssl'; +---------------+----------+ | Variable_name | Value | +---------------+----------+ | have_ssl | DISABLED | +---------------+----------+

e

s

bl a r fe

an r t n

− The result shows that the SSL feature is compiled in but not currently enabled. 2. Check whether your current server connection uses SSL; do this by examining the value of the Ssl_cipher status variable. Then shut down the mysql client. Enter the following in a terminal window (from the mysql client), and receive the result shown below:

o

er e f a

an s ha deฺ ) mysql> SHOW STATUS LIKE 'Ssl_cipher'; om Gui c +---------------+-------+ ฺ en dent | Variable_name | Value | e t a Stu +---------------+-------+ | Ssl_cipher | | w @ is n h +---------------+-------+ a t kh use ฺ r e mysql> EXITfe to a Bye e s ( ens n − a The resulticshows that no SSL connection cipher is assigned. l Kh

S

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

Practices for Lesson 12: Security Chapter 12 - Page 7

Practice 12-3: Additional Practice – Enabling MySQL Support for SSL Connections

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

Overview In this practice, set the appropriate variables to permit the MySQL server and client to use an SSL connection.

Duration This practice should take approximately 10 minutes to complete.

Tasks 1. Create the OpenSSL files needed to enable SSL connections by following the steps in the solution. Name the new folder newcerts and place it in the current /etc/ directory. 2. Confirm the creation of the eight SSL files required for SSL connection: − ca-cert.pem − client-cert.pem

e

bl a r fe

s

an r t n

no a − server-key.pem s ฺ a h ) − ca-key.pem de i m u o − client-key.pem ฺc nt G n e − server-cert.pem ate Stude w − server-req.pem @ his n a t practices for the “User Management” lesson) to h (created 3. Use the Stefan user account in e k ฺ s r u From the root account, grant privileges to the ethe mysql set up the SSL within client. e o f t a Stefan account user table of the mysql database, and require SSLse onthethesame (s foreSELECT n n encrypted connections, within GRANT statement. a ic h l K 4. Restart r the server with the option to enable the SSL certificate authority, server certificate, e e and server key. f − client-req.pem

Sa 5.

Attempt a standard login to the mysql client as Stefan. What is the result?

6. Log in to the Stefan account, adding the option to enable the SSL connection. 7. List the current value of the have_ssl and Ssl_ciper variables. Does this confirm the SSL connection status? 8. Exit the mysql session. 9. In preparation for the next practice, stop and restart the server without the SSL connection options.

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

Practices for Lesson 12: Security Chapter 12 - Page 8

Solutions 12-3: Additional Practice – Enabling MySQL Support for SSL Connections

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

Tasks 1. Create the OpenSSL files needed to enable SSL connections by following the steps in the solution. Name the new folder newcerts and place it in the current /etc/ directory. Enter the following in a terminal window, and receive the results shown below: $ su Password: oracle # cd /etc # mkdir newcerts # cd newcerts # openssl genrsa 2048 > ca-key.pem Generating RSA private key, 2048 bit long modulus ...........................+++ ...........+++ e is 65537 (0x10001) # openssl req -new -x509 -nodes -days 1000 \ -key ca-key.pem > ca-cert.pem You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----Country Name (2 letter code) [XX]: US State or Province Name (full name) []: Texas Locality Name (eg, city) [Default City]: Dallas Organization Name (eg, company) [Default Company Ltd]: Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server's hostname) []: Email Address []: # openssl req -newkey rsa:2048 -days 1000 -nodes \ -keyout server-key.pem > server-req.pem Generating a 2048 bit RSA private key .............+++ ..+++ writing new private key to 'server-key.pem' ----You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----Country Name (2 letter code) [XX]: State or Province Name (full name) []: Locality Name (eg, city) [Default City]: Organization Name (eg, company) [Default Company Ltd]:

s

o

an r t n

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

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

Practices for Lesson 12: Security Chapter 12 - Page 9

e

bl a r fe

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

Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server's hostname) []: Email Address []: Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []: # openssl x509 -req -in server-req.pem -days 1000 -CA ca-cert.pem \ -CAkey ca-key.pem -set_serial 01 > server-cert.pem Signature ok subject=/C=XX/L=Default City/O=Default Company Ltd Getting CA Private Key # openssl req -newkey rsa:2048 -days 1000 -nodes \ -keyout client-key.pem > client-req.pem Generating a 2048 bit RSA private key ...................................................................... ......................................+++ ...................................................................... .................................................+++ writing new private key to 'client-key.pem' ----You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----Country Name (2 letter code) [XX]: State or Province Name (full name) []: Locality Name (eg, city) [Default City]: Organization Name (eg, company) [Default Company Ltd]: Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server's hostname) []: Email Address []: Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []: # openssl x509 -req -in client-req.pem -days 1000 -CA ca-cert.pem \ -CAkey ca-key.pem -set_serial 01 > client-cert.pem Signature ok subject=/C=XX/L=Default City/O=Default Company Ltd Getting CA Private Key

s

an r t n

o

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

2. Confirm the creation of the eight SSL files required for SSL connection. Enter the following in a terminal window (at the same shell prompt as the previous step), and receive the result shown below: # ls ca-cert.pem ca-key.pem

client-cert.pem client-key.pem

client-req.pem server-cert.pem

server-key.pem server-req.pem

3. Use the Stefan user account (created in practices for the “User Management” lesson) to set up SSL within the mysql client. From the root account, grant privileges to the Stefan Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Security Chapter 12 - Page 10

e

bl a r fe

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

account for SELECT on the user table of the mysql database, and require SSL-encrypted connections, within the same GRANT statement. Confirm the privileges. Enter the following in a terminal window (at the mysql client prompt), and receive the result shown below: $ mysql --login-path=admin Welcome to the MySQL monitor. ...

Commands end with ; or \g.

mysql> GRANT SELECT ON mysql.user TO 'Stefan'@'localhost' > IDENTIFIED BY 'new_pass' REQUIRE SSL; Query OK, 0 rows affected (0.00 sec) mysql> SHOW GRANTS FOR 'Stefan'@'localhost'\G *************************** 1. row *************************** Grants for Stefan@localhost: GRANT USAGE ON *.* TO 'Stefan'@'localhost' IDENTIFIED BY PASSWORD '*B6408F4D32E8BEC631EF224B6F743F3340E6E744' REQUIRE SSL *************************** 2. row *************************** Grants for Stefan@localhost: GRANT SELECT ON `mysql`.`user` TO 'Stefan'@'localhost' *************************** 3. row *************************** Grants for Stefan@localhost: GRANT ALL PRIVILEGES ON `world_innodb`.`Country` TO 'Stefan'@'localhost' *************************** 4. row *************************** Grants for Stefan@localhost: GRANT ALL PRIVILEGES ON `world_innodb`.`CountryLanguage` TO 'Stefan'@'localhost' *************************** 5. row *************************** Grants for Stefan@localhost: GRANT SELECT (Population, Name) ON `world_innodb`.`City` TO 'Stefan'@'localhost' 5 rows in set (0.00 sec)

e

bl a r fe

s

an r t n

S

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a h se t k ฺ r ee e to u f a s ns (EXIT mysql> n a ce i h l K 4. Restart the server with the option to enable the SSL certificate authority, server certificate, r server e e and key. Enter the following in a terminal window (at a Linux terminal prompt logged af in as root), and receive the results shown below:

# service mysql restart --ssl-ca=/etc/newcerts/ca-cert.pem \ --ssl-cert=/etc/newcerts/server-cert.pem \ --ssl-key=/etc/newcerts/server-key.pem Shutting down MySQL.. [ Starting MySQL... [

OK OK

] ]

5. Attempt a standard login to the mysql client as Stefan. What is the result? $ mysql -uStefan -pnew_pass ERROR 1045 (28000): Access denied for user 'Stefan'@'localhost' (using password: YES)

− You get an error for this user because it is now an SSL-required account, which requires an SSL option to log in to the account. 6. Log in to the Stefan account, adding the option to enable the SSL connection. $ mysql -uStefan -pnew_pass --ssl-ca=/etc/newcerts/ca-cert.pem Welcome to the MySQL monitor. Commands end with ; or \g. ... Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Security Chapter 12 - Page 11

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

7. List the current value of the have_ssl and Ssl_ciper variables. Does this confirm the SSL connection status? mysql> SHOW VARIABLES LIKE 'have_ssl'; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | have_ssl | YES | +---------------+-------+ 1 row in set (0.01 sec) mysql> SHOW STATUS LIKE 'Ssl_cipher'; +---------------+--------------------+ | Variable_name | Value | +---------------+--------------------+ | Ssl_cipher | DHE-RSA-AES256-SHA | +---------------+--------------------+ 1 row in set (0.00 sec)

s

8. Exit the mysql session.

an r t n

mysql> EXIT Bye

Sa

e

bl a r fe

no a s the 9. In preparation for the next practice, stop and restart the servera without SSL connection ฺ h e ) options. Enter the following from a terminal logged in as root. om Guid c # service mysql restart ฺ en dent Shutting down MySQL... [ OK ] e t a Starting MySQL. [ OK ] u t w sS @ n hi a t h e rฺk o us e e af se t s ( an licen h K r e fe

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

Practices for Lesson 12: Security Chapter 12 - Page 12

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

e

s

bl a r fe

an r t n

er e f a

no a s ฺ 13: a Practices for Lesson h m) uide Tableco Maintenance G ฺ t n n e e u13de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 13: Table Maintenance Chapter 13 - Page 1

Practices for Lesson 13: Overview

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

Practices Overview In these practices, you test your knowledge of table maintenance. The hands-on practices are written for the Oracle Linux operating system environment, which is provided in Oracle classrooms. For non-Oracle classrooms, some adjustments may need to be made regarding file locations.

Assumptions •

The MySQL server installation has been completed prior to these practices.



You are logged in as oracle user in a terminal window.



You can access the mysql client from a command line prompt.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 13: Table Maintenance Chapter 13 - Page 2

Practice 13-1: Quiz – Table Maintenance Overview

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

In this quiz, you answer questions about table maintenance.

Duration This practice should take approximately five minutes to complete.

Quiz Questions Choose the best answer from those provided for each multiple choice or True/False question. 1. The myisamchk and mysqlcheck command line client utilities can both be used to check InnoDB tables. a. True b. False 2. myisamchk and mysqlcheck both access tables directly, rather than communicating with the MySQL server. a. True b. False 3. It is recommended that you run mysqlcheck with _____________ option first. Then run again if repairs are needed. a. --force b. no c. --scan --quick 4. Which of the following maintenance operations can be performed on InnoDB tables? a. ANALYZE TABLE b. CHECK TABLE c. CHECKSUM TABLE d. REPAIR TABLE

s

an r t n

o

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

e. OPTIMIZE TABLE f. All of the above 5. When you optimize a table, the unused space is reclaimed when rows are deleted from the table. To optimize a table, you can use the OPTIMIZE TABLE statement or the _____________ utility with the _____________ option. a. mysqlcheck --optimize b. myisamchk --optimize

c. mysqlcheck --reclaim d. None of the above 6. Prior to performing a myisamchk on a MyISAM table, you should lock the tables or stop the server to ensure that the server does not access the tables while they are being worked on. a. True b. False

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

Practices for Lesson 13: Table Maintenance Chapter 13 - Page 3

e

bl a r fe

7. To repair an InnoDB table after a crash from which InnoDB cannot automatically recover, restart the server by using the _____________ option. a. --recover

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

b. -recover -f c. --innodb_force_recovery

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 13: Table Maintenance Chapter 13 - Page 4

Solutions 13-1: Quiz – Table Maintenance Quiz Solutions

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

1. b. False. Of these two utilities, only mysqlcheck can be used to check InnoDB tables. 2. b. False. mysqlcheck does not connect directly to the tables, but communicates through the MySQL server while it is running. 3. b. No 4. a. ANALYZE TABLE, b. CHECK TABLE, c. CHECKSUM TABLE, and e. OPTIMIZE TABLE. REPAIR TABLE is not supported by InnoDB. 5. a. mysqlcheck with the --optimize option 6. a. True 7. c. --innodb_force_recovery

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 13: Table Maintenance Chapter 13 - Page 5

Practice 13-2: Using Table Maintenance SQL Statements Overview

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

In this practice, you use SQL statements to check and optimize a table.

Duration This practice should take approximately 15 minutes to complete.

Tasks 1. In the world_innodb database, create a new table called City_temp, which is a copy of the City table. Insert the contents of the City table into the City_temp table: CREATE TABLE City_temp LIKE City; INSERT INTO City_temp SELECT * FROM City;

− Show the current table status, for future comparison, using the SHOW TABLE STATUS statement.

ns a r t -City_temp n 3. Create “holes” (gaps between rows resulting from deletes or updates) ino the table data by removing several rows, using the ID column, as follows: an s DELETE FROM City_temp WHERE ID BETWEEN 1001 AND ha 2000; eฺ ) d i m − Confirm that the rows were deleted, and the u and Index_Length oData_Length c G ฺ t n statistics have changed. e den e t 4. Update the table’s statistics by running ANALYZE u on the City_temp table. Confirm tTABLE wtheamysql S that the analysis took place. Then exit client session. @ s i n h a t ฺkh use r e fe e to a s ( ens n a h lic K er e f a 2. Check the City_temp table for any problems. Does the table currently have a problem?

S

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

Practices for Lesson 13: Table Maintenance Chapter 13 - Page 6

e

bl a r fe

Solutions 13-2: Using Table Maintenance SQL Statements

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

Tasks 1. In the world_innodb database, create a new table called City_temp, which is a copy of the City table. Insert the contents of the City table into the City_temp table. a. Enter the following in a terminal window, and receive the results shown below: $ mysql --login-path=admin Welcome to the MySQL monitor. ...

Commands end with ; or \g.

mysql> USE world_innodb Database changed mysql> CREATE TABLE City_temp LIKE City; Query OK, 0 rows affected (0.10 sec)

e

bl a r fe

s

an r t n

b. Enter the following statement to populate the City_temp table, and receive the results shown below:

Sa

no a mysql> INSERT INTO City_temp SELECT * FROM City;s hasec)deฺ Query OK, 4079 rows affected, 1 warning (2.02 ) Records: 4079 Duplicates: 0 Warnings:om 1 ui c G ฺ t table into another with an auto The warning indicates that you are inserting rows one n en from e e t increment field while binary logging is enabled. a SYou tudcan safely ignore this warning in the w current lesson. @ his n a c. Show the current table status, h sefortfuture comparison, using the SHOW TABLE k ฺ r STATUS statement: e to u e f a mysql> (SHOW s TABLE seSTATUS LIKE 'City_temp' \G n n e *************************** ha licName: City_temp 1. row *************************** K r fee Engine: InnoDB Version: Row_format: Rows: Avg_row_length: Data_length: Max_data_length: Index_length: ...

10 Compact 4188 97 409600 0 131072

− Take note of the current values for Rows, Data_Length, and Index_Length.

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

Practices for Lesson 13: Table Maintenance Chapter 13 - Page 7

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

2. Check the City_temp table for any problems. Does the table currently have a problem? Enter the following in the current mysql client session, and receive the results shown below: mysql> CHECK TABLE City_temp\G *************************** 1. row *************************** Table: world_innodb.City_temp Op: check Msg_type: status Msg_text: OK 1 row in set (0.02 sec)

3. Create “holes” (gaps between rows resulting from deletes or updates) in the City_temp table data by removing several rows. Confirm that the rows were deleted and that the Data_Length and Index_Length statistics have changed. a. Enter the following in the current mysql client session, and receive the result shown below: mysql> DELETE FROM City_temp WHERE Id BETWEEN 1001 AND 2000; Query OK, 1000 rows affected (0.03 sec)

S

er e f a

s

an r t b. Show the table status to confirm that the rows have been removed: on n a mysql> SHOW TABLE STATUS LIKE 'City_temp' \G s a *************************** 1. row *************************** h deฺ ) m Name: City_temp ui o c G ฺ Engine: InnoDB n ent e e t Version: 10 a Stud w Row_format: Compact @ his n a Rows: 3109 h se t k ฺ r Avg_row_length: ee e131 ou f t a Data_length: 409600 (s ens 0 n Max_data_length: a lic 131072 Kh Index_length: ...

− Note the change in the number of rows. Although this number is an estimate only for InnoDB tables (and may change with each execution of the SHOW TABLE STATUS statement), it gives you the general idea that the number of rows has decreased. − The Data_Length and Index_Length numbers remain the same.

4. Update the table’s statistics by running ANALYZE TABLE on the City_temp table. Confirm that the analysis took place. Then exit the mysql client session. a. Enter the following in the current mysql client session, and receive the results shown below: mysql> ANALYZE TABLE City_temp; +------------------------+---------+----------+----------+ | Table | Op | Msg_type | Msg_text | +------------------------+---------+----------+----------+ | world_innodb.City_temp | analyze | status | OK | +------------------------+---------+----------+----------+ 1 row in set (1.13 sec)

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

Practices for Lesson 13: Table Maintenance Chapter 13 - Page 8

e

bl a r fe

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

b. Show the new table status to confirm the optimization: mysql> SHOW TABLE STATUS LIKE 'City_temp' \G *************************** 1. row *************************** Name: City_temp Engine: InnoDB Version: 10 Row_format: Compact Rows: 3079 Avg_row_length: 106 Data_length: 327680 Max_data_length: 0 Index_length: 98304 ...

Note that the number of rows, average row length, and other values have changed after the analysis. c. Exit the session:

s

mysql> EXIT Bye

er e f a

o

an r t n

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 13: Table Maintenance Chapter 13 - Page 9

e

bl a r fe

Practice 13-3: Using Table Maintenance Utilities Overview

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

In this practice, you use MySQL command line utilities to check and repair a table.

Duration This practice should take approximately 15 minutes to complete.

Tasks 1. From a shell prompt, run a check on the world_innodb database by using the mysqlcheck client program (with the standard username (-u) and password (-p) options). 2. Run a similar check as in the previous step, but this time use a login path instead of -u and -p, and check on all current databases using mysqlcheck. 3. Modify the statement used in the previous step to analyze all tables in all databases. Note the messages given by each table, and the differences between those messages.

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 13: Table Maintenance Chapter 13 - Page 10

e

bl a r fe

Solutions 13-3: Using Table Maintenance Utilities

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

Tasks 1. From a shell prompt, run a check on the world_innodb database by using the mysqlcheck client program (with the standard username (-u) and password (-p) options). Enter the following in a terminal window, and receive the results shown below: $ mysqlcheck -uroot -p --databases world_innodb Enter password: oracle world_innodb.City world_innodb.Country world_innodb.CountryLanguage

OK OK OK

− All eligible tables show that their status is OK. 2. Run a similar check as in the previous step, but this time use a login path instead of -u and -p, and check on all current databases using mysqlcheck. Enter the following in a terminal window, and receive the results shown below: $ mysqlcheck --login-path=admin --all-databases mysql.columns_priv mysql.db mysql.event ... world_innodb.City_temp world_innodb.Country world_innodb.CountryLanguage

Sa

s

OK OK OK

an r t n

no a s ฺ a h ) de i m u o c G OK ฺ t n n OK tee tude a OK w sS @ − All tables show that theirnstatus ishOK. i a t h e 3. Modify the statement used ฺkin the uprevious s step to analyze all tables in all databases. Note reach e the messages given by table, e o f t and the differences between those messages. a e s ( ein na sterminal window, and receive the results shown below: Enter the following n a $hmysqlcheck lic --login-path=admin --all-databases --analyze K r Table is already up to fee mysql.columns_priv date mysql.db Table is already up to date mysql.event Table is already up to date mysql.func Table is already up to date mysql.general_log note : The storage engine for the table doesn't support analyze mysql.help_category Table is already up to date ... mysql.slave_worker_info OK mysql.slow_log note : The storage engine for the table doesn't support analyze mysql.tables_priv Table is already up to date Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Table Maintenance Chapter 13 - Page 11

e

bl a r fe

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

mysql.time_zone date ... sakila.film_actor sakila.film_category sakila.film_text date sakila.inventory sakila.language ... world_innodb.City_part world_innodb.City_temp world_innodb.Country world_innodb.CountryLanguage

Table is already up to

OK OK Table is already up to OK OK OK OK OK OK

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 13: Table Maintenance Chapter 13 - Page 12

e

bl a r fe

Analyzed tables return a status of OK. Tables analyzed in a previous practice (or that have not changed since an earlier ANALYZE) report that the Table is already up to date, and CSV tables such as mysql.general_log report that The storage engine for the table doesn't support analyze.

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

e

bl a r fe

s

an r t n

er e f a

no a s ฺ 14: a Practices for Lesson h ) and iImporting de m Exporting Data u o c G ฺ t n e 14den e Chapter t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 14: Exporting and Importing Data Chapter 14 - Page 1

Practices for Lesson 14: Overview

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

Practices Overview In these practices, you test your knowledge of exporting and importing data. The hands-on practices are written for the Oracle Linux operating system environment, which is provided in Oracle classrooms. For non-Oracle classrooms, some adjustments may need to be made regarding file locations.

Assumptions •

The MySQL server installation has been completed prior to these practices.



You are logged in as the oracle user in a terminal window.



You can access the mysql client from a command line prompt.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 14: Exporting and Importing Data Chapter 14 - Page 2

Practice 14-1: Exporting MySQL Data

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

Overview In this practice, you use the SELECT ... INTO OUTFILE statement to export data. To accomplish this objective: • Using the default export options, export the contents of the CountryLanguage table in the world_innodb database. •

Using a comma-separated value output, export the contents of the CountryLanguage table in the world_innodb database.

Duration This practice should take approximately five minutes to complete.

e

bl a r fe

Tasks

1. Using the mysql client, in the world_innodb database, export the contents of the CountryLanguage table to a file called CountryLanguage.txt in the /tmp directory. Use the default export options. 2. In a second terminal window, view the contents of the /tmp/countryLanguage.txt file.

s

an r t n

Sa

no a s ฺ a − How are the different columns separated from each h other? ) de ______________________________________________________________ i m u o G database, export the ฺc world_innodb 3. In the first terminal window in the mysql client, innthe t n e contents of the CountryLanguage table to tea file tcalled deCountryLanguage.csv in the a u w /tmp directory. Use a comma-separated value S output. @ s i n h tcontents of the /tmp/countryLanguage.csv 4. In the second terminal window, ha viewsthe e k ฺ r file. e to u edifferent f a − How are the e columns separated from each other? s s ( n ______________________________________________________________ han lice K r fee

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

Practices for Lesson 14: Exporting and Importing Data Chapter 14 - Page 3

Solutions 14-1: Exporting MySQL Data

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

Tasks 1. Using the mysql client, in the world_innodb database, export the contents of the CountryLanguage table to a file called CountryLanguage.txt in the /tmp directory. Use the default export options. At a Linux terminal prompt, issue the following commands and receive the results shown: $ mysql -uroot -poracle Welcome to the MySQL monitor. ...

Commands end with ; or \g.

mysql> USE world_innodb; ... Database changed mysql> SELECT * INTO OUTFILE '/tmp/CountryLanguage.txt' -> FROM CountryLanguage; Query OK, 984 rows affected (0.00 sec)

s

an r t n

no a s ฺ a 2. In a second terminal window, view the contents of the /tmp/countryLanguage.txt file. h e ) d i m At a Linux terminal prompt, issue the following command u the results shown: o andGreceive c ฺ t n $ more /tmp/CountryLanguage.txt e n e e t d ABW Dutch T 5.3 a w s Stu @ ABW English F 9.5 n F thi 76.7 a h ABW Papiamento ฺFk u7.4 se r e ABW Spanish fe Fe to 0.9 a AFG Balochi s ( ens n AFG Dari 32.1 a h lic TT K AFG Pashto 52.4 r e e f AFG Turkmenian F 1.9 The preceding command creates a file in the /tmp directory.

Sa

e

bl a r fe

AFG AGO ...

Uzbek Ambo

F F

8.8 2.4

− Press to page down, and q to exit the more window. − How are the different columns separated from each other? The columns are tabdelimited. 3. In the first terminal window in the mysql client, in the world_innodb database, export the contents of the CountryLanguage table to a file called CountryLanguage.csv in the /tmp directory. Use a comma-separated value output. At a mysql prompt, issue the following command and receive the results shown: mysql> -> -> ->

SELECT * INTO OUTFILE '/tmp/CountryLanguage.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' FROM CountryLanguage;

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

Practices for Lesson 14: Exporting and Importing Data Chapter 14 - Page 4

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

4. In the second terminal window, view the contents of the /tmp/CountryLanguage.csv file. At a Linux terminal prompt, issue the following command and receive the results shown: $ more /tmp/CountryLanguage.csv "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" ...

e

s

an r t n

− How are the different columns separated from each other? The columns are comma-separated.

o

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 14: Exporting and Importing Data Chapter 14 - Page 5

bl a r fe

Practice 14-2: Importing Data

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

Overview In this practice, you use the LOAD DATA INFILE statement to import data. To accomplish this objective: • Create a new table based on the CountryLanguage table in the world_innodb database. • Import the contents of the text file created in the previous practice into this new table.

Duration This practice should take approximately five minutes to complete.

Tasks

s

an r t n

Sa

no a s ฺ a h e the table is now ) dthat i 4. Select all the data in the new CountryLanguage2 table to confirm m u o ฺc nt G populated. Then exit the mysql session. n e ate Stude w @ his n a h se t k ฺ r ee e to u f a (s ens n ha lic K r fee

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

Practices for Lesson 14: Exporting and Importing Data Chapter 14 - Page 6

e

bl a r fe

1. Using the mysql client while connected to the world_innodb database, create a new table named CountryLanguage2 that has the same structure as the original CountryLanguage table. 2. Show the tables list and confirm that the new table now exists. 3. Issue a LOAD DATA INFILE statement that loads the file /tmp/CountryLanguage.txt into the CountryLanguage2 table.

Solutions 14-2: Importing Data

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

Tasks 1. Using the mysql client while connected to the world_innodb database, create a new table named CountryLanguage2 that has the same structure as the original CountryLanguage table. At a mysql prompt, issue the following command: mysql> CREATE TABLE CountryLanguage2 LIKE CountryLanguage; Query OK, 0 rows affected (0.86 sec)

2. Show the tables list and confirm that the new table now exists. At a mysql prompt, issue the following command and receive the results shown: mysql> SHOW TABLES; +------------------------+ | Tables_in_world_innodb | +------------------------+ | City | | CityLanguage | | City_part | | City_temp | | Country | | CountryLanguage | | CountryLanguage2 | +------------------------+ 7 rows in set (0.00 sec)

e

bl a r fe

s

an r t n

S

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a h se t k ฺ r u that loads the file /tmp/CountryLanguage.txt 3. Issue a LOAD DATA e statement e INFILE o f t a into the CountryLanguage2 table. sethe following command and receive the results shown: (s eissue n n At a mysql prompt, ha LOAD licDATA INFILE '/tmp/CountryLanguage.txt' INTO TABLE K mysql> er e -> CountryLanguage2; f a 4. Select all the data in the new CountryLanguage2 table to confirm that the table is now populated. Then exit the mysql session. At a mysql prompt, issue the following command and receive the results shown:

mysql> SELECT * FROM CountryLanguage2; +-------------+---------------------------+------------+------------+ | CountryCode | Language | IsOfficial | Percentage | +-------------+---------------------------+------------+------------+ | ABW | Dutch | T | 5.3 | | ABW | English | F | 9.5 | ... | ZWE | Ndebele | F | 16.2 | | ZWE | Nyanja | F | 2.2 | | ZWE | Shona | F | 72.1 | +-------------+---------------------------+------------+------------+ 984 rows in set (0.00 sec) mysql> EXIT Bye Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Exporting and Importing Data Chapter 14 - Page 7

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

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 14: Exporting and Importing Data Chapter 14 - Page 8

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

e

bl a r fe

s

an r t n

er e f a

no a s ฺ 15: a Practices for Lesson h ) de MySQL i m Programming Inside u o ฺc nt G n e e u15de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 1

Practices for Lesson 15: Overview

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

Practices Overview In these practices, you test your knowledge of using the programming tools inside MySQL. The hands-on practices are written for the Oracle Linux operating system environment, which is provided in Oracle classrooms. For non-Oracle classrooms, some adjustments may need to be made regarding file locations.

Assumptions •

The MySQL server installation has been completed prior to these practices.



You are logged in as the oracle user in a terminal window.



You can access the mysql client from a command line prompt.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 2

Practice 15-1: Creating Stored Routines Overview

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

In this practice, you create and execute a stored procedure and a stored function. To accomplish this objective: •

Use the world_innodb database.



Create and execute a stored procedure that displays the record count for the City, Country, and CountryLanguage tables in the world_innodb database.



Create and execute a stored function that determines take-home pay based on inputting two values: base salary and tax rate.

Duration This practice should take approximately 20 minutes to complete.

Tasks 1.

e

s

an r t n

Using the mysql client, in the world_innodb database, enter the following SQL statements to create the record_count stored procedure:

bl a r fe

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a h se t k ฺ r ee e to u f a s (s encommand 2. Issue an n appropriate to execute the record_count stored procedure. a c i h l K to the test database, and attempt to execute the record_count stored 3. Change r e fe procedure. DELIMITER // CREATE PROCEDURE record_count () BEGIN SELECT 'Country count ', COUNT(*) FROM Country; SELECT 'City count ', COUNT(*) FROM City; SELECT 'CountryLanguage count', COUNT(*) FROM CountryLanguage; END// DELIMITER ;

Sa

4.

− Why did the record_count procedure fail? _________________________________________________________________ _________________________________________________________________ Execute the record_count stored procedure, this time qualified with the name of the world_innodb database. − Did the record_count stored procedure execute properly? _______________

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 3

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

5.

Change to the world_innodb database and issue the following SQL statements to create the pay_check stored function: DELIMITER // CREATE FUNCTION pay_check (gross_pay FLOAT(9,2), tax_rate FLOAT(3,2)) RETURNS FLOAT(9,2) NO SQL BEGIN DECLARE net_pay FLOAT(9,2) DEFAULT 0; SET net_pay=gross_pay - gross_pay * tax_rate; RETURN net_pay; END// DELIMITER ;

6.

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 4

e

bl a r fe

Execute the pay_check stored function by issuing an appropriate SQL statement, passing in the arguments 100000 and 0.05.

Solutions 15-1: Creating Stored Routines Tasks

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

1.

Using the mysql client, in the world_innodb database, enter the following SQL statements to create the record_count stored procedure. Enter the following at a Linux terminal and receive the results shown below: $ mysql --login-path=admin Welcome to the MySQL monitor. Commands end with ; or \g. ... mysql> USE world_innodb; ... Database changed mysql> DELIMITER // mysql> CREATE PROCEDURE record_count () -> BEGIN -> SELECT 'Country count ', COUNT(*) FROM Country; -> SELECT 'City count ', COUNT(*) FROM City; -> SELECT 'CountryLanguage count', COUNT(*) FROM -> CountryLanguage; -> END// Query OK, 0 rows affected (0.06 sec)

e

s

an r t n

Sa

bl a r fe

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w mysql> DELIMITER ; @ his n a The world_innodb database now t a stored procedure called record_count. h secontains k ฺ r uexecute the record_count stored procedure. 2. Issue an appropriatee to e command o f t a Enter the following se at a mysql prompt, and receive the results shown below: (s estatement n n mysql> ha CALL licrecord_count(); K +----------------+----------+ r fee | Country count | COUNT(*) | +----------------+----------+ | Country count | 239 | +----------------+----------+ 1 row in set (0.00 sec) +-------------+----------+ | City count | COUNT(*) | +-------------+----------+ | City count | 4079 | +-------------+----------+ 1 row in set (0.01 sec) +-----------------------+----------+ | CountryLanguage count | COUNT(*) | +-----------------------+----------+ | CountryLanguage count | 984 | +-----------------------+----------+ 1 row in set (0.01 sec) Query OK, 0 rows affected (0.01 sec) Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 5

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

3.

Change to the test database, and attempt to execute the record_count stored procedure. Enter the following in a terminal window, and receive the results shown: mysql> USE test; ... Database changed mysql> CALL record_count(); ERROR 1305 (42000): PROCEDURE test.record_count does not exist.

− Why did the record_count procedure fail? The stored procedure record_count is part of the world_innodb database. MySQL is looking for the record_count stored procedure in the test database. 4.

Execute the record_count stored procedure, this time qualified with the name of the world_innodb database. Enter the following in a terminal window, and receive the results shown:

s

mysql> CALL world_innodb.record_count(); +----------------+----------+ | Country count | COUNT(*) | +----------------+----------+ | Country count | 239 | +----------------+----------+ 1 row in set (0.01 sec)

S

er e f a

o

an s ha deฺ ) om Gui c ฺ en dent +-------------+----------+ e t | City count | COUNT(*) | wa tu S +-------------+----------+ @ s i n a | City count | 4079 | th h e +-------------+----------+ rฺk sec) us e 1 row in set (0.01 e o f t a se s ( n icen +-----------------------+----------+ a h l count | COUNT(*) | K| CountryLanguage +-----------------------+----------+ | CountryLanguage count | 984 | +-----------------------+----------+ 1 row in set (0.01 sec) Query OK, 0 rows affected (0.01 sec)

− Did the record_count stored procedure execute properly? Yes

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 6

an r t n

e

bl a r fe

5.

Change to the world_innodb database and issue the following SQL statements to create the pay_check stored function.

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

Enter the following statements at a mysql prompt and receive the results shown: mysql> USE world_innodb; ... Database changed mysql> DELIMITER // mysql> CREATE FUNCTION pay_check (gross_pay FLOAT(9,2), -> tax_rate FLOAT(3,2)) -> RETURNS FLOAT(9,2) -> NO SQL -> BEGIN -> DECLARE net_pay FLOAT(9,2) DEFAULT 0; -> SET net_pay=gross_pay - gross_pay * tax_rate; -> RETURN net_pay; -> END// Query OK, 0 rows affected (0.06 sec)

Sa

e

bl a r fe

s

an r t n

no a s ฺ mysql> DELIMITER ; a h e statement, passing ) dSQL i 6. Execute the pay_check stored function by issuing o anm appropriate u ฺc nt G in the arguments 100000 and 0.05. n e e the results shown: e and dreceive Enter the following statement at a mysql atprompt u t w S mysql> SELECT pay_check (100000, 0.05); @ s i n h +-------------------------+ ha se| t k ฺ | pay_check (100000,0.05) r ee e to u +-------------------------+ f a | (s ens 95000.00 | n +-------------------------+ ha lic K r fee

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 7

Practice 15-2: Reviewing Stored Routines Overview

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

In this practice, you review the stored routines created in an earlier practice. To accomplish this objective: •

Review a specific stored routine located in the world_innodb database using the SHOW CREATE PROCEDURE command.



Review stored routines located in the MySQL server using the SHOW { PROCEDURE | FUNCTION } STATUS commands.



Review all the stored routines located in the MySQL server using the INFORMATION_SCHEMA database.

Duration This practice should take approximately 10 minutes to complete.

ns a r t n 1. Using the mysql client, in the world_innodb database, issue a SHOW o CREATE n procedure. PROCEDURE command to review the details of the record_count a stored s a ofeallฺ stored procedures 2. Issue a SHOW PROCEDURE STATUS command to review thehstatus ) on the MySQL server that have a name beginning with record.uid om c G ฺ t 3. Issue a SHOW FUNCTION STATUS commandetonreview the status of all stored functions n located on the MySQL server. ate Stude w 4. Using the INFORMATION_SCHEMA@ database, sissue a SELECT statement to review the ithe n h a t details for all the stored routines located on MySQL server. h se k ฺ r ee e to u f a (s ens n ha lic K er e f a Tasks

S

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 8

e

bl a r fe

Solutions 15-2: Reviewing Stored Routines Tasks

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

1.

Using the mysql client, in the world_innodb database, issue a SHOW CREATE PROCEDURE command to review the details of the record_count stored procedure. Enter the following statement at a mysql prompt connected to the world_innodb database, and receive the results shown: mysql> SHOW CREATE PROCEDURE record_count\G *************************** 1. row *************************** Procedure: record_count sql_mode: STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION Create Procedure: CREATE DEFINER=`root`@`localhost` PROCEDURE `record_count`() BEGIN SELECT 'Country count ', COUNT(*) FROM Country; SELECT 'City count ', COUNT(*) FROM City; SELECT 'CountryLanguage count', COUNT(*) FROM CountryLanguage; END character_set_client: utf8 collation_connection: utf8_general_ci Database Collation: latin1_swedish_ci 1 row in set (0.00 sec)

s

an r t n

Sa

no a s ฺ a h ) de i m u o c Gstatus of all stored procedures 2. Issue a SHOW PROCEDURE STATUS commandntoฺ reviewnthe t e te tuwith on the MySQL server that have a namea beginning derecord. w S and receive the results shown: Enter the following statement at a@ mysql prompt, s i n h tLIKE 'record%'\G ha STATUS mysql> SHOW PROCEDURE e k ฺ s r *************************** u 1. row *************************** ee eDb: o world_innodb f t a (s ensName: record_count n Type: PROCEDURE ha lic Definer: K root@localhost r e Modified: 2013-02-10 13:48:11 e f Created: 2013-02-10 13:48:11 Security_type: DEFINER Comment: character_set_client: utf8 collation_connection: utf8_general_ci Database Collation: latin1_swedish_ci 1 row in set (0.00 sec)

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 9

e

bl a r fe

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

3.

Issue a SHOW FUNCTION STATUS command to review the status of all stored functions located on the MySQL server. Enter the following statement at a mysql prompt, and receive the results shown: mysql> SHOW FUNCTION STATUS\G *************************** 1. row *************************** Db: sakila Name: get_customer_balance Type: FUNCTION Definer: root@localhost Modified: 2013-02-03 15:25:01 Created: 2013-02-03 15:25:01 Security_type: DEFINER Comment: character_set_client: utf8 collation_connection: utf8_general_ci Database Collation: latin1_swedish_ci *************************** 2. row *************************** Db: sakila Name: inventory_held_by_customer Type: FUNCTION Definer: root@localhost Modified: 2013-02-03 15:25:01 Created: 2013-02-03 15:25:01 Security_type: DEFINER Comment: character_set_client: utf8 collation_connection: utf8_general_ci Database Collation: latin1_swedish_ci *************************** 3. row *************************** Db: sakila Name: inventory_in_stock Type: FUNCTION Definer: root@localhost Modified: 2013-02-03 15:25:01 Created: 2013-02-03 15:25:01 Security_type: DEFINER Comment: character_set_client: utf8 collation_connection: utf8_general_ci Database Collation: latin1_swedish_ci *************************** 4. row *************************** Db: world_innodb Name: pay_check Type: FUNCTION Definer: root@localhost Modified: 2013-02-10 13:52:32 Created: 2013-02-10 13:52:32 Security_type: DEFINER Comment: character_set_client: utf8 collation_connection: utf8_general_ci Database Collation: latin1_swedish_ci 4 rows in set (0.00 sec)

S

er e f a

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 10

s

an r t n

o

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

e

bl a r fe

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

4.

Using the INFORMATION_SCHEMA database, issue a SELECT statement to review the details for all the stored routines located on the MySQL server. Enter the following statement at a mysql prompt, and receive the results shown: mysql> USE INFORMATION_SCHEMA; ... Database changed mysql> SELECT * FROM ROUTINES\G *************************** 1. row *************************** SPECIFIC_NAME: film_in_stock ROUTINE_CATALOG: def ROUTINE_SCHEMA: sakila ROUTINE_NAME: film_in_stock ... *************************** 7. row *************************** SPECIFIC_NAME: pay_check ROUTINE_CATALOG: def ROUTINE_SCHEMA: world_innodb ROUTINE_NAME: pay_check ROUTINE_TYPE: FUNCTION DATA_TYPE: float CHARACTER_MAXIMUM_LENGTH: NULL CHARACTER_OCTET_LENGTH: NULL NUMERIC_PRECISION: 9 NUMERIC_SCALE: 2 DATETIME_PRECISION: NULL CHARACTER_SET_NAME: NULL COLLATION_NAME: NULL DTD_IDENTIFIER: float(9,2) ROUTINE_BODY: SQL ROUTINE_DEFINITION: BEGIN DECLARE net_pay FLOAT(9,2) DEFAULT 0; SET net_pay=gross_pay - gross_pay * tax_rate; RETURN net_pay; END EXTERNAL_NAME: NULL EXTERNAL_LANGUAGE: NULL PARAMETER_STYLE: SQL IS_DETERMINISTIC: NO SQL_DATA_ACCESS: NO SQL SQL_PATH: NULL SECURITY_TYPE: DEFINER CREATED: 2013-02-10 13:52:32 LAST_ALTERED: 2013-02-10 13:52:32 SQL_MODE: STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION ROUTINE_COMMENT: DEFINER: root@localhost CHARACTER_SET_CLIENT: utf8 COLLATION_CONNECTION: utf8_general_ci DATABASE_COLLATION: latin1_swedish_ci *************************** 8. row *************************** SPECIFIC_NAME: record_count ROUTINE_CATALOG: def ROUTINE_SCHEMA: world_innodb ROUTINE_NAME: record_count ROUTINE_TYPE: PROCEDURE DATA_TYPE: CHARACTER_MAXIMUM_LENGTH: NULL

s

o

an r t n

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 11

e

bl a r fe

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

CHARACTER_OCTET_LENGTH: NULL NUMERIC_PRECISION: NULL NUMERIC_SCALE: NULL DATETIME_PRECISION: NULL CHARACTER_SET_NAME: NULL COLLATION_NAME: NULL DTD_IDENTIFIER: NULL ROUTINE_BODY: SQL ROUTINE_DEFINITION: BEGIN SELECT 'Country count ', COUNT(*) FROM Country; SELECT 'City count ', COUNT(*) FROM City; SELECT 'CountryLanguage count', COUNT(*) FROM CountryLanguage; END EXTERNAL_NAME: NULL EXTERNAL_LANGUAGE: NULL PARAMETER_STYLE: SQL IS_DETERMINISTIC: NO SQL_DATA_ACCESS: CONTAINS SQL SQL_PATH: NULL SECURITY_TYPE: DEFINER CREATED: 2013-02-10 13:48:11 LAST_ALTERED: 2013-02-10 13:48:11 SQL_MODE: STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION ROUTINE_COMMENT: DEFINER: root@localhost CHARACTER_SET_CLIENT: utf8 COLLATION_CONNECTION: utf8_general_ci DATABASE_COLLATION: latin1_swedish_ci 8 rows in set (0.00 sec)

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 12

e

bl a r fe

Practice 15-3: Creating a Trigger Overview

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

In this practice, you create a trigger to capture data as it is deleted. To accomplish this objective: •

Create a table to store references to data that is deleted in the City table in the world_innodb table.



Create a trigger that stores the reference to the deleted data after the delete has taken place in the created table.



Delete data from the City table in the world_innodb table.



Verify that the table created contains the references to the deleted data.

Duration

e

This practice should take approximately 20 minutes to complete.

s

an r t n

Tasks

bl a r fe

no a s ฺ a h CREATE TABLE DeletedCity ) de i m ( ID INT UNSIGNED, u o ฺc nt G n Name VARCHAR(50), e e ude When_Deleted timestamp); at t w S @ s 2. Issue the following SQL statement a trigger to capture data after a record is n to create hicaptured a t h deleted from the City table and place the data in the DeletedCity table: e ฺk us r e CREATE TRIGGER fe City_AD to AFTER DELETE ON City a e s ( ROWens FOR EACH n a INSERT h INTO licDeletedCity (ID, Name) K r VALUES (OLD.ID, OLD.Name); fee 1.

Sa 3.

4. 5. 6.

Using the mysql client, in the world_innodb database, issue the following SQL statement to create a table to store references to records deleted in the City table:

Issue an appropriate SHOW command to confirm that the trigger has been created.

Delete the records with the city name Dallas in the City table. Attempt to select all the City table records with the name Dallas to verify that the delete operation worked properly. View the contents of the DeletedCity table to determine whether the trigger captured the references to the record deleted in step 4.

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 13

Solutions 15-3: Creating a Trigger Tasks

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

1.

Using the mysql client, in the world_innodb database, issue the following SQL statement to create a table to store references to records deleted in the City table. Enter the following statements at a mysql prompt connected to the world_innodb database, and receive the results shown: mysql> USE world_innodb; ... Database changed mysql> CREATE TABLE DeletedCity -> (ID INT UNSIGNED, -> Name VARCHAR(50), -> When_Deleted timestamp); ); Query OK, 0 rows affected (0.06 sec)

s

an r t n

no a s ฺ a h ) de i m u o mysql> CREATE TRIGGER City_AD AFTER DELETE ON City ฺc nt G n -> FOR EACH ROW e ate(ID,StName) -> INSERT INTO DeletedCity ude w @ -> VALUES (OLD.ID, OLD.Name); is n h a t h se(0.06 sec) Query OK, 0 rowsฺk affected r e e SHOWecommand o u to confirm that the trigger has been created. 3. Issue an appropriate f t a (s estatement Enter then following ns at a mysql prompt, and receive the results shown: a c h SHOW li TRIGGERS\G mysql> K r fee *************************** 1. row *************************** 2.

Sa

e

Issue the following SQL statement to create a trigger to capture data after a record is deleted from the City table and place the captured data in the DeletedCity table. Enter the following statement at a mysql prompt, and receive the results shown:

Trigger: City_AD Event: DELETE Table: City Statement: INSERT INTO DeletedCity (ID, Name) VALUES (OLD.ID, OLD.Name) Timing: AFTER Created: NULL sql_mode: STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION Definer: root@localhost character_set_client: utf8 collation_connection: utf8_general_ci Database Collation: latin1_swedish_ci 1 row in set (0.01 sec)

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 14

bl a r fe

4.

Delete the records with the city name Dallas in the City table. Enter the following statement at a mysql prompt, and receive the results shown:

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

mysql> DELETE FROM City WHERE Name = 'Dallas'; Query OK, 1 row affected (0.13 sec)

5.

Attempt to select all the City table records with the name Dallas to verify that the delete operation worked properly. Enter the following statement at a mysql prompt, and receive the results shown: mysql> SELECT * FROM City WHERE Name = 'Dallas'; Empty set (0.00 sec)

6.

View the contents of the DeletedCity table to determine whether the trigger captured the references to the record deleted in step 4. Enter the following statement at a mysql prompt, and receive the results shown: mysql> SELECT * FROM DeletedCity; +------+--------+---------------------+ | ID | Name | When_Deleted | +------+--------+---------------------+ | 3800 | Dallas | 2013-02-10 14:01:51 | +------+--------+---------------------+ 1 row in set (0.00 sec)

Sa

e

an r t n

no a s ฺ a h ) it was The deleted record appears in the result set, along with when dedeleted. i m u o ฺc nt G n e ate Stude w @ his n a h se t k ฺ r ee e to u f a (s ens n ha lic K r fee

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 15

s

bl a r fe

Practice 15-4: Creating and Testing an Event Overview

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

In this practice, you create an event to locate processes that are taking too long to run on the MySQL server and terminate their connection. To accomplish this objective: • •

Create an event that disconnects non-root users when queries run longer than 30 seconds. Turn on the event scheduler.



Create a non-root user to test the created event.



Test the created event.

Duration This practice should take approximately 20 minutes to complete. Note: This practice uses an advanced level of programming in the event creation that is beyond the scope of this course. However, the example is intended to show the power of programming at an advanced level, and how beneficial learning more about this topic could be to your day-today tasks of managing a MySQL server.

s

an r t n

Sa

no a s ฺ Tasks a h e SQL statement )issue theidfollowing 1. Using the mysql client, in the world_innodb database, m u o to create an event that disconnects non-root users G run longer than 30 ฺc whennqueries t n e seconds: ate Stude w DELIMITER // @ his n CREATE EVENT kill_user a t h 20 SECOND e k ON SCHEDULE EVERY ฺ s r ee e to u DO f a (s ens BEGIN n a c hDECLARE INT; livar_id K r DECLARE procs CURSOR FOR SELECT id fee FROM INFORMATION_SCHEMA.PROCESSLIST WHERE TIME>30 AND Command != 'Sleep' AND USER != 'root'; OPEN procs; BEGIN DECLARE EXIT HANDLER FOR NOT FOUND BEGIN CLOSE procs; END; LOOP FETCH procs INTO var_id; KILL var_id; END LOOP; END; END// DELIMITER ;

2. Turn on the event scheduler. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 16

e

bl a r fe

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

3. Create a non-root user named tester logging in from the localhost with the password 'secret'. 4. Grant the new user access to all databases. 5. In a second terminal window, log in to the mysql client as the new user. 6. In the second terminal window, enter the following command to create a SELECT statement that attempts to run longer than 30 seconds: mysql> SELECT SLEEP(60);

− How long did it take the server to terminate the connections? ________________________________________________________________. 7. Exit the mysql client in the second terminal window.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 17

Solutions 15-4: Creating and Testing an Event

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

Tasks 1. Using the mysql client, in the world_innodb database, issue the following SQL statement to create an event that disconnects non-root users when queries run longer than 30 seconds: mysql> DELIMITER // mysql> CREATE EVENT kill_user -> ON SCHEDULE EVERY 20 SECOND -> DO -> BEGIN -> DECLARE var_id INT; -> DECLARE procs CURSOR FOR SELECT id -> FROM INFORMATION_SCHEMA.PROCESSLIST WHERE TIME>30 -> AND Command != 'Sleep' AND USER != 'root'; -> OPEN procs; -> BEGIN -> DECLARE EXIT HANDLER FOR NOT FOUND -> BEGIN -> CLOSE procs; -> END; -> LOOP -> FETCH procs INTO var_id; -> KILL var_id; -> END LOOP; -> END; -> END// Query OK, 0 rows affected (0.06 sec)

e

bl a r fe

s

an r t n

o

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K mysql> DELIMITER ;

2. Turn on the event scheduler. mysql> SET GLOBAL event_scheduler = ON; Query OK, 0 rows affected (0.06 sec)

3. Create a non-root user named tester logging in from the localhost with the password 'secret'. mysql> CREATE USER tester@localhost IDENTIFIED BY 'secret'; Query OK, 0 rows affected (0.06 sec)

4. Grant the new user access to all databases. mysql> GRANT SELECT ON *.* TO tester@localhost; Query OK, 0 rows affected (0.06 sec)

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 18

5. In a second terminal window, log in to the mysql client as the new user.

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

$ mysql -utester -p Enter password: secret Welcome to the MySQL monitor. ...

Commands end with ; or \g.

6. In the second terminal window, enter the following command to create a SELECT statement that attempts to run longer than 30 seconds: mysql> SELECT SLEEP(60); ERROR 2013 (HY000): Lost connection to MySQL server during query

− How long did it take the server to terminate the connection? Approximately 30 to 50 seconds after the query starts running, the server terminates the connection. Because this event is scheduled to run every 20 seconds, the event kills the process within 20 seconds of the 30-second limit. 7. Exit the mysql client in the second terminal window: mysql> EXIT Bye

s

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 19

e

bl a r fe

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

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 15: Programming Inside MySQL Chapter 15 - Page 20

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

e

bl a r fe

s

an r t n

er e f a

no a s ฺ 16: a Practices for Lesson h e ) dand i m MySQL Backup Recovery u o c G ฺ t n e 16den e Chapter t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 1

Practices for Lesson 16: Overview

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

Practices Overview In these practices, you test your knowledge of backup and recovery topics. The hands-on practices are written for the Oracle Linux operating system environment, which is provided in Oracle classrooms. For non-Oracle classrooms, some adjustments may need to be made regarding file locations.

Assumptions •

The MySQL server installation has been completed prior to these practices.



You are logged in as root user in a terminal window.



You can access the mysql client from a command-line prompt.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 2

Practice 16-1: Quiz – Introduction to Backups Overview

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

In this practice, you answer questions about MySQL backup strategies.

Duration This practice should take approximately five minutes to complete.

Quiz Questions For each of the choices below, write the types of backup strategy to be used: disk, logical/textual, or binary. (Each answer can consist of one, two, or all three types of strategy.) 1. Schema - Version Control

_________________________________

2. Data Analysis/Reporting

_________________________________

3. Virus/SQL injection (bad disk)

_________________________________

s

an r t n

4. User mistake/error _________________________________

no a s ฺ a 6. Power failure _________________________________ h ) de i m u o 7. System failure (disk, memory, network crash) _________________________________ ฺc nt G n e 8. Disaster (man-made, natural) _________________________________ ate Stude w 9. Archive records (compliance) _________________________________ @ s i n h t ha seserver 10. Testing data/creating a development _________________________________ k ฺ r u e 11. Migration _________________________________ fe e to a s ( ens 12. Software update _________________________________ n a c i h l K 13. Replication r e afe _________________________________

S

5. User destructive action (purposeful)

_________________________________

14. Evidence (for court/government proceedings)

_________________________________

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 3

e

bl a r fe

Solutions 16-1: Quiz – Introduction to Backups

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

Quiz Solutions 1. Disk, logical/textual 2. Logical/textual 3. Disk, logical/textual 4. Disk, logical/textual, binary log 5. Disk, logical/textual, binary log 6. Disk, logical/textual, binary log 7. Disk, logical/textual 8. Disk, logical/textual 9. Logical/textual 10. Disk 11. Logical/textual 12. Disk, logical/textual 13. Binary log 14. Logical/textual

er e f a

e

s

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 4

an r t n

o

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

bl a r fe

Practice 16-2: MySQL Enterprise Backup

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

Overview In this practice, you create a backup by using the mysqlbackup application. To accomplish this objective: • Modify the my.cnf file. •

Create a load on the MySQL server.



Execute the mysqlbackup application while there is a load on the MySQL server.



Delete files from the /var/lib/mysql directory.



Execute the backup to restore the files that were deleted.

Assumptions •

The MySQL server is installed and running.



The world_innodb database is installed.



The MySQL Enterprise Backup software is installed.

e

bl a r fe

s

an r t n

no a s ฺ This practice should take 30 minutes to complete. a h ) de i m u o Tasks ฺc nt G n e 1. Create the /backups directory, and change its owner te tudeto the mysql user. a w of stheSdatadir server parameter. 2. In the /etc/my.cnf file, note the value @ n hi a 3. Set the following my.cnf options as shown: t h e rฺk o us [mysqld] e e af se t log-bin=mybinlog s ( innodb_log_files_in_group = 2 an licen h K r innodb_log_file_size = 256M e e innodb_data_file_path=ibdata1:10M:autoextend af Duration

S

4. Add a section [mysqlbackup], and add the following settings:

5. 6. 7. 8.



backup-dir: /backups/meb1



user: backupuser



socket: /var/lib/mysql/mysql.sock

Save the changes to /etc/my.cnf file and close the file. Delete the InnoDB log files. Restart the MySQL server to apply the updated /etc/my.cnf. Open a second terminal window and start the mysql client.

9. In the second terminal window, create a MySQL user backupuser, identified by the password oracle, and grant that user all required permissions to use mysqlbackup. 10. In the second terminal window, use the world_innodb database and create a copy of the City table called City_Large.

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 5

11. In the second terminal window, issue the following command to insert all the records from the City table into the City_Large table.

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

INSERT INTO City_Large (Name, CountryCode, District, Population) SELECT Name, CountryCode, District, Population FROM City; 12. In the second terminal window, issue the following command to double the records from the City_Large table: INSERT INTO City_Large (Name, CountryCode, District, Population) SELECT Name, CountryCode, District, Population FROM City_Large;

13. In the second terminal window, execute the SQL statement from the preceding step seven times. 14. In the second terminal window, prior to running the backup, execute a FLUSH LOGS command. 15. In the second terminal window, issue the command from step 12 one more time. Do not wait for this step to finish; start the next step immediately. 16. In the first terminal window, issue the following commands (while the mysql command from the preceding step is continuing to execute) to run the mysqlbackup application as the mysql user.

s

an r t n

no a s ฺ a h ) # su - mysql de i m u o $ mysqlbackup --defaults-file=/etc/my.cnf -p backup-and-apply-log ฺc nt G n e 17. In the first terminal window, list the files in tthe directory. de a e /backups/meb1 u t w Suser shell back to the root shell. Then, in 18. In the first terminal window, exit from the mysql @ s i n h the /var/lib/mysql directory, the t ibdata1 file and the world_innodb directory. ha delete e k ฺ s r 19. In the second terminal ee e window, o u display all the databases that the MySQL f t server contains. a s exit the mysql client. (sterminal nwindow, n 20. In the second e a c hfirst terminal li window, shut down the MySQL server. K 21. Inr the eeIn the first terminal window, execute the following commands to restore the backup created af22.

S

to the /var/lib/mysql directory.

# su - mysql $ mysqlbackup --defaults-file=/etc/my.cnf copy-back 23. In the first terminal window, exit from the mysql shell and start the MySQL server. 24. In the second terminal window, start the mysql client and display all the databases that the MySQL server contains. 25. In the second terminal window, view all the tables that the world_innodb database contains. 26. In the second terminal window, exit the mysql client and close the terminal window.

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 6

e

bl a r fe

Solutions 16-2: MySQL Enterprise Backup Tasks 1. Create the /backups directory, and change its owner to the mysql user.

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

Enter the following at a Linux terminal: $ su Password: oracle # mkdir /backups # chown mysql:mysql /backups

2. In the /etc/my.cnf file, note the value of the datadir server parameter. − Locate the heading [mysqld] and note the value of the datadir parameter: [mysqld] ... datadir = /var/lib/mysql ...

ns a r t − Note: The datadir parameter must be in the file for cold backupsnto - take place. o The directory paths must be absolute. For hot or warm backups, mysqlbackup an queries the value from the server; it does not assume any defaults for file locations. s ha deฺ ) 3. Set the following my.cnf options as shown. ui and add the remaining om of log-bin, cvalue G − Locate the heading [mysqld] , modifyn the ฺ e dent lines shown below: e t wa s Stu [mysqld] @ n ... hi a t h e log-bin=mybinlog rฺk o us e e innodb_log_files_in_group = 2 af se t s ( innodb_log_file_size = 256M an licen h innodb_data_file_path=ibdata1:12M:autoextend K r e ... fe

Sa 4.

Add a section [mysqlbackup], and add the following settings: •

backup-dir: /backups/meb1



user: backupuser



socket: /var/lib/mysql/mysql.sock − Add the following lines to the end of /etc/my.cnf: ... [mysqlbackup] backup-dir=/backups/meb1 user=backupuser socket=/var/lib/mysql/mysql.sock

5. Save the changes to /etc/my.cnf file and close the file. 6. Delete the InnoDB log files. Enter the following in a terminal window: # rm -f /var/lib/mysql/ib_logfile* Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 7

e

bl a r fe

7. Restart the MySQL server to apply the updated /etc/my.cnf. Enter the following in a terminal window, and receive the result shown below:

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

# service mysql restart Shutting down MySQL... Starting MySQL.

[ [

OK OK

] ]

8. Open a second terminal window and start the mysql client. Receive the result shown below: $ mysql --login-path=admin Welcome to the MySQL monitor. ...

Commands end with ; or \g.

9. In the second terminal window, create a MySQL user backupuser, identified by the password oracle, and grant that user all required permissions to use mysqlbackup. Enter the following in a terminal window, and receive the results shown below:

s

no a s ฺ a h m) uide mysql> GRANT CREATE, INSERT, DROP ON c mysql.ibbackup_binlog_marker o G ฺ t n > TO 'backupuser'@'localhost'; n e de atesec) Query OK, 0 rows affected (0.00 u t w S @ s i n h tDROP ON mysql.backup_progress haINSERT, mysql> GRANT CREATE, e k ฺ s r > TO 'backupuser'@'localhost'; ee e to u f a Query OK, s affected (0.00 sec) (s 0 erows n n ha GRANT lic CREATE, INSERT, DROP ON mysql.backup_history Kmysql> mysql> GRANT RELOAD ON *.* TO 'backupuser'@'localhost'; Query OK, 0 rows affected (0.00 sec)

S

er e f a

an r t n

> TO 'backupuser'@'localhost'; Query OK, 0 rows affected (0.00 sec) mysql> GRANT REPLICATION CLIENT ON *.* TO 'backupuser'@'localhost'; Query OK, 0 rows affected (0.00 sec) mysql> GRANT SUPER ON *.* TO 'backupuser'@'localhost'; Query OK, 0 rows affected (0.00 sec) mysql> GRANT CREATE TEMPORARY TABLES ON mysql.* > TO 'backupuser'@'localhost'; Query OK, 0 rows affected (0.00 sec)

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 8

e

bl a r fe

mysql> CREATE USER 'backupuser'@'localhost' IDENTIFIED BY 'oracle'; Query OK, 0 rows affected (0.00 sec)

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

10. In the second terminal window, use the world_innodb database and create a copy of the City table called City_Large. Enter the following in a terminal window, and receive the results shown below: mysql> USE world_innodb; ... Database changed mysql> CREATE TABLE City_Large LIKE City;

11. In the second terminal window, issue the following command to insert all the records from the City table into the City_Large table. Receive the result shown below: mysql> INSERT INTO City_Large (Name, CountryCode, District, -> Population) SELECT Name, CountryCode, District, -> Population FROM City; Query OK, 4078 rows affected, 1 warning (1.78 sec) Records: 4078 Duplicates: 0 Warnings: 1

e

bl a r fe

s

an r t n

12. In the second terminal window, issue the following command to double the records from the City_Large table, and receive the result shown below:

no a s ฺ a h ) de i m u o ฺc nt G n e e atheteSQLSstatement 13. In the second terminal window, execute tud from the preceding step seven w @ window, times. Enter the following in a terminal is and receive the result shown below: n h a t h operation − Note: The time for e to complete gets progressively longer due to the kthe ฺ s r u e exponentialedoubling of f table.e tothe number of records that are being added to the a City_Large s ( ens n mysql> (Name, CountryCode, District, a h -> INSERT lic INTO City_Large K Population) SELECT Name, CountryCode, District, r e -> Population FROM City_Large; e f mysql> INSERT INTO City_Large (Name, CountryCode, District, -> Population) SELECT Name, CountryCode, District, -> Population FROM City_Large; Query OK, 4078 rows affected, 1 warning (1.68 sec) Records: 4078 Duplicates: 0 Warnings: 1

Sa

Query OK, 8156 rows affected, 1 warning (0.34 sec) Records: 8156 Duplicates: 0 Warnings: 1

mysql> INSERT INTO City_Large (Name, CountryCode, District, -> Population) SELECT Name, CountryCode, District, -> Population FROM City_Large; Query OK, 16312 rows affected, 1 warning (0.64 sec) Records: 16312 Duplicates: 0 Warnings: 1 mysql> INSERT INTO City_Large (Name, CountryCode, District, -> Population) SELECT Name, CountryCode, District, -> Population FROM City_Large; Query OK, 32624 rows affected, 1 warning (0.77 sec) Records: 32624 Duplicates: 0 Warnings: 1

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 9

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

mysql> INSERT INTO City_Large (Name, CountryCode, District, -> Population) SELECT Name, CountryCode, District, -> Population FROM City_Large; Query OK, 65248 rows affected, 1 warning (1.54 sec) Records: 65248 Duplicates: 0 Warnings: 1 mysql> INSERT INTO City_Large (Name, CountryCode, District, -> Population) SELECT Name, CountryCode, District, -> Population FROM City_Large; Query OK, 130496 rows affected, 1 warning (2.63 sec) Records: 130496 Duplicates: 0 Warnings: 1 mysql> INSERT INTO City_Large (Name, CountryCode, District, -> Population) SELECT Name, CountryCode, District, -> Population FROM City_Large; Query OK, 260992 rows affected, 1 warning (4.58 sec) Records: 260992 Duplicates: 0 Warnings: 1

e

bl a r fe

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e de execute a FLUSH LOGS 14. In the second terminal window, prior to running ate Sthetubackup, w command. This forces the current@ binary logs to close and the next incremental binary log to i n h be opened. ha se t k ฺ r mysql> FLUSH LOGS; e to u e f a 15. In the second(s terminal window, issue the command from step 12 one more time. Do not wait sethe next n n for this step to finish; start step immediately. e a operation hThe lic should take 20–40 Note: seconds to run. During this time, you return to the K r e first terminal window and execute the mysqlbackup command. This provides a simulated fe mysql> INSERT INTO City_Large (Name, CountryCode, District, -> Population) SELECT Name, CountryCode, District, -> Population FROM City_Large; Query OK, 521984 rows affected, 1 warning (11.33 sec) Records: 521984 Duplicates: 0 Warnings: 1

Sa

“hot” backup of the InnoDB tables. Enter the following in a terminal window, and receive the result shown below:

mysql> INSERT INTO City_Large (Name, CountryCode, District, -> Population) SELECT Name, CountryCode, District, -> Population FROM City_Large; Query OK, 1043968 rows affected, 1 warning (29.49 sec) Records: 1043968 Duplicates: 0 Warnings: 1

16. In the first terminal window, issue the following commands (while the mysql command from the preceding step is continuing to execute) to run the mysqlbackup application as the mysql user. Enter the following commands and receive the result shown below: # su mysql $ mysqlbackup --defaults-file=/etc/my.cnf -p backup-and-apply-log MySQL Enterprise Backup version 3.8.1 [2013/01/28] Copyright (c) 2003, 2012, Oracle and/or its affiliates. All Rights Reserved. mysqlbackup: INFO: Starting with following command line ... mysqlbackup --defaults-file=/etc/my.cnf -p backup-and-apply-log Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 10

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

Enter password: oracle mysqlbackup: INFO: MySQL server version is '5.6.10-enterprisecommercial-advanced-log'. mysqlbackup: INFO: Got some server configuration information from running server. IMPORTANT: Please check that mysqlbackup run completes successfully. At the end of a successful 'backup-and-apply-log' run mysqlbackup prints "mysqlbackup completed OK!". -------------------------------------------------------------------Server Repository Options: -------------------------------------------------------------------datadir = /var/lib/mysql/ innodb_data_home_dir = innodb_data_file_path = ibdata1:12M:autoextend innodb_log_group_home_dir = /var/lib/mysql/ innodb_log_files_in_group = 2 innodb_log_file_size = 268435456 innodb_page_size = 16384 innodb_checksum_algorithm = innodb innodb_undo_directory = /var/lib/mysql/ innodb_undo_tablespaces = 0 innodb_undo_logs = 128

s

an r t n

S

er e f a

no a s ฺ a h ) de i m u o ฺc nt G n e e ude -------------------------------------------------------------------atConfig t Options: Backup w S @ s -------------------------------------------------------------------n hi a t datadir = /backups/meb1/datadir h e rฺk o u= s/backups/meb1/datadir innodb_data_home_dir e e innodb_data_file_path af se t = ibdata1:12M:autoextend s ( innodb_log_group_home_dir = /backups/meb1/datadir n n e innodb_log_files_in_group = 2 a c li Khinnodb_log_file_size = 268435456 innodb_page_size = 16384 innodb_checksum_algorithm = innodb innodb_undo_directory = /backups/meb1/datadir innodb_undo_tablespaces = 0 innodb_undo_logs = 128 mysqlbackup: INFO: Unique generated backup id for this is 13605079305675972 mysqlbackup: INFO: Uses posix_fadvise() for performance optimization. mysqlbackup: INFO: Creating 14 buffers each of size 16777216. 130210 14:52:12 mysqlbackup: INFO: Full Backup operation starts with following threads 1 read-threads 6 process-threads 1 write-threads 130210 14:52:12 mysqlbackup: INFO: System tablespace file format is Antelope. 130210 14:52:12 mysqlbackup: INFO: Starting to copy all innodb files... 130210 14:52:12 mysqlbackup: INFO: Copying /var/lib/mysql/ibdata1 (Antelope file format). 130210 14:52:12 mysqlbackup: INFO: Found checkpoint at lsn 309944491. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 11

e

bl a r fe

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

130210 14:52:12 mysqlbackup: INFO: Starting log scan from lsn 309944320. 130210 14:52:12 mysqlbackup: INFO: Copying log... 130210 14:52:12 mysqlbackup: INFO: Log copied, lsn 309944491. 130210 14:52:12 mysqlbackup: INFO: Copying /var/lib/mysql/mysql/innodb_index_stats.ibd (Antelope file format). 130210 14:52:12 mysqlbackup: INFO: Copying /var/lib/mysql/mysql/innodb_table_stats.ibd (Antelope file format). ... 130210 14:52:20 mysqlbackup: INFO: Copying the database directory 'world_innodb' 130210 14:52:20 mysqlbackup: INFO: Completing the copy of all noninnodb files. 130210 14:52:20 mysqlbackup: INFO: A copied database page was modified at 309944491. (This is the highest lsn found on page) Scanned log up to lsn 309947815. Was able to parse the log up to lsn 309947815. Maximum page number for a log record 430 130210 14:52:20 mysqlbackup: INFO: All tables unlocked 130210 14:52:20 mysqlbackup: INFO: All MySQL tables were locked for 0.496 seconds. 130210 14:52:20 mysqlbackup: INFO: Full Backup operation completed successfully. 130210 14:52:20 mysqlbackup: INFO: Backup created in directory '/backups/meb1' 130210 14:52:20 mysqlbackup: INFO: MySQL binlog position: filename mybinlog.000003, position 2671

s

an r t n

S

er e f a

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his ------------------------------------------------------------n a Parameters Summary h se t k ฺ r ------------------------------------------------------------ee e to u f Start a LSN : 309944320 s s End (LSN : 309947815 n n e ------------------------------------------------------------a c li Kh

mysqlbackup: INFO: Creating 14 buffers each of size 65536. 130210 14:52:20 mysqlbackup: INFO: Apply-log operation starts with following threads 1 read-threads 1 process-threads 130210 14:52:20 mysqlbackup: INFO: ibbackup_logfile's creation parameters: start lsn 309944320, end lsn 309947815, start checkpoint 309944491. mysqlbackup: INFO: InnoDB: Starting an apply batch of log records to the database... InnoDB: Progress in percent: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 Setting log file size to 268435456 InnoDB: Progress in MB: 100 200 Setting log file size to 268435456 InnoDB: Progress in MB: 100 200 130210 14:52:30 mysqlbackup: INFO: We were able to parse ibbackup_logfile up to Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 12

e

bl a r fe

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

lsn 309947815. mysqlbackup: INFO: Last MySQL binlog file position 0 2671, file name mybinlog.000003 130210 14:52:30 mysqlbackup: INFO: The first data file is '/backups/meb1/datadir/ibdata1' and the new created log files are at '/backups/meb1/datadir' 130210 14:52:30 mysqlbackup: INFO: Apply-log operation completed successfully. 130210 14:52:30 mysqlbackup: INFO: Full backup prepared for recovery successfully. mysqlbackup completed OK!

17. In the first terminal window, list the files in the /backups/meb1 directory, and receive the result shown below: $ ls /backups/meb1/ backup-my.cnf datadir

e

bl a r 18. In the first terminal window, exit from the mysql user shell back to the root shell. Then, fe in s n the /var/lib/mysql directory, delete the ibdata1 file and the world_innodb directory. tra Enter the following in a terminal window, and receive the result shown below: n no $ exit a s ฺ a # cd /var/lib/mysql h ) de i # rm -f ibdata1 m u o ฺc nt G # rm -rf world_innodb n e te tuall dethe databases that the MySQL 19. In the second terminal window,adisplay w server contains. S @ s i n h t and receive the result shown below: Enter the following in a mysql ha window, e k ฺ s r mysql> SHOW DATABASES; ee e to u f +--------------------+ a (s ens | | Database n a +--------------------+ hinformation_schema lic K | | r e e | mysql | af | performance_schema | meta

S

| sakila | | test | | world2 | +--------------------+ 6 rows in set (0.00 sec) − Does the listing of databases include the world_innodb database? No

20. In the second terminal window, exit the mysql client. mysql> EXIT;

21. In the first terminal window, shut down the MySQL server. # service mysql stop Shutting down MySQL..

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 13

[

OK

]

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

22. In the first terminal window, execute the following commands to restore the backup created to the /var/lib/mysql directory, and receive the result shown below: # su mysql $ mysqlbackup --defaults-file=/etc/my.cnf copy-back MySQL Enterprise Backup version 3.6.0 [2011/07/01] Copyright (c) 2003, 2011, Oracle and/or its affiliates. All Rights Reserved. INFO: Starting with following command line ... ./mysqlbackup --defaults-file=/etc/my.cnf --backup-dir=/backups/meb1 copy-back IMPORTANT: Please check that mysqlbackup run completes successfully. At the end of a successful 'copy-back' run mysqlbackup prints "mysqlbackup completed OK!".

s

mysqlbackup: INFO: Server repository datadir = innodb_data_home_dir = innodb_data_file_path = innodb_log_group_home_dir = innodb_log_files_in_group = innodb_log_file_size =

Sa

an r t n

configuration: /var/lib/mysql /var/lib/mysql ibdata1:10M:autoextend /var/lib/mysql 2 256M

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a t hBackupserepository mysqlbackup: INFO: configuration: k ฺ r u e datadir = /backups/meb1/datadir e e to f a innodb_data_home_dir = /backups/meb1/datadir (s ens n = ibdata1:10M:autoextend a hinnodb_data_file_path lic K innodb_log_group_home_dir = /backups/meb1/datadir er

fe

innodb_log_files_in_group innodb_log_file_size

= =

2 268435456

mysqlbackup: INFO: Starting to copy back files mysqlbackup: INFO: in '/backups/meb1/datadir' directory mysqlbackup: INFO: back to original data directory '/var/lib/mysql' mysqlbackup: INFO: Copying back directory '/backups/meb1/datadir/mysql' mysqlbackup: INFO: Copying back directory '/backups/meb1/datadir/performance_schema' mysqlbackup: INFO: Copying back directory '/backups/meb1/datadir/test' mysqlbackup: INFO: Copying back directory '/backups/meb1/datadir/world_innodb' mysqlbackup: INFO: Starting to copy back InnoDB tables and indexes in '/backups/meb1' back to original InnoDB data directory: /var/lib/mysql mysqlbackup: INFO: Copying back file '/backups/meb1/datadir/ibdata1' mysqlbackup: INFO: Starting to copy back InnoDB log files Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 14

e

bl a r fe

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

in '/backups/meb1/datadir' back to original InnoDB log directory '/var/lib/mysql' mysqlbackup: INFO: Copying back file '/backups/meb1/datadir/ib_logfile0' mysqlbackup: INFO: Copying back file '/backups/meb1/datadir/ib_logfile1' mysqlbackup: INFO: Finished copying backup files. 23. In the first terminal window, exit from the mysql shell and start the MySQL server. $ exit # service mysql start 24. In the second terminal window, start the mysql client and display all the databases that the MySQL server contains. Enter the following in a terminal window,

and receive the results shown below: $ mysql --login-path=admin ... mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sakila | | test | | world2 | | world_innodb | +--------------------+ 7 rows in set (0.00 sec)

Sa

e

bl a r fe

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a h se t k ฺ r ee e to u f a (s terminal ns window, view all the tables that the world_innodb n e 25. In the a second c h contains. li Enter the following in a terminal window, and receive the results K database r feeshown below: mysql> USE world_innodb Database changed. mysql> SHOW TABLES; +------------------------+ | Tables_in_world_innodb | +------------------------+ | City | | CityLanguage | | City_Large | | City_part | | City_temp | | Country | | CountryLanguage | | CountryLanguage2 | | DeletedCity | +------------------------+ 9 rows in set (0.00 sec)

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 15

26. In the second terminal window, exit the mysql client and close the terminal window.

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

mysql> EXIT Bye $ exit

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 16

Practice 16-3: mysqldump

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

Overview In this practice, you use the mysqldump application to create a backup copy of the world_innodb database and then restore most of the contents to another database. To accomplish this objective: •

Back up the world_innodb database by using the mysqldump application.



Create a new database called world3.



Use the mysql client to create most of the tables that were backed up.



Use the mysqlimport command to load the backed up data into the created tables.



Verify that the tables that were backed up are the same as those that were restored from the backup into a new database.

Assumptions •

The MySQL server is installed and running.



The world_innodb database is installed.

s

an r t n

no a s ฺ Duration a h ) de This practice should take 20 minutes to complete. i m u o ฺc nt G n e Tasks e ude aattab-delimited t backup of the world_innodb w 1. Using the mysqldump application, make S @ s n database to /backups. hi a t h e ฺk/backups 2. Review the contents of rthe us directory. e e o f t − How many a *.sql efiles are located in this directory? s s ( n n ice a____________________________________________________________ h l K − How many *.txt files are located in this directory? r e ____________________________________________________________ afe

S

3. Review the contents of the Country.sql file. 4. Review the first few lines of the /backups/Country.txt file.

− Reviewing the data, what is the file format? ____________________________________________________________ 5. Using the mysqladmin client, create a new database called world3. 6. Using the mysql application, load each of the *.sql files for the Country, City, and CountryLanguage tables created in step 1 into the world3 database. 7. Using the mysqlimport application, load each of the *.txt files for the Country, City, and CountryLanguage tables created in step 1. 8. Using the mysql client, review the tables in the world3 database. 9. Review the record count for the world3.City table and world_innodb.City table to verify that they both contain the same row counts. − Is the number of rows the same for both of the tables? _________________

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 17

e

bl a r fe

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

10. Review the record count for the world3.Country, world_innodb.Country, world3.CountryLanguage, and world_innodb.CountryLanguage tables to verify that the respective tables contain the same row counts. − Is the number of rows the same for the Country tables? _________________ − Is the number of rows the same for the CountryLanguage tables? _________________ 11. Exit the mysql client session.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 18

Solutions 16-3: mysqldump Tasks

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

1. Using the mysqldump application, make a tab-delimited backup of the world_innodb database to /backups. # mysqldump -uroot -p --tab=/backups world_innodb Enter password: oracle

2. Review the contents of the /backups directory. Enter the following in a terminal window, and receive the result shown below:

S

er e f a

# ls /backups -l total 77828 -rw-r--r-- 1 root -rw-rw-rw- 1 mysql -rw-r--r-- 1 root -rw-rw-rw- 1 mysql -rw-r--r-- 1 root -rw-rw-rw- 1 mysql -rw-r--r-- 1 root -rw-r--r-- 1 root -rw-rw-rw- 1 mysql -rw-rw-rw- 1 mysql -rw-r--r-- 1 root -rw-rw-rw- 1 mysql -rw-r--r-- 1 root -rw-rw-rw- 1 mysql -rw-r--r-- 1 root -rw-rw-rw- 1 mysql -rw-r--r-- 1 root -rw-rw-rw- 1 mysql drwx------ 4 mysql

root 1469 Feb 10 16:50 CityLanguage.sql mysql 0 Feb 10 16:50 CityLanguage.txt root 1616 Feb 10 16:50 City_Large.sql mysql 79207921 Feb 10 16:51 City_Large.txt root 1610 Feb 10 16:51 City_part.sql mysql 107645 Feb 10 16:51 City_part.txt root 2620 Feb 10 16:50 City.sql root 1610 Feb 10 16:51 City_temp.sql mysql 108797 Feb 10 16:51 City_temp.txt mysql 143528 Feb 10 16:50 City.txt root 1608 Feb 10 16:51 CountryLanguage2.sql mysql 18234 Feb 10 16:51 CountryLanguage2.txt root 1702 Feb 10 16:51 CountryLanguage.sql mysql 18234 Feb 10 16:51 CountryLanguage.txt root 2038 Feb 10 16:51 Country.sql mysql 31755 Feb 10 16:51 Country.txt root 1489 Feb 10 16:51 DeletedCity.sql mysql 32 Feb 10 16:51 DeletedCity.txt mysql 4096 Feb 10 14:52 meb1

s

an r t n

o

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

− How many *.sql files are located in this directory? Nine, one for each table in the world_innodb database − How many *.txt files are located in this directory? Nine, one for each table in the world_innodb database

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 19

e

bl a r fe

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

3. Review the contents of the Country.sql file. Enter the following in a terminal window, and receive the result shown below: # more /backups/Country.sql -- MySQL dump 10.13 Distrib 5.6.10, for Linux (x86_64) --- Host: localhost Database: world_innodb -- ------------------------------------------------------- Server version 5.6.10-enterprise-commercial-advanced-log /*!40101 /*!40101 /*!40101 /*!40101 /*!40103 /*!40103 /*!40101 /*!40111

SET SET SET SET SET SET SET SET

@OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; NAMES utf8 */; @OLD_TIME_ZONE=@@TIME_ZONE */; TIME_ZONE='+00:00' */; @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='' */; @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--- Table structure for table `Country` --

S

er e f a

s

an r t n

no a DROP TABLE IF EXISTS `Country`; s ฺ */; a /*!40101 SET @saved_cs_client = @@character_set_client h ) de /*!40101 SET character_set_client = utf8m */; i u o CREATE TABLE `Country` ( ฺc nt G n e `Code` char(3) NOT NULL DEFAULT '', ate S'', `Name` char(52) NOT NULL DEFAULT ude t w `Continent` enum('Asia','Europe','North @ his n America','Africa','Oceania','Antarctica','South America') NOT NULL a h se t DEFAULT 'Asia',rฺk uNULL DEFAULT '', e tNOT `Region` fchar(26) e o a `SurfaceArea` NOT NULL DEFAULT '0.00', e sfloat(10,2) (s ensmallint(6) `IndepYear` DEFAULT NULL, n a lic int(11) NOT NULL DEFAULT '0', Kh`Population` `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; /*!40101 SET character_set_client = @saved_cs_client */; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 /*!40101 /*!40101 /*!40101 /*!40111

SET SET SET SET SET

SQL_MODE=@OLD_SQL_MODE */; CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2013-02-10 16:51:01 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 20

e

bl a r fe

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

4. Review the first few lines of the /backups/Country.txt file. Enter the following in a terminal window, and receive the result shown below: # head /backups/Country.txt 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 ...

− Reviewing the data, what is the file format? It is a tab-delimited text file 5. Using the mysqladmin client, create a new database called world3. # mysqladmin -uroot -p create world3 Enter password: oracle

s

an r t n

no a -poracle world3 < Country.sql s ฺ a h a password on the command line interface e can be ) d i m u ฺco nt G -poracle world3 < e CountryLanguage.sql n te command deline interface can be a password on a the u t w S @ s i n h -poracle world3 < City.sql ha seon tthe command line interface can be aฺk password r ee e to u f a (s ensapplication, load in each of the *.txt files for the Country, 7. Using the n mysqlimport a CountryLanguage hand lic City, tables created in step 1. Enter the following in a terminal K r e window, and receive the result shown below: fe # cd /backups # mysql -uroot Warning: Using insecure. # mysql -uroot Warning: Using insecure. # mysql -uroot Warning: Using insecure.

Sa

# mysqlimport -uroot -poracle world3 /backups/Country.txt Warning: Using a password on the command line interface can be insecure. world3.Country: Records: 239 Deleted: 0 Skipped: 0 Warnings: 0 # mysqlimport -uroot -poracle world3 /backups/CountryLanguage.txt Warning: Using a password on the command line interface can be insecure. world3.CountryLanguage: Records: 984 Deleted: 0 Skipped: 0 Warnings: 0 # mysqlimport -uroot -poracle world3 /backups/City.txt Warning: Using a password on the command line interface can be insecure. world3.City: Records: 4078 Deleted: 0 Skipped: 0 Warnings: 0

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 21

e

bl a r fe

6. Using the mysql application, load each of the *.sql files for the Country, City, and CountryLanguage tables created in step 1 into the world3 database. Enter the following in a terminal window, and receive the result shown below:

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

8. Using the mysql client, review the tables in the world3 database. Enter the following in a terminal window, and receive the result shown below: # mysql -uroot -poracle Welcome to the MySQL monitor. ... mysql> USE world3 Database changed mysql> SHOW TABLES; +------------------+ | Tables_in_world3 | +------------------+ | City | | Country | | CountryLanguage | +------------------+ 3 rows in set (0.01 sec)

Commands end with ; or \g.

e

s

bl a r fe

9. Review the record count for the world3.City table and world_innodb.City table to verify that they both contain the same row counts. Enter the following in a terminal window, and receive the result shown below:

o

an r t n

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e mysql> SELECT COUNT(*) s world_innodb.City; rฺk o uFROM +----------+ee af| se t | COUNT(*) s ( +----------+ an 4078lic|en |h er K+----------+ mysql> SELECT COUNT(*) FROM world3.City; +----------+ | COUNT(*) | +----------+ | 4078 | +----------+ 1 row in set (0.00 sec)

Sa

fe

1 row in set (0.00 sec)

− Is the number of rows the same for both of the tables? Yes

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 22

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

10. Review the record count for the world3.Country, world_innodb.Country, world3.CountryLanguage, and world_innodb.CountryLanguage tables to verify that the respective tables contain the same row counts. Enter the following in a terminal window, and receive the result shown below: mysql> SELECT COUNT(*) FROM world3.Country; +----------+ | COUNT(*) | +----------+ | 239 | +----------+ 1 row in set (0.00 sec) mysql> SELECT COUNT(*) FROM world_innodb.Country; +----------+ | COUNT(*) | +----------+ | 239 | +----------+ 1 row in set (0.00 sec)

e

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a t mysql> SELECT COUNT(*) FROM kh use world_innodb.CountryLanguage; +----------+ erฺ f|e e to | COUNT(*) a s +----------+ ( ens | an 984ic h l| K +----------+ er mysql> SELECT COUNT(*) FROM world3.CountryLanguage; +----------+ | COUNT(*) | +----------+ | 984 | +----------+ 1 row in set (0.00 sec)

fe Sa

1 row in set (0.00 sec)

− Is the number of rows the same for the Country tables? Yes

− Is the number of rows the same for the CountryLanguage tables? Yes 11. Exit the mysql client session. mysql> EXIT Bye

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 23

s

bl a r fe

Practice 16-4: Backup and Recovery Using LVM Snapshots and the Binary Log

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

Overview In this practice, you perform a complete recovery of the MySQL server data. To accomplish this objective: • Configure a logical volume (on a loop device) containing a copy of the data directory to support this practice. • Make a snapshot of the MySQL data directory. • Back up from the snapshot. • Make changes to the world_innodb database. • • •

Simulate a severe storage failure. Restore the MySQL data directory from the backup. Run the binary logs up to a certain point to recover changes made since the snapshot, and to avoid making a mistake twice.

s

an r t n

no a s ฺ • The MySQL server is installed and running. a h )directory.ide • The world_innodb.sql file is located in the /labs m u o c G ฺ t n e den Duration e t wa s Stu This practice should take 40 minutes to complete. @ n hi a t h e Tasks rฺk o us e e 1. Stop the MySQL t af server. e s s ( 2. Execute the following ncommands at a terminal window logged in as root to create a copy of ice on a loop device LVM logical volume. handataldirectory theK MySQL er dd if=/dev/zero of=/var/local/mysqldisk bs=1M count=2000 e f a Assumptions

S

losetup /dev/loop2 /var/local/mysqldisk vgcreate VG_MYSQL /dev/loop2 lvcreate -l50%VG -n lv_datadir VG_MYSQL mkfs.ext4 /dev/VG_MYSQL/lv_datadir mkdir -p /datadir mount /dev/VG_MYSQL/lv_datadir /datadir rmdir /datadir/lost+found cp -a /var/lib/mysql/* /datadir/ chown mysql:mysql /datadir

3. Create a directory called /binlogs and change the owner and group to mysql. 4. Change MySQL’s data directory setting to point to the new /datadir data directory, and set binary logging to log to the /binlogs/mysql-bin. 5. Restart MySQL. 6. Review the contents of the /binlogs directory. Is the MySQL server writing the binlogs to this directory? Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 24

e

bl a r fe

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

7. Using the mysql client from a new terminal window, drop the world_innodb database and re-create it using the /labs/world_innodb.sql file, as done in the practices for the “System Administration” lesson. 8. View the number of tables that the world_innodb database contains. How many tables does the world_innodb database contain? 9. View the processes that are running against the MySQL server by issuing the following command: SHOW PROCESSLIST;

− Are there any queries running against the server? 10. Simulate heavy traffic on the server by executing steps 9–12 in the “MySQL Enterprise Backup” practice to re-create the table City_Large. Ensure that a large slow INSERT operation is executing while you create the snapshot in the following step. Set autocommit to 0 during the insert operations to extend the duration of the transaction. 11. While the previous step is still executing, flush the MySQL logs and create an LVM snapshot of the MySQL data directory by issuing the following commands at a Terminal window logged in as root:

s

an r t n

mysqladmin -uroot -poracle flush-logs lvcreate -s -n lv_datadirbackup -L 500M /dev/VG_MYSQL/lv_datadir

no a s backฺto 1. a 12. Commit the transaction started in step 10 by setting autocommit h ) dename Sakila. i m 13. Add a new row to the City table, with the country code SWE anduthe o G ฺcthe City Confirm the insert with a suitable query. Then drop table. t n n e e e t d command, by mounting the 14. Make a backup of the snapshot contentsausing the u tar tthe w S snapshot to a local directory. When you complete backup, unmount the snapshot. @ s i n h t command: 15. Remove the snapshot by using ha the sfollowing e k ฺ r lvremove VG_MYSQL/lv_datadirbackup -f ee e to u f a 16. To simulate a(s disaster,nexecute s the following command: n e a c lvresize h li-fL 1M VG_MYSQL/lv_datadir K r e command resizes the logical volume to 1 MB, effectively destroying all data in its file afe This system.

S

17. Execute some statements in a MySQL prompt to see whether MySQL is still running, and then exit the client. 18. Attempt to shut down MySQL using the service command and using mysqladmin. 19. Verify that MySQL is running by issuing a ps command. 20. Kill the mysqld_safe process. 21. Re-execute the command in step 19 to verify that MySQL is no longer running.

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 25

e

bl a r fe

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

22. To simulate fixing the faulty file system, execute the following commands at a terminal window logged in as root to remove the broken LVM logical volume and create a new one: umount /datadir lvremove -f VG_MYSQL/lv_datadir lvcreate -l50%VG -n lv_datadir VG_MYSQL mkfs.ext4 /dev/VG_MYSQL/lv_datadir mount /dev/VG_MYSQL/lv_datadir /datadir rmdir /datadir/lost+found chown mysql:mysql /datadir

Note: These commands are similar to those in step 2, when you initially created the logical volume. You are not re-creating the volume group, the /datadir directory, or the copy of the old data directory. At the end of this step, the data directory is again empty. 23. Restore the contents of the backup taken in step 14. 24. Restart MySQL. 25. Log in to the mysql client from the terminal logged in as oracle and view the tables in the world_innodb database. Ensure that the City table exists, and establish whether the Sakila row added in step 13 exists. 26. In a terminal window, view the contents of the /binlogs directory.

s

an r t n

no a s ฺ a h − Which binlog was started after the backup was made? e ) dview i m 27. Starting with the binlog that was started after the backup was made, the contents of u o c G ฺ t n each binlog to locate the binary log that contained n that drops the City table e thedstatement e e t in the world_innodb database? tu waTABLE S @ − Which binlog contains the DROP command? s i n h a t h e − What is the position s the DROP TABLE command? rฺk containing u e e o 28. Using the data recorded f inethet preceding step, create a SQL script and execute it with the arestores s mysql client (that ns the world_innodb database up to the position of the DROP n e a c TABLE command. h li K r 29.eUsing the mysql client, view all the records in the City table of the world_innodb afe database that have an ID greater than 4070.

S

− Is the record that you added in step 13 in the City table? 30. Change MySQL’s data directory setting back to the original value, and restart MySQL to apply the changes.

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 26

e

bl a r fe

Solutions 16-4: Backup and Recovery Using LVM Snapshots and the Binary Log

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

Tasks 1. Stop the MySQL server. Execute the following at a terminal window logged in as root and receive the results shown: # service mysql stop Shutting down MySQL..

[

OK

]

2. Execute the following commands at a terminal window logged in as root to create a copy of the MySQL data directory on a loop device LVM logical volume. dd if=/dev/zero of=/var/local/mysqldisk bs=1M count=2000 losetup /dev/loop2 /var/local/mysqldisk vgcreate VG_MYSQL /dev/loop2 lvcreate -l50%VG -n lv_datadir VG_MYSQL mkfs.ext4 /dev/VG_MYSQL/lv_datadir mkdir -p /datadir mount /dev/VG_MYSQL/lv_datadir /datadir rmdir /datadir/lost+found cp -a /var/lib/mysql/* /datadir/ chown mysql:mysql /datadir

e

s

an r t n

Sa

bl a r fe

no a s ฺ a h ) de i m u o ฺc nt G n e e te the downer achange u t 3. Create a directory called /binlogs and and group to mysql. w S @ s i n # mkdir /binlogs a e th h k ฺ # chown mysql:mysql r /binlogs us e e o f t 4. Change MySQL’s setting to point to the new /datadir data directory, and stoethe /binlogs/mysql-bin. (sa datandirectory set binaryn logging toelog a hthe lic K Open /etc/my.cnf file as root, and make the following changes: r e e f [mysqld] ... log-bin=/binlogs/mysql-bin ... datadir=/datadir ...

5. Restart MySQL. Execute the following at a terminal window logged in as root and receive the results shown: # service mysql start Starting MySQL.

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 27

[

OK

]

6. Review the contents of the /binlogs directory. Enter the following in a terminal window, and receive the result shown below:

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

# ls /binlogs mysql-bin.000001

mysql-bin.index

− Is the MySQL server writing the binlogs to this directory? Yes 7. Using the mysql client from a new terminal window, drop the world_innodb database and re-create it using the /labs/world_innodb.sql file, as done in the practices for the “System Administration” lesson. $ mysql --login-path=admin Welcome to the MySQL monitor. Commands end with ; or \g. ... mysql> DROP DATABASE world_innodb; Query OK, 4 rows affected (1.45 sec) mysql> CREATE DATABASE world_innodb; Query OK, 1 row affected (0.00 sec)

S

er e f a

s

an r t n

o

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu mysql> SOURCE /labs/world_innodb.sql @ n (0.00 Query OK, 0 rows affected hi sec) a t h e rฺk o us e e Query OK, 0f rows affected (0.00 sec) t a e s s ( ... n en a SETlicautocommit=1; h mysql> K mysql> USE world_innodb Database changed mysql> SET autocommit=0; Query OK, 0 rows affected (0.00 sec)

e

bl a r fe

Query OK, 0 rows affected (0.04 sec)

8. View the number of tables that the world_innodb database contains. Enter the following in a mysql window, and receive the result shown below: mysql> SHOW TABLES; +------------------------+ | Tables_in_world_innodb | +------------------------+ | City | | Country | | CountryLanguage | +------------------------+ 3 rows in set (0.00 sec)

− How many tables does the world_innodb database contain? Three—the correct number of tables in a newly created world_innodb database.

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 28

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

9. View the processes that are running against the MySQL server by issuing the following command, and receive the result shown below: mysql> SHOW PROCESSLIST; +----+------+-----------+-----+---------+------+-------+----------------+ | Id | User | Host | db | Command | Time | State | Info | +----+------+-----------+-----+---------+------+-------+----------------+ | 2 | root | localhost | NULL| Query | 0 | NULL | SHOW PROCESSLIST| +----+------+-----------+-----+---------+------+-------+----------------+ 1 row in set (0.00 sec)

− Are there any queries running against the server? No 10. Simulate heavy traffic on the server by executing steps 9–12 in the “MySQL Enterprise Backup” practice to re-create the table City_Large. Ensure that a large slow INSERT operation is executing while you create the snapshot in the following step. Set autocommit to 0 during the insert operations to extend the duration of the transaction.

s

no a s ฺ a h ) de i m u o mysql> INSERT INTO City_Large (Name, CountryCode, District, c G District, ฺ t n n -> Population) SELECT Name, CountryCode, tee tude -> Population FROM City; a w (0.14 Ssec) @ Query OK, 4079 rows affected s i n h ha se0 t Warnings: 0 Records: 4079 Duplicates: k ฺ r ee e to u f a mysql> (SET s autocommit=0; s n n e a c Issuehthe following 6–10 times to vastly increase the number records from the li command K City_Large table and to cause traffic on the server while the snapshot is being taken. r feeUse the up arrow on your keyboard to quickly repeat the commands. mysql> CREATE TABLE City_Large LIKE City; Query OK, 0 rows affected (2.82 sec)

Sa

an r t n

mysql> INSERT INTO City_Large (Name, CountryCode, District, -> Population) SELECT Name, CountryCode, District, -> Population FROM City_Large;

11. While the previous step is still executing, flush the MySQL logs and create an LVM snapshot of the MySQL data directory by issuing the following commands at the terminal window logged in as root. Enter the following commands and receive the results shown: # mysqladmin -uroot -poracle flush-logs ; \ lvcreate -s -n lv_datadirbackup -L 500M /dev/VG_MYSQL/lv_datadir Logical volume "lv_datadirbackup" created

Note: This technique does not permit you to get the binary log position, and is therefore not suited to creating backups in some situations such as when creating a replication slave.

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 29

e

bl a r fe

12. Commit the transaction started in step 10 by setting autocommit back to 1.

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

mysql> SET autocommit=1; Query OK, 0 rows affected (0.66 sec)

13. Add a new row to the City table, with the country code SWE and the name Sakila. Confirm the insert with a suitable query. Then drop the City table. Enter the following in a mysql window, and receive the result shown below: mysql> INSERT INTO City(Name, CountryCode) VALUES ('Sakila', 'SWE'); Query OK, 1 row affected (0.11 sec) mysql> SELECT * FROM City ORDER BY ID DESC LIMIT 1; +------+--------+-------------+----------+------------+ | ID | Name | CountryCode | District | Population | +------+--------+-------------+----------+------------+ | 4080 | Sakila | SWE | | 0 | +------+--------+-------------+----------+------------+ 1 row in set (0.00 sec)

e

bl a r fe

s

an r t n

S

o n a mysql> DROP TABLE City; s ฺ a h Query OK, 0 rows affected (0.31 sec) e ) doperation. i m u o Note: These steps comes after the snapshot but ฺbefore the backup The following c G t n backup copies from the snapshot, not the liveeserver. n te thetutar decommand, by mounting the ausing 14. Make a backup of the snapshot contents w S the backup, unmount the snapshot. @ s snapshot to a local directory. When you complete i n h t prompt logged in as root: ha at asLinux Enter the following commands e k ฺ r ee e to u mkdir /root/snapshot f a (s ens mount /dev/VG_MYSQL/lv_datadirbackup /root/snapshot n a c cd h /root/snapshot li K r tar -czf /root/mysqldatadir.tgz . e e f a cd umount /root/snapshot

15. Remove the snapshot by using the following command: Enter the following commands at a Linux prompt logged in as root and receive the results shown: # lvremove VG_MYSQL/lv_datadirbackup -f Logical volume "lv_datadirbackup" successfully removed

16. To simulate a disaster, execute the following command. Enter the following command at a Linux prompt logged in as root: # lvresize -fL 1M VG_MYSQL/lv_datadir This command resizes the logical volume to the smallest physical extent (4 MB, rounded up from the specified 1 MB), effectively destroying all data in its file system.

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 30

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

17. Execute some statements in a MySQL prompt to see whether MySQL is still running, and then exit the client. mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | world3 | | world_innodb | +--------------------+ 5 rows in set (0.00 sec)

e

bl a r fe

mysql> DROP DATABASE world3; No connection. Trying to reconnect... ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

s

an r t n

Sa

no a s ฺ a mysql> EXIT h ) de i m Bye u o G it can crash sooner. Try ฺc has ncached, t n Note: Depending on how much information MySQL e e USE statements, before trying commands like STATUS and SHOW DATABASES ate Sand udseveral t w to modify a database. As soon as@ MySQL cannot is log or record changes, it crashes. n h a t Note: You might see different errors, such h se as “ERROR 2013 (HY000): Lost connection to k ฺ r MySQL server duringequery” or “ERROR 2006 (HY000): MySQL server has gone away.” u eoperating o f t You might also see system messages such as “kernel:journal commit I/O error”, a esystem problems caused s s ( referring to the serious file by shrinking the volume. n n ice a h l 18. Attempt K to shut down MySQL using the service command and using mysqladmin. r e fe Enter the following commands at a Linux prompt logged in as root: # service mysql stop MySQL server process #17951 is not running! [FAILED] rm: cannot remove `/datadir/.pid': Read-only file system # mysqladmin -uroot -poracle shutdown mysqladmin: connect to server at 'localhost' failed error: 'Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)' Check that mysqld is running and that the socket: '/var/lib/mysql/mysql.sock' exists!

Note: You have simulated a serious hard-disk failure, so the error message can differ from that shown.

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 31

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

19. Verify that MySQL is running by issuing a ps command. Enter the following commands at a Linux prompt logged in as root: # ps ax | grep mysqld 17738 pts/2 S 2:11 /bin/sh /usr/bin/mysqld_safe -datadir=/datadir --pid-file=/datadir/.pid 17846 pts/2 R 0:00 /usr/sbin/mysqld --basedir=/usr -datadir=/datadir --plugin-dir=/usr/lib64/mysql/plugin --user=mysql -log-error=/var/log/mysqld.log --pid-file=/datadir/.pid -socket=/var/lib/mysql/mysql.sock 17849 pts/2 S+ 0:00 grep mysqld

MySQL is still running because it is restarted by the mysqld_safe script every time it crashes. If you run this statement multiple times, you will note that sometimes mysqld is running and sometimes it is not. 20. Kill the mysqld_safe process. Enter the following commands at a Linux prompt logged in as root:

ns a r t 21. Re-execute the command in step 19 to verify that MySQL is no longer running. n o Enter the following commands at a Linux prompt logged in as root: an s # ps ax | grep mysqld ha deฺ ) 11528 pts/2 S+ 0:00 grep mysqld om ui c G ฺ MySQL is no longer running. en dent e t a Sthe 22. To simulate fixing the faulty file system, execute tufollowing commands at a terminal w window logged in as root to remove the broken LVM logical volume and create a new one: @ s i n h a t umount /datadir ฺkh e s r u e lvremove -ffe VG_MYSQL/lv_datadir o tlv_datadir a e s lvcreate -l50%VG -n VG_MYSQL ( ens n mkfs.ext4 c i/dev/VG_MYSQL/lv_datadir ha l K /dev/VG_MYSQL/lv_datadir /datadir er mount e f rmdir /datadir/lost+found a # killall -9 mysqld_safe

S

chown mysql:mysql /datadir

Note: These commands are similar to those in step 2, when you initially created the logical volume. You are not re-creating the volume group, the /datadir directory, or the copy of the old data directory. At the end of this step, the data directory is again empty. 23. Restore the contents of the backup taken in step 14. Enter the following commands at a Linux prompt logged in as root: # cd /datadir # tar -xzf /root/mysqldatadir.tgz

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 32

e

bl a r fe

24. Restart MySQL. Execute the following at a terminal window logged in as root and receive the results shown:

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

# service mysql start Starting MySQL....

[

OK

]

Were you able to start the MySQL server? Yes Note: The start operation can take some time if you created the snapshot during a period of heavy activity, because InnoDB needs to perform recovery when starting after an abnormal shutdown, and a snapshot of a running system is indistinguishable from a power cut or other crash. 25. Log in to the mysql client from the terminal logged in as oracle and view the tables in the world_innodb database. Ensure that the City table exists, and establish whether the Sakila row added in step 12 exists.

s

$ mysql --login-path=admin Welcome to the MySQL monitor. Commands end with ; or \g. ... mysql> USE world_innodb Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A

an r t n

o

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e Database changed t wa sBYSIDtuDESC LIMIT 1; mysql> SELECT * FROM City ORDER @ n hi +------+-------+-------------+----------+------------+ a t h e | ID | Name r|ฺk us | District | Population | e CountryCode e o f t +------+-------+-------------+----------+------------+ a se s ( | 4079 | | Rafah | 92020 | n| PSE n Rafah e a c i h l K+------+-------+-------------+----------+------------+ 1 row in set (0.00 sec)

The City table exists, but the Sakila row does not, because the backup came from a snapshot that was taken before you created the row and dropped the City table. You can use the binary log to recover changes made since taking the backup. 26. In a terminal window, view the contents of the /binlogs directory. Enter the following in a terminal window, and receive the result shown below: # ls /binlogs -l total 856 -rw-rw---- 1 mysql -rw-rw---- 1 mysql -rw-rw---- 1 mysql -rw-rw---- 1 mysql

mysql 863061 Feb 11 05:09 mysql 940 Feb 11 05:42 mysql 120 Feb 11 05:42 mysql 78 Feb 11 05:42

mysql-bin.000001 mysql-bin.000002 mysql-bin.000003 mysql-bin.index

− Which binlog was started after the backup was made? mysql-bin.000002

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 33

e

bl a r fe

Enter the following in a terminal window, and receive the result shown below:

27. Starting with the first binlog created after the snapshot, view the contents of each binlog to locate the binary log containing the statement that drops the City table in the world_innodb database? Enter the following in a terminal window, and receive the result shown below:

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

# mysqlbinlog /binlogs/mysql-bin.000002 | more /*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/; /*!40019 SET @@session.max_insert_delayed_threads=0*/; /*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/; DELIMITER /*!*/; # at 4 #130211 5:09:50 server id 1 end_log_pos 120 CRC32 0xc405eb90 Start: binlog v 4, server v 5.6 .10-enterprise-commercial-advanced-log created 130211 5:09:50 BINLOG ' Hn0YUQ8BAAAAdAAAAHgAAAAAAAQANS42LjEwLWVudGVycHJpc2UtY29tbWVyY2lhbC1hZH ZhbmNl ZC1sb2cAAAAAAAAAAAAAAAAAEzgNAAgAEgAEBAQEEgAAXAAEGggAAAAICAgCAAAACgoKGR kAAZDr BcQ= '/*!*/; # at 120 #130211 5:09:36 server id 1 end_log_pos 215 CRC32 0xa312ddd4 Query thread_id=3 exec_ti me=28 error_code=0 SET TIMESTAMP=1360559376/*!*/; SET @@session.pseudo_thread_id=3/*!*/; SET @@session.foreign_key_checks=1, @@session.sql_auto_is_null=0, @@session.unique_checks=1, @@ session.autocommit=1/*!*/; SET @@session.sql_mode=1075838976/*!*/; SET @@session.auto_increment_increment=1, @@session.auto_increment_offset=1/*!*/; /*!\C utf8 *//*!*/; SET @@session.character_set_client=33,@@session.collation_connection=33,@@ session.collation_ser ver=8/*!*/; SET @@session.lc_time_names=0/*!*/; SET @@session.collation_database=DEFAULT/*!*/; BEGIN /*!*/; # at 215 # at 247 #130211 5:09:36 server id 1 end_log_pos 247 CRC32 0x3fd40695 Intvar SET INSERT_ID=524277/*!*/; #130211 5:09:36 server id 1 end_log_pos 468 CRC32 0xccb3fceb Query thread_id=3 exec_ti

s

o

an r t n

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 34

e

bl a r fe

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

me=28 error_code=0 use `world_innodb`/*!*/; SET TIMESTAMP=1360559376/*!*/; INSERT INTO City_Large (Name, CountryCode, District, Population) SELECT Name, CountryCode, District, Population FROM City_Large /*!*/; # at 468 #130211 5:09:36 server id 1 end_log_pos 499 CRC32 0x5c1a7c2e 5572 COMMIT/*!*/; # at 499 #130211 5:12:46 server id 1 end_log_pos 594 CRC32 0xc74b18b0 thread_id=3 exec_ti me=0 error_code=0 SET TIMESTAMP=1360559566/*!*/; BEGIN /*!*/; # at 594 # at 626 #130211 5:12:46 server id 1 end_log_pos 626 CRC32 0x36ec76bb SET INSERT_ID=4080/*!*/; #130211 5:12:46 server id 1 end_log_pos 776 CRC32 0xdaffdd6e thread_id=3 exec_ti me=0 error_code=0 SET TIMESTAMP=1360559566/*!*/; INSERT INTO City(Name, CountryCode) VALUES ('Sakila', 'SWE') /*!*/; # at 776 #130211 5:12:46 server id 1 end_log_pos 807 CRC32 0x0deff828 5626 COMMIT/*!*/; # at 807 #130211 5:13:01 server id 1 end_log_pos 940 CRC32 0xce845fd6 thread_id=3 exec_ti me=2 error_code=0 SET TIMESTAMP=1360559581/*!*/; DROP TABLE `City` /* generated by server */ /*!*/; DELIMITER ; # End of log file ROLLBACK /* added by mysqlbinlog */; /*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/; /*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;

Xid =

Query

e

bl a r fe

s

an r t n

o

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

Intvar Query

Xid =

Query

− Which binlog contains the DROP TABLE command? mysql-bin.000002 − What is the position containing the DROP TABLE command? The DROP TABLE command happens at position 807. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 35

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

Note: These values may differ on your system. 28. Using the data recorded in the preceding step, create a SQL script and execute it with the mysql client that restores the world_innodb database up to the position of the DROP TABLE command. # cd /binlogs # mysqlbinlog --disable-log-bin --stop-position=807 \ mysql-bin.000002 | mysql -uroot -poracle 29. Using the mysql client, view all the records in the City table of the world_innodb database that have an ID greater than 4070. Enter the following in a terminal window, and receive the result shown below: mysql> SELECT * FROM world_innodb.City WHERE ID > 4070; +------+--------------+-------------+------------+------------+ | ID | Name | CountryCode | District | Population | +------+--------------+-------------+------------+------------+ | 4071 | Mount Darwin | ZWE | Harare | 164362 | | 4072 | Mutare | ZWE | Manicaland | 131367 | | 4073 | Gweru | ZWE | Midlands | 128037 | | 4074 | Gaza | PSE | Gaza | 353632 | | 4075 | Khan Yunis | PSE | Khan Yunis | 123175 | | 4076 | Hebron | PSE | Hebron | 119401 | | 4077 | Jabaliya | PSE | North Gaza | 113901 | | 4078 | Nablus | PSE | Nablus | 100231 | | 4079 | Rafah | PSE | Rafah | 92020 | | 4080 | Sakila | SWE | | 1 | +------+--------------+-------------+------------+------------+ 10 rows in set (0.00 sec)

e

s

an r t n

Sa

bl a r fe

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a t 1 in the City table? Yes. h addedsine step − Is the record thatฺk you r u back to the original value, and restart MySQL to 30. Change MySQL’s fdata setting eedirectory o t a apply the changes. (s ense n Execute hathe following lic at a terminal window logged in as root and receive the results shown: K r # service mysql stop fee Shutting down MySQL..

[

OK

]

Open the /etc/my.cnf file as root, and make the following change: [mysqld] ... datadir=/var/lib/mysql ...

After saving the preceding changes, enter the following in a terminal window, and receive the result shown below: # service mysql start Starting MySQL.

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

Practices for Lesson 16: MySQL Backup and Recovery Chapter 16 - Page 36

[

OK

]

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

e

s

bl a r fe

an r t n

er e f a

no a s ฺ 17: a Practices for Lesson h ) de i m Replication u o ฺc nt G n e e u17de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 17: Replication Chapter 17 - Page 1

Practices for Lesson 17: Overview

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

Practices Overview In these practices, you test your knowledge of replication. The hands-on practices are written for the Oracle Linux operating system environment, which is provided in Oracle classrooms. For non-Oracle classrooms, some adjustments may need to be made regarding file locations.

Assumptions • •

The MySQL server installation has been completed prior to these practices. The MySQL Utilities are installed.



The file /labs/repl.cnf exists, with contents as shown in the second practice.



You are logged in as root user in a terminal window.



You can access the mysql client from a command line prompt.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 17: Replication Chapter 17 - Page 2

Practice 17-1: Quiz – Replication Overview

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

In this practice, you answer questions about replication.

Duration This practice should take approximately five minutes to complete.

Quiz Questions Choose the best answer from those provided for each multiple choice or True/False question. 1. Which of the following is true concerning MySQL master servers? a. There is no limit on the number of slaves a single master can have. b. It is possible for a slave to have a different MySQL version from the master. c. It is common to limit the number of slaves to less than 30 in most production setups. d. All of the above 2. At its simplest, MySQL replication works through a one-way, log-shipping, asynchronous mechanism, making it a master-slave relationship. a. True b. False 3. Which of the following is a common use for replication? a. Scale-out solutions b. High availability c. Analytics d. All of the above 4. MySQL replication uses a log-shipping system in which all data changes that occur on the master are stored in a log and then retrieved by the slave and executed from these received log files. What is the name of this log file in MySQL? a. Slave log b. Master log c. Binary log d. Error log 5. Slaves need to be connected permanently to receive updates from the master. a. True b. False 6. What is a disadvantage to using statement-based replication? a. Disk space usage and bandwidth requirements for replication are larger. b. Replication occurs on the row level. c. Some functions might not replicate correctly to a remote server of a different version. d. None of the above

s

o

an r t n

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

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

Practices for Lesson 17: Replication Chapter 17 - Page 3

e

bl a r fe

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

7. Which thread is responsible for downloading the binary logs from the master into a local file set called the relay logs? a. BINARY_THREAD b. IO_THREAD c. SQL_THREAD d. MASTER_THREAD

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 17: Replication Chapter 17 - Page 4

Solutions 17-1: Quiz – Replication

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

Quiz Solutions 1. 2. 3. 4. 5.

d. All of the above a. True d. All of the above c. Binary log b. False. Slaves do not need to be connected permanently to receive updates from the master. 6. c. Some functions might not replicate correctly to a remote server of a different version. 7. b. IO_THREAD

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 17: Replication Chapter 17 - Page 5

Practice 17-2: Configuring Replication Overview

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

In this practice, you start four server instances of MySQL, configure one server as a slave of another, create some data on the master, and see that it replicates to the slave.

Assumptions The MySQL server is installed, and the file /labs/repl.cnf exists and has contents as shown in the solution to step 2 of this practice.

Duration This practice should take approximately 10 minutes to complete.

Tasks

Sa

e

bl a r fe

1. 2. 3.

Stop the MySQL server. View the contents of the file /labs/repl.cnf. Using mysqld_multi, start the four servers defined in /labs/repl.cnf.

4.

In a new terminal window, use the mysql client to connect to the first server as root, and set the prompt to “1> ”. Note: For the sake of simplicity and brevity in a training environment, the four servers do not have a root password. Execute a query to find the log coordinates of the first server. On the first server, create a user called repl, with the password oracle, and grant that user the REPLICATION SLAVE permission.

s

an r t n

no a s ฺ a h ) de i m u o 5. ฺc nt G n e 6. ate Stude w @ his database from script, as you did in the n 7. On the first server, create the world_innodb a h se t lesson. k ฺ practices for the “System Administration” r ee totheu mysql client to connect to the second server as root, f 8. In a new terminal window,euse a s ”. (s eton“2> and set the prompt n a c li window, issue a CHANGE MASTER TO… command to configure the 9. In thehsecond mysql K r feesecond server as a slave of the first, using the log coordinates noted in step 5 and the user 10. 11. 12. 13.

created in step 6. Display the text of any warnings generated. Display the databases that exist on the second server. Start the slave threads on the second server. Show the processes on the first and second server. Display the databases on the second server again. Note the differences.

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

Practices for Lesson 17: Replication Chapter 17 - Page 6

Solutions 17-2: Configuring Replication Tasks

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

1.

Stop the MySQL server. Enter the following at a terminal logged in as root, and receive the results shown: # service mysql stop Shutting down MySQL..

2.

OK

]

View the contents of the file /labs/repl.cnf. Enter the following at a terminal logged in as root, and receive the results shown:

er e f a

S

[

# cat /labs/repl.cnf [mysqld1] datadir=/var/lib/mysql1 port=3311 socket=/var/lib/mysql1/mysql.sock server-id=1 user=mysql log-bin=mysql1-bin relay-log=mysql1-relay-bin log-slave-updates log-error=mysql1 report-host=localhost report-port=3311 relay-log-recovery=1 master-info-repository=TABLE relay-log-info-repository=TABLE # gtid-mode=ON # enforce-gtid-consistency

e

s

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

Practices for Lesson 17: Replication Chapter 17 - Page 7

an r t n

o

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K [mysqld2] datadir=/var/lib/mysql2 port=3312 socket=/var/lib/mysql2/mysql.sock server-id=2 user=mysql log-bin=mysql2-bin relay-log=mysql2-relay-bin log-slave-updates log-error=mysql2 report-host=localhost report-port=3312 relay-log-recovery=1 master-info-repository=TABLE relay-log-info-repository=TABLE # gtid-mode=ON # enforce-gtid-consistency

bl a r fe

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

[mysqld3] datadir=/var/lib/mysql3 port=3313 socket=/var/lib/mysql3/mysql.sock server-id=3 user=mysql log-bin=mysql3-bin relay-log=mysql3-relay-bin log-slave-updates log-error=mysql3 report-host=localhost report-port=3313 relay-log-recovery=1 master-info-repository=TABLE relay-log-info-repository=TABLE # gtid-mode=ON # enforce-gtid-consistency

S

er e f a

e

s

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

Practices for Lesson 17: Replication Chapter 17 - Page 8

an r t n

o

an s ha deฺ [mysqld4] ) om Gui datadir=/var/lib/mysql4 c ฺ en dent port=3314 e t socket=/var/lib/mysql4/mysql.sock wa s Stu @ server-id=4 n hi a t h user=mysql e rฺk o us e log-bin=mysql4-bin e af se t s relay-log=mysql4-relay-bin ( an licen log-slave-updates h K log-error=mysql4 report-host=localhost report-port=3314 relay-log-recovery=1 master-info-repository=TABLE relay-log-info-repository=TABLE # gtid-mode=ON # enforce-gtid-consistency

bl a r fe

3.

Using mysqld_multi, start the four servers defined in /labs/repl.cnf. Enter the following at a terminal logged in as root, and receive the results shown: # mysqld_multi --defaults-file=/labs/repl.cnf start 1-4

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

Installing new database in /var/lib/mysql1 Installing MySQL system tables...2012-12-16 13:08:17 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use -explicit_defaults_for_timestamp server option (see documentation for more details). 2012-12-16 13:08:17 6876 [Note] InnoDB: The InnoDB memory heap is disabled 2012-12-16 13:08:17 6876 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins 2012-12-16 13:08:17 6876 [Note] InnoDB: Compressed tables use zlib 1.2.3 2012-12-16 13:08:17 6876 [Note] InnoDB: CPU does not support crc32 instructions 2012-12-16 13:08:17 6876 [Note] InnoDB: Using Linux native AIO 2012-12-16 13:08:17 6876 [Note] InnoDB: Initializing buffer pool, size = 128.0M 2012-12-16 13:08:17 6876 [Note] InnoDB: Completed initialization of buffer pool 2012-12-16 13:08:17 6876 [Note] InnoDB: The first specified data file ./ibdata1 did not exist: a new database to be created! ...

s

an r t n

Sa

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a t ฺkhfour userver se instances with the settings stored in Note: This commandestarts r o the servers start, the process creates data directories as feThe first ttime /labs/repl.cnf. a e s ( options specified n in the nsfor each server. e a c h terminalli window, use the mysql client to connect to the first server as root, and 4. In K a new r feeset the prompt to “1> ”. Note: For the sake of simplicity and brevity in a training environment, the four servers do not have a root password. Enter the following at a new terminal, and receive the results shown:

$ mysql -uroot -h127.0.0.1 -P3311 Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 1 ... mysql> PROMPT 1> ; PROMPT set to '1> '

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

Practices for Lesson 17: Replication Chapter 17 - Page 9

e

bl a r fe

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

5.

Execute a query to find the log coordinates of the first server. In the mysql prompt created in the preceding step, enter the following command and receive the results shown: 1> SHOW MASTER STATUS \G *************************** 1. row *************************** File: mysql-bin.000001 Position: 120 Binlog_Do_DB: Binlog_Ignore_DB: Executed_Gtid_Set: 1 row in set (0.00 sec)

Note that the log file is mysql-bin.000001 and the log position is 120. 6.

On the first server, create a user called repl, with the password oracle, and grant that user the REPLICATION SLAVE permission.

s

In the mysql prompt used in the preceding step, enter the following command and receive the results shown:

an r t n

no a s ฺ a h ) de i m 1> GRANT REPLICATION SLAVE ON *.* TO 'repl'@'127.0.0.1'; u o ฺc nt G n Query OK, 0 rows affected (0.00 sec) e e ate Sdatabase 7. On the first server, create the world_innodb tud from script, as you did in the w @ hlesson. practices for the “System Administration” is n a t e step, enter the following command and receive In the mysql prompt used ฺkhin theupreceding s r e the results shown:fe to a e s s world_innodb; 1> CREATE ( DATABASE n n e a c Query h OK,li1 row affected (0.00 sec) K r fee 1> CREATE USER 'repl'@'127.0.0.1' IDENTIFIED BY 'oracle'; Query OK, 0 rows affected (0.00 sec)

Sa

1> USE world_innodb Database changed 1> SET autocommit=0; Query OK, 0 rows affected (0.00 sec) 1> SOURCE /labs/world_innodb.sql Query OK, 1 row affected (0.00 sec) Query OK, 1 row affected (0.00 sec) ... 1> SET autocommit=1; Query OK, 0 rows affected (0.06 sec)

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

Practices for Lesson 17: Replication Chapter 17 - Page 10

e

bl a r fe

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

8.

In a new terminal window, use the mysql client to connect to the second server as root, and set the prompt to “2> ”. Enter the following at a new terminal, and receive the results shown: $ mysql -uroot -h127.0.0.1 -P3312 Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 1 ... mysql> PROMPT 2> ; PROMPT set to '2> '

9.

In the second mysql window, issue a CHANGE MASTER TO… command to configure the second server as a slave of the first, using the log coordinates noted in step 5 and the user created in step 6. Display the text of any warnings generated. In the mysql prompt created in the preceding step, enter the following command and receive the results shown: 2> CHANGE MASTER TO -> MASTER_HOST='127.0.0.1', -> MASTER_PORT=3311, -> MASTER_LOG_FILE='mysql1-bin.000001', -> MASTER_LOG_POS=120, -> MASTER_USER='repl', -> MASTER_PASSWORD='oracle'; Query OK, 0 rows affected, 2 warnings (0.51 sec)

Sa

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his 2> SHOW WARNINGS\G an h se 1.t row *************************** k ฺ r *************************** ee e to u f Level: a Note (s 1759ens Code: n ha lic Message: Sending passwords in plain text without SSL/TLS is extremely K er insecure.

fe

*************************** 2. row *************************** Level: Note Code: 1760 Message: Storing MySQL user name or password information in the master.info repository is not secure and is therefore not recommended. Please see the MySQL Manual for more about this issue and possible alternatives. 2 rows in set (0.00 sec)

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

Practices for Lesson 17: Replication Chapter 17 - Page 11

e

bl a r fe

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

10. Display the databases that exist on the second server. In the mysql prompt used in the preceding step, enter the following command and receive the results shown: 2> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | test | +--------------------+ 4 rows in set (0.00 sec)

s

no a s ฺ a h 12. Show the processes on the first and second server. ide the results shown: m) andureceive o a. In the first mysql prompt, issue the following c command G ฺ t n n e 1> SHOW PROCESSLIST\G e aterowS*************************** tud *************************** 1. w @ his Id: 1 n a h se t User: root k ฺ r Host: localhost:35112 ee e to u f a s db: (s world_innodb n n e a c Command: Query h li K r Time: 0 fee 2> START SLAVE; Query OK, 0 rows affected (0.05 sec)

Sa

an r t n

State: init Info: SHOW PROCESSLIST *************************** 2. row *************************** Id: 2 User: repl Host: localhost:35115 db: NULL Command: Binlog Dump Time: 1944 State: Master has sent all binlog to slave; waiting for binlog to be updated Info: NULL 2 rows in set (0.00 sec)

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

Practices for Lesson 17: Replication Chapter 17 - Page 12

e

bl a r fe

11. Start the slave threads on the second server. In the mysql prompt used in the preceding step, enter the following command and receive the results shown:

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

b.

S

er e f a

In the second mysql prompt, issue the following command and receive the results shown: 2> SHOW PROCESSLIST\G *************************** Id: 1 User: root Host: localhost:39075 db: NULL Command: Query Time: 0 State: init Info: SHOW PROCESSLIST *************************** Id: 2 User: system user Host: db: NULL Command: Connect Time: 1811 State: Waiting for master Info: NULL *************************** Id: 3 User: system user Host: db: NULL Command: Connect Time: 2311 State: Slave has read all thread to update it Info: NULL 3 rows in set (0.00 sec)

1. row ***************************

2. row ***************************

e

s

bl a r fe

an r t n

no a s ฺ a h to send event ) de i m u o ฺc nt G n*************************** e 3. e row at Stude w @ his n a h se t k ฺ r ee e to u f a (s ens n a lic Kh

relay log; waiting for the slave I/O

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

Practices for Lesson 17: Replication Chapter 17 - Page 13

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

13. Display the databases on the second server again. Note the differences. In the mysql prompt used in the preceding step, enter the following command and receive the results shown: 2> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | test | | world_innodb | +--------------------+ 5 rows in set (0.00 sec)

Sa

e

bl a r e The world_innodb database is in the list, because it was created on the first serverfafter s n you noted the log coordinates in step 5. The slave process on the second server replicated tradatabase, every change after those coordinates, including all data in the world_innodb n no and the user created in step 6. a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a h se t k ฺ r ee e to u f a (s ens n ha lic K r fee

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

Practices for Lesson 17: Replication Chapter 17 - Page 14

Practice 17-3: Adding a New Slave Overview

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

In this practice, you provision a new server as a new slave of the existing slave (using mysqldump), change some data on the master, and see that it replicates to both slaves.

Assumptions You have successfully carried out the steps in Practice 17-2.

Duration This practice should take approximately 10 minutes to complete.

Tasks 1. 2. 3. 4. 5. 6. 7.

Using mysqldump, take a backup of the world_innodb database on the second server, including the information needed to create and use the database, and configure a slave. Edit the backup file created in the preceding step to change the CHANGE MASTER TO … line so that it points to the second server, and is uncommented. Connect to the third server using the mysql client, and set the prompt to “3> ”. Apply the backup taken in step 1 and altered in step 2 to the third server. Start the slave process on the third server, and display the slave status. Delete all rows where the ID is greater than 4070 from the City table on the first server, and ensure that the changes replicate to the second and third servers. To prepare for the following practice, create a user on the third server called repl, with the password oracle, and grant that user the REPLICATION SLAVE permission.

er e f a

s

o

an r t n

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 17: Replication Chapter 17 - Page 15

e

bl a r fe

Solutions 17-3: Adding a New Slave Tasks

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

1.

Using mysqldump, take a backup of the world_innodb database on the second server, including the information needed to create and use the database, and configure a slave. Enter the following at a terminal window, and receive the results shown: $ mysqldump -uroot -h127.0.0.1 -P3312 --master-data=2 \ -B world_innodb > /tmp/server2.sql

2.

Edit the backup file created in the preceding step to change the CHANGE MASTER TO … line so that it points to the second server, and is uncommented. a. Using an editor such as gedit, open the /tmp/server2.sql file and locate the following line:

e

bl a r fe

-- CHANGE MASTER TO MASTER_LOG_FILE='mysql2-bin.000001', MASTER_LOG_POS=860071;

b.

s

Change that line as follows:

an r t n

CHANGE MASTER TO MASTER_HOST='127.0.0.1', MASTER_PORT=3312, MASTER_USER='repl', MASTER_PASSWORD='oracle', MASTER_LOG_FILE='mysql2-bin.000001', MASTER_LOG_POS=860071;

Sa

no a s ฺ a h )in your output, Note that the log coordinates may differ from that shown de and that the i m u o replication user on the second server was originally created on the c G first server and ฺ t n n replicated in the preceding practice. e de ateclient, tuand set the prompt to “3> ”. 3. Connect to the third server using the w mysql S @ s n window, Enter the following at a new terminal hi and receive the results shown: a t h e ฺk us -P3313 $ mysql -uroot r-h127.0.0.1 e e fthe MySQL tomonitor. Commands end with ; or \g. Welcome to a e s ( connection YournMySQL id is 1 ns e a c i h l ... Kmysql> PROMPT 3> ; r e fe PROMPT set to '3> '

4.

Apply the backup taken in step 1 and altered in step 2 to the third server. In the mysql prompt created in the preceding step, enter the following command and receive the results shown: 3> SOURCE /tmp/server2.sql Query OK, 0 rows affected (0.00 sec) Query OK, 0 rows affected (0.00 sec) Query OK, 0 rows affected (0.00 sec) ...

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

Practices for Lesson 17: Replication Chapter 17 - Page 16

5.

Start the slave process on the third server, and display the slave status. In the mysql prompt used in the preceding step, enter the following commands and receive the results shown:

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

3> START SLAVE; Query OK, 0 rows affected (0.05 sec) 3> SHOW SLAVE STATUS\G *************************** 1. Slave_IO_State: Master_Host: Master_User: Master_Port: Connect_Retry: Master_Log_File: Read_Master_Log_Pos: Relay_Log_File: Relay_Log_Pos: Relay_Master_Log_File: Slave_IO_Running: Slave_SQL_Running: Replicate_Do_DB: ...

row *************************** Waiting for master to send event 127.0.0.1 repl 3312 60 mysql2-bin.000001 860071 mysql3-relay-bin.000002 284 mysql2-bin.000001 Yes Yes

e

bl a r fe

s

an r t n

S

no a s ฺ a h ) de i m u o ฺc nt G n e te tude a w 6. Delete all rows where the ID is greater 4070 S from the City table on the first server, @ tothan s i n and ensure that the changesa replicate the second and third servers. h t h e k ฺ s a. On the first server, command and receive the results shown: erentertotheufollowing e f 1> DELETEaFROM world_innodb.City WHERE ID > 4070; e s s ( n Query an OK,li9cerows affected (0.05 sec) h K b. r On the second server, enter the following command and receive the results shown: e e 2> SELECT * FROM world_innodb.City ORDER BY Id DESC LIMIT 5; af +------+------------------+-------------+----------------+------------+ | ID | Name | CountryCode | District | Population | +------+------------------+-------------+----------------+------------+ | 4070 | Chitungwiza | ZWE | Harare | 274912 | | 4069 | Bulawayo | ZWE | Bulawayo | 621742 | | 4068 | Harare | ZWE | Harare | 1410000 | | 4067 | Charlotte Amalie | VIR | St Thomas | 13000 | | 4066 | Charleston | USA | South Carolina | 89063 | +------+------------------+-------------+----------------+------------+ 5 rows in set (0.00 sec)

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

Practices for Lesson 17: Replication Chapter 17 - Page 17

c.

On the third server, enter the following command and receive the results shown:

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

3> SELECT * FROM world_innodb.City ORDER BY Id DESC LIMIT 5; +------+------------------+-------------+----------------+------------+ | ID | Name | CountryCode | District | Population | +------+------------------+-------------+----------------+------------+ | 4070 | Chitungwiza | ZWE | Harare | 274912 | | 4069 | Bulawayo | ZWE | Bulawayo | 621742 | | 4068 | Harare | ZWE | Harare | 1410000 | | 4067 | Charlotte Amalie | VIR | St Thomas | 13000 | | 4066 | Charleston | USA | South Carolina | 89063 | +------+------------------+-------------+----------------+------------+ 5 rows in set (0.00 sec)

7.

To prepare for the following practice, create a user on the third server called repl, with the password oracle, and grant that user the REPLICATION SLAVE permission. In the mysql prompt used in the preceding step, enter the following command and receive the results shown:

s

an r t n

3> CREATE USER 'repl'@'127.0.0.1' IDENTIFIED BY 'oracle'; Query OK, 0 rows affected (0.00 sec)

Sa

no a s ฺ a h 3> GRANT REPLICATION SLAVE ON *.* TO 'repl'@'127.0.0.1'; ) de i Query OK, 0 rows affected (0.00 sec) om u G t nฺc having n e At this point, the repl user exists on threee servers, been created on the first server, e t on thetuthird. d a replicated to the second, and finally created w sS @ n hi a t h e rฺk o us e e af se t s ( an licen h K r e fe

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

Practices for Lesson 17: Replication Chapter 17 - Page 18

e

bl a r fe

Practice 17-4: Enabling GTID and Configuring Circular Replication Overview

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

In this practice, you enable GTID on the three servers, connect the master so that it becomes a slave of the second slave, and test the newly created circular topology by changing some data.

Assumptions You have successfully carried out the steps in Practice 17-3.

Duration This practice should take approximately 10 minutes to complete.

Tasks 1. 2. 3. 4. 5.

s

bl a r fe

an r t n

Using mysqld_multi, start all four servers. Stop the slaves. Issue a RESET MASTER command on each server so that the log files contain only events that use GTIDs. 6. Issue an appropriate CHANGE MASTER TO… command on the slaves to use the GTID replication protocol. 7. Restart the slaves. 8. Delete all rows where the ID is greater than 4060 from the City table on the first server, and ensure that the changes replicate to the second and third servers. 9. Note the server UUIDs for the first, second, and third servers. 10. On the third server, view the slave status. 11. Issue an appropriate CHANGE MASTER TO… statement on the first server, configuring it as a slave to the third server, and start the slave threads. 12. Delete all rows where the ID is greater than 4050 from the City table on the second server, and ensure that the changes replicate to the first and third servers.

er e f a

S

e

Using mysqld_multi, stop all four servers. Edit the /labs/repl.cnf file to uncomment all commented lines.

o

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

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

Practices for Lesson 17: Replication Chapter 17 - Page 19

Solutions 17-4: Enabling GTID and Configuring Circular Replication Tasks Note: Execute all Linux terminal commands in this practice at a prompt logged in as root.

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

1.

Using mysqld_multi, stop all four servers. Enter the following at a terminal window: # mysqld_multi --defaults-file=/labs/repl.cnf --user=root stop 1-4

2.

Edit the /labs/repl.cnf file to uncomment all commented lines. a.

Using an editor such as gedit, open the /labs/repl.cnf file and find all commented lines: # gtid-mode=ON # enforce-gtid-consistency

b.

e

bl a r fe

Remove the comments, as follows:

s

gtid-mode=ON enforce-gtid-consistency

an r t n

no a s ฺ a h 3. ) de i m u o ฺc nt Gstart 1-4 n e # mysqld_multi --defaults-file=/labs/repl.cnf te tude athe w Note that the command does not create data S directories (as in a previous practice), because they already exist. an@ this ฺkh use 4. Stop the slaves. r e feserver,eenter to the following command and receive the results shown: a. On the second a s ( ens 2> STATUS n a h 2013lic(HY000): Lost connection to MySQL server during query ERROR K r fee 2> STOP SLAVE; c.

Repeat for all such commented lines (one pair for each server option group) and save and close the file. Using mysqld_multi, start all four servers. Enter the following at a terminal window:

Sa

ERROR 2006 (HY000): MySQL server has gone away No connection. Trying to reconnect... Connection id: 2 Current database: world_innodb Query OK, 0 rows affected (0.15 sec)

b.

On the third server, enter the following command and receive the results shown: 3> STATUS ERROR 2013 (HY000): Lost connection to MySQL server during query 3> STOP SLAVE; ERROR 2006 (HY000): MySQL server has gone away No connection. Trying to reconnect... Connection id: 2 Current database: world_innodb Query OK, 0 rows affected (0.12 sec) Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 17: Replication Chapter 17 - Page 20

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

5.

Issue a RESET MASTER command on each server so that the log files contain only events that use GTIDs. a. In the first server connection, issue any command (for example, STATUS) to reconnect, and then reset the master settings, as follows: 1> STATUS ERROR 2013 (HY000): Lost connection to MySQL server during query 1> RESET MASTER; ERROR 2006 (HY000): MySQL server has gone away No connection. Trying to reconnect... Connection id: 2 Current database: world_innodb Query OK, 0 rows affected (0.21 sec)

b.

2> RESET MASTER; Query OK, 0 rows affected (0.21 sec)

Sa

s

an r t n

o n a c. In the third server connection, issue the following command and receive the result s ฺ a shown: h ) de i m 3> RESET MASTER; u o ฺc nt G Query OK, 0 rows affected (0.22 sec) n e te command deon the slaves to use the GTID aTO… 6. Issue an appropriate CHANGE MASTER u t w S @ replication protocol. s i n h t the following command and receive the result ha seissue a. In the second server connection, k ฺ r shown: ee e to u f a 2> CHANGE s TO MASTER_AUTO_POSITION=1; (s MASTER n n e Query ha OK,li0crows affected (0.24 sec) K r feeb. In the third server connection, issue the following command and receive the result shown:

3> CHANGE MASTER TO MASTER_AUTO_POSITION=1; Query OK, 0 rows affected (0.25 sec)

7.

Restart the slaves. a. In the mysql prompt connected to the second server, enter the following command and receive the results shown: 2> START SLAVE; Query OK, 0 rows affected (0.05 sec)

b.

In the mysql prompt connected to the third server, enter the following command and receive the results shown: 3> START SLAVE; Query OK, 0 rows affected (0.04 sec)

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

Practices for Lesson 17: Replication Chapter 17 - Page 21

e

bl a r fe

In the second server connection, issue the following command and receive the result shown:

8.

Delete all rows where the ID is greater than 4060 from the City table on the first server, and ensure that the changes replicate to the second and third servers. a. On the first server, enter the following command and receive the results shown: 1> DELETE FROM world_innodb.City WHERE ID > 4060;

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

b.

On the second server, enter the following command and receive the results shown: 2> SELECT * FROM world_innodb.City ORDER BY Id DESC LIMIT 5; +------+--------------+-------------+----------------+------------+ | ID | Name | CountryCode | District | Population | +------+--------------+-------------+----------------+------------+ | 4060 | Santa Monica | USA | California | 91084 | | 4059 | Cary | USA | North Carolina | 91213 | | 4058 | Boulder | USA | Colorado | 91238 | | 4057 | Visalia | USA | California | 91762 | | 4056 | San Mateo | USA | California | 91799 | +------+--------------+-------------+----------------+------------+ 5 rows in set (0.00 sec)

s

c.

an r t n

no a 3> SELECT * FROM world_innodb.City ORDER BY Id DESC 5; s LIMIT a ฺ h +------+--------------+-------------+----------------+------------+ m) uide| Population | o | ID | Name | CountryCode |cDistrict G ฺ t n +------+--------------+-------------+----------------+------------+ n e de ate St|uCalifornia | 4060 | Santa Monica | USA | 91084 | w @ | 4059 | Cary | USA | North Carolina | 91213 | s i n h a t | 4058 | Boulder kh | USA | Colorado | 91238 | e ฺ s r u e | 4057 | Visalia | California | 91762 | fe e to || USA | 4056 (|sa San Mateo USA | California | 91799 | s n n e +------+--------------+-------------+----------------+------------+ a lic Kh On the third server, enter the following command and receive the results shown:

r 5 rows in set (0.00 sec) e e af9. Note the server UUIDs for the first, second, and third servers.

S

a.

On the first server, enter the following command and receive a result similar to the following: 1> SELECT @@server_uuid; +--------------------------------------+ | @@server_uuid | +--------------------------------------+ | ba1e7829-7416-11e2-b285-0019b944b7f7 | +--------------------------------------+ 1 row in set (0.00 sec)

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

Practices for Lesson 17: Replication Chapter 17 - Page 22

e

bl a r fe

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

b.

On the second server, enter the following command and receive a result similar to the following: 2> SELECT @@server_uuid; +--------------------------------------+ | @@server_uuid | +--------------------------------------+ | c701d6c5-7416-11e2-b285-0019b944b7f7 | +--------------------------------------+ 1 row in set (0.00 sec)

c.

On the third server, enter the following command and receive a result similar to the following: 3> SELECT @@server_uuid; +--------------------------------------+ | @@server_uuid | +--------------------------------------+ | d3f1fc98-7416-11e2-b286-0019b944b7f7 | +--------------------------------------+ 1 row in set (0.00 sec)

Sa

e

bl a r fe

s

an r t n

no a s a Note: Your UUIDs differ from those shown; the server UUIDhis unique ฺby design. ) de i m 10. On the third server, view the slave status. u o c receive Ga result similar to that shown: ฺand t n On the third server, enter the following command n e 3> SHOW SLAVE STATUS\G ate Stude w *************************** @ 1.hirow s *************************** n a t Slave_IO_State: h se Waiting for master to send event ฺkMaster_Host: r e 127.0.0.1 e eMaster_User: ou f t a (s ens Master_Port: repl n ha lic Connect_Retry: 3312 K 60 r e e Master_Log_File: mysql2-bin.000001 f Read_Master_Log_Pos: Relay_Log_File: Relay_Log_Pos: Relay_Master_Log_File: Slave_IO_Running: Slave_SQL_Running: Replicate_Do_DB: Replicate_Ignore_DB: Replicate_Do_Table: Replicate_Ignore_Table: Replicate_Wild_Do_Table: Replicate_Wild_Ignore_Table: Last_Errno: Last_Error: Skip_Counter: Exec_Master_Log_Pos:

460 mysql3-relay-bin.000002 672 mysql2-bin.000001 Yes Yes

0 0 460

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

Practices for Lesson 17: Replication Chapter 17 - Page 23

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

Relay_Log_Space: 877 Until_Condition: None Until_Log_File: Until_Log_Pos: 0 Master_SSL_Allowed: No Master_SSL_CA_File: Master_SSL_CA_Path: Master_SSL_Cert: Master_SSL_Cipher: Master_SSL_Key: Seconds_Behind_Master: 0 Master_SSL_Verify_Server_Cert: No Last_IO_Errno: 0 Last_IO_Error: Last_SQL_Errno: 0 Last_SQL_Error: Replicate_Ignore_Server_Ids: Master_Server_Id: 2 Master_UUID: c701d6c5-7416-11e2-b285-0019b944b7f7 Master_Info_File: mysql.slave_master_info SQL_Delay: 0 SQL_Remaining_Delay: NULL Slave_SQL_Running_State: Slave has read all relay log; waiting for the slave I/O thread to update it Master_Retry_Count: 86400 Master_Bind: Last_IO_Error_Timestamp: Last_SQL_Error_Timestamp: Master_SSL_Crl: Master_SSL_Crlpath: Retrieved_Gtid_Set: ba1e7829-7416-11e2-b285-0019b944b7f7:1 Executed_Gtid_Set: ba1e7829-7416-11e2-b285-0019b944b7f7:1 Auto_Position: 1 1 row in set (0.00 sec)

s

an r t n

o

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

Note that the master UUID identifies the second server, but the GTID for the data modification in step 8 identifies the first server; the transaction is globally identified. 11. Issue an appropriate CHANGE MASTER TO… statement on the first server, configuring it as a slave to the third server, and start the slave threads. On the first server, enter the following command and receive a result similar to that shown: 1> CHANGE MASTER TO MASTER_HOST='127.0.0.1', MASTER_PORT=3313, > MASTER_USER='repl', MASTER_PASSWORD='oracle', > MASTER_AUTO_POSITION=1; Query OK, 0 rows affected, 2 warnings (0.59 sec) 1> START SLAVE; Query OK, 0 rows affected (0.04 sec) Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 17: Replication Chapter 17 - Page 24

e

bl a r fe

12. Delete all rows where the ID is greater than 4050 from the City table on the second server, and ensure that the changes replicate to the first and third servers. a. On the second server, enter the following command and receive the results shown:

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

2> DELETE FROM world_innodb.City WHERE ID > 4050; Query OK, 10 rows affected (0.24 sec)

b.

On the first server, enter the following command and receive the results shown: 1> SELECT * FROM world_innodb.City ORDER BY Id DESC LIMIT 5; +------+----------+-------------+---------------+------------+ | ID | Name | CountryCode | District | Population | +------+----------+-------------+---------------+------------+ | 4050 | Roanoke | USA | Virginia | 93357 | | 4049 | Brockton | USA | Massachusetts | 93653 | | 4048 | Albany | USA | New York | 93994 | | 4047 | Richmond | USA | California | 94100 | | 4046 | Norman | USA | Oklahoma | 94193 | +------+----------+-------------+---------------+------------+ 5 rows in set (0.00 sec)

e

s

an r t n

Sa

bl a r fe

o n a c. On the third server, enter the following command and receive s the ฺresults shown: a h 3> SELECT * FROM world_innodb.City ORDER BY) Id DESC e LIMIT 5; d i m u +------+----------+-------------+---------------+------------+ ฺco nt G | Population | n | ID | Name | CountryCode |eDistrict ate Stude +------+----------+-------------+---------------+------------+ w @ his| Virginia | 4050 | Roanoke | USA | 93357 | n a t h USA se | Massachusetts | | 4049 | Brocktonk| 93653 | ฺ r u e | 4048 | Albany | New York | 93994 | o fe e|| tUSA | 4047 (|sa Richmond USA | California | 94100 | s n n e | 4046 | USA | Oklahoma | 94193 | ha | Norman lic K +------+----------+-------------+---------------+------------+ r fee 5 rows in set (0.00 sec) Circular replication is in effect, and a change on the second server replicated back to the first via the third.

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

Practices for Lesson 17: Replication Chapter 17 - Page 25

Practices 17-5: Using MySQL Utilities and Performing a Failover Overview

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

In this practice, you use the MySQL Utilities to provision a new slave, simulate a server failure, and perform an automated failover.

Assumptions You have successfully carried out the steps in Practice 17-4.

Duration This practice should take approximately 35 minutes to complete.

Tasks 1. 2. 3.

e

bl a r fe

s

an r t n

Apply the backup taken in the preceding practice (saved to /tmp/server2.sql) to the fourth server. Issue the following command to compare the databases on servers one and four, and save the output to /tmp/diff.sql.

no a s ฺ a h ) /usr/share/mysql-workbench/python/mysqldbcompare \ide m u o [email protected]:3311 \ฺc G t n n e [email protected]:3314 --changes-for=server2 \ e ude t a t --difftype=sql -a world_innodb:world_innodb > /tmp/diff.sql w sS @ i n 5. View the contents of /tmp/diff.sql. a e th h k ฺ 6. Source the file /tmp/diff.sql er to uons the fourth server to bring it up to date with the first. e f a change 7. On the fourth(s server, se the master settings to point to the first server and to use n n GTID, and start the slave. e ha window, lic issue the following command to display the replication topology. K 8. In a terminal r fee /usr/share/mysql-workbench/python/mysqlrplshow \ 4.

Sa

On the first server, stop and reset the slave. Connect to the fourth server using the mysql client, and set the prompt to “4> ”.

[email protected]:3311 \ --discover-slaves-login=root --recurse

To prepare for automatic failover, create a repl user on the fourth server, with the password oracle, and grant that user the REPLICATION SLAVE permission. 10. Repeat the preceding step using the host localhost instead of the loopback address. 9.

11. Launch mysqlfailover interactively in auto mode by using the following command. /usr/share/mysql-workbench/python/mysqlfailover \ [email protected]:3311 \ --discover-slaves-login=root --rpl-user=repl:[email protected]

12. View the different screens by pressing the G and U keys.

13. Shut down the first server from a separate terminal window. 14. Return to the terminal containing the mysqlfailover process, and observe the tool performing an automatic failover.

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

Practices for Lesson 17: Replication Chapter 17 - Page 26

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

15. Issue a mysqlrplshow command to display the replication topology with the fourth server as master. 16. Stop all four servers used in this lesson, and start the normal mysql service.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 17: Replication Chapter 17 - Page 27

Solutions 17-5: Using MySQL Utilities and Performing a Failover Tasks

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

1.

On the first server, stop and reset the slave. Enter the following at the first mysql prompt, and receive the results shown: 1> STOP SLAVE; Query OK, 0 rows affected (0.10 sec) 1> RESET SLAVE ALL; Query OK, 0 rows affected (0.32 sec)

2.

Connect to the fourth server using the mysql client, and set the prompt to “4> ”. Enter the following at a new terminal window, and receive the results shown: $ mysql -uroot -h127.0.0.1 -P3314 Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 1 ... mysql> PROMPT 4> ; PROMPT set to '4> '

e

s

an r t n

Sa

bl a r fe

no a s ฺ a h )to /tmp/server2.sql) de 3. Apply the backup taken in the preceding practice (saved to the i m u o c G fourth server. ฺ n ent estep, e In the mysql prompt created in the preceding t d the following command and a Stuenter w receive the results shown: @ his n 4> SOURCE /tmp/server2.sql a t h se(0.00 k ฺ Query OK, 0 rows affected sec) r e to u e f a se s ( Query OK, n affected (0.00 sec) an li0cerows h K r e Query OK, 0 rows affected (0.00 sec) fe Query OK, 0 rows affected (0.00 sec) ...

4.

Note that this backup includes a CHANGE MASTER TO… statement that specifies log coordinates rather than GTIDs. Issue the following command to compare the databases on servers one and four, and save the output to /tmp/diff.sql. Enter the following at a terminal window: $ /usr/share/mysql-workbench/python/mysqldbcompare \ [email protected]:3311 \ [email protected]:3314 --changes-for=server2 \ --difftype=sql -a world_innodb:world_innodb > /tmp/diff.sql

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

Practices for Lesson 17: Replication Chapter 17 - Page 28

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

5.

View the contents of /tmp/diff.sql. Enter the following at a terminal window and receive the results shown: $ cat /tmp/diff.sql # server1 on 127.0.0.1: ... connected. # server2 on 127.0.0.1: ... connected. # Checking databases world_innodb on server1 and world_innodb on server2 # # Defn Row Data # Type Object Name Diff Count Check # -----------------------------------------------------------------------# TABLE City FAIL FAIL FAIL # # Transformation for --changes-for=server2: #

s

an r t n

S

er e f a

no a s ฺ a h ) ALTER TABLE world_innodb.City de i m u o DROP INDEX CountryCode, ฺc nt G n e DROP PRIMARY KEY, ate Stude ADD PRIMARY KEY(ID), w @ is n ADD INDEX CountryCode (CountryCode), h a t AUTO_INCREMENT=4071; ฺkh use r e fe e to a s ( eare # Row counts ns not the same among world_innodb.City and n a world_innodb.City. c li Kh # # Transformation for --changes-for=server2: #

# Data differences found among rows: UPDATE world_innodb.City WHERE ID = '694'; UPDATE world_innodb.City SET ID = '785', Name = 'Pasay', CountryCode = 'PHL', District = 'National Capital Reg', Population = '354908' WHERE ID = '785'; DELETE FROM world_innodb.City WHERE ID = '4079'; ... DELETE FROM world_innodb.City WHERE ID = '4068';

# TABLE pass # TABLE pass

Country

pass

pass

CountryLanguage

pass

pass

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

Practices for Lesson 17: Replication Chapter 17 - Page 29

e

bl a r fe

# Database consistency check failed. # # ...done

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

6.

Source the file /tmp/diff.sql on the fourth server to bring it up to date with the first. In the mysql prompt connected to the fourth server, enter the following command and receive the results shown: 4> SOURCE /tmp/diff.sql Query OK, 0 rows affected (0.04 sec) Records: 0 Duplicates: 0 Warnings: 0 ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE ID = '694'' at line 1 Query OK, 0 rows affected (0.06 sec) Rows matched: 1 Changed: 0 Warnings: 0

s

Query OK, 1 row affected (0.05 sec)

Sa

an r t n

no a s ฺ ... a h ) Query OK, 1 row affected (0.05 sec) de i m u o Gin the mysqldbcompare ฺc syntax The error in the preceding output is due to an incorrect t n n e output. te tude a w 7. On the fourth server, change the master settings @ his S to point to the first server and to use GTID, and start the slave. an t h seto the k ฺ a. In the mysql prompt connected fourth server, enter the following command and r u ee shown: o f t receive thea results seTO MASTER_PORT=3311, MASTER_AUTO_POSITION=1; (s MASTER 4> CHANGE n n e ha OK,li0crows affected (0.34 sec) Query K r fee 4> START SLAVE; Query OK, 0 rows affected (0.05 sec)

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

Practices for Lesson 17: Replication Chapter 17 - Page 30

e

bl a r fe

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

8.

In a terminal window, issue the following command to display the replication topology. Enter the following at a terminal window and receive the results shown: $ /usr/share/mysql-workbench/python/mysqlrplshow \ [email protected]:3311 \ --discover-slaves-login=root --recurse # master on 127.0.0.1: ... connected. # Finding slaves for master: 127.0.0.1:3311 # master on localhost: ... connected. # Finding slaves for master: localhost:3312 # master on localhost: ... connected. # Finding slaves for master: localhost:3313 # master on localhost: ... connected. # Finding slaves for master: localhost:3314

e

# Replication Topology Graph 127.0.0.1:3311 (MASTER) | +--- localhost:3312 - (SLAVE + MASTER) | | | +--- localhost:3313 - (SLAVE) | +--- localhost:3314 - (SLAVE)

Sa

bl a r fe

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e e ude atthe t w The output shows a diagram representing relationship of slaves to masters. S @ s i n 9. To prepare for automatic failover, a create tha repl user on the fourth server, with the h e k ฺ password oracle, andr grant that s the REPLICATION SLAVE permission. uuser e e o f t In the mysql prompt a used ein the preceding step, enter the following command and receive s s ( the results shown: n n ice haCREATE l USER 'repl'@'127.0.0.1' IDENTIFIED BY 'oracle'; 4> K r fee Query OK, 0 rows affected (0.00 sec) 4> GRANT REPLICATION SLAVE ON *.* TO 'repl'@'127.0.0.1'; Query OK, 0 rows affected (0.00 sec)

At this point, the repl user exists on all four servers. 10. Repeat the preceding step using the host localhost instead of the loopback address. In the mysql prompt used in the preceding step, enter the following command and receive the results shown: 4> CREATE USER 'repl'@'localhost' IDENTIFIED BY 'oracle'; Query OK, 0 rows affected (0.00 sec) 4> GRANT REPLICATION SLAVE ON *.* TO 'repl'@'localhost'; Query OK, 0 rows affected (0.00 sec)

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

Practices for Lesson 17: Replication Chapter 17 - Page 31

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

11. Launch mysqlfailover interactively in auto mode by using the following command. a. Enter the following at a terminal window and receive the results shown: $ /usr/share/mysql-workbench/python/mysqlfailover \ [email protected]:3311 \ --discover-slaves-login=root --rpl-user=repl:oracle # Discovering slaves for master at 127.0.0.1:3311 # Checking privileges. # WARNING: You may be mixing host names and IP addresses. This may result in negative status reporting if your DNS services do not support reverse name lookup. # # Failover console will start in 10 seconds.

b.

When the console appears, it looks somewhat similar to the following: MySQL Replication Failover Utility Failover Mode = auto Next Interval = Mon Feb 11 07:55:33 2013

s

an r t n

no a s ฺ Binlog_Do_DB Binlog_Ignore_DB a h ) de i m u o ฺc nt G n e GTID Executed Set ate Stude[...] ba1e7829-7416-11e2-b285-0019b944b7f7:1-4 w @ his n a hStatusse t k Replication Health ฺ r ee e to u +------------+-------+---------+--------+------------+---------+ f a s | role | state | gtid_mode | health | | host (s |nport n e a c h li K+------------+-------+---------+--------+------------+---------+ Master Information -----------------Binary Log File Position mysql1-bin.000002 679

er e f a

S

| 127.0.0.1 | 3311 | MASTER | UP | ON | OK | | localhost | 3312 | SLAVE | UP | ON | OK | | localhost | 3314 | SLAVE | UP | ON | OK | +------------+-------+---------+--------+------------+---------+ Q-quit R-refresh H-health G-GTID Lists U-UUIDs

Note that the display does not show circularity, nor does it recurse. It shows only the slaves of the master provided on the command line. 12. View the different screens by pressing the G and U keys. a.

Press the G key to view the “Master GTID Executed Set,” and receive the results shown: MySQL Replication Failover Utility Failover Mode = auto Next Interval = Mon Feb 11 07:57:03 2013 Master Information -----------------Binary Log File Position mysql1-bin.000002 679

Binlog_Do_DB

Binlog_Ignore_DB

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

Practices for Lesson 17: Replication Chapter 17 - Page 32

e

bl a r fe

GTID Executed Set ba1e7829-7416-11e2-b285-0019b944b7f7:1-4 [...]

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

Master GTID Executed Set +-------------------------------------------+ | gtid | +-------------------------------------------+ | ba1e7829-7416-11e2-b285-0019b944b7f7:1-4 | | c701d6c5-7416-11e2-b285-0019b944b7f7:1 | +-------------------------------------------+

Q-quit R-refresh H-health G-GTID Lists U-UUIDs

b.

Press the G key again to view the “Transactions executed on the servers,” and receive the results shown: MySQL Replication Failover Utility Failover Mode = auto Next Interval = Mon Feb 11 07:57:21 2013

s

an r t n

o

an s Binlog_Do_DB Binlog_Ignore_DB ha deฺ ) om Gui c ฺ en dent GTID Executed Set e t ba1e7829-7416-11e2-b285-0019b944b7f7:1-4 wa s Stu[...] @ n hi a t h Transactions executed on the servers: e rฺk o us e e af se t s ( an licen h K Master Information -----------------Binary Log File Position mysql1-bin.000002 679

+------------+-------+---------+--------------------------------------------+ | host

| port

| role

| gtid

|

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

er e f a

S

| 127.0.0.1

| 3311

| MASTER

| ba1e7829-7416-11e2-b285-0019b944b7f7:1-4

|

| 127.0.0.1

| 3311

| MASTER

| c701d6c5-7416-11e2-b285-0019b944b7f7:1

|

| localhost

| 3312

| SLAVE

| ba1e7829-7416-11e2-b285-0019b944b7f7:1-4

|

| localhost

| 3312

| SLAVE

| c701d6c5-7416-11e2-b285-0019b944b7f7:1

|

| localhost

| 3314

| SLAVE

| 85bae58f-741f-11e2-b2be-0019b944b7f7:1-49

|

| localhost

| 3314

| SLAVE

| ba1e7829-7416-11e2-b285-0019b944b7f7:1-4

|

| localhost

| 3314

| SLAVE

| c701d6c5-7416-11e2-b285-0019b944b7f7:1

|

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

Q-quit R-refresh H-health G-GTID Lists U-UUIDs Up|Down-scroll

c.

Press the G key again to view the “Transactions purged from the servers,” and receive the results shown: MySQL Replication Failover Utility Failover Mode = auto Next Interval = Mon Feb 11 07:57:57 2013 Master Information -----------------Binary Log File Position mysql1-bin.000002 679

Binlog_Do_DB

Binlog_Ignore_DB

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

Practices for Lesson 17: Replication Chapter 17 - Page 33

e

bl a r fe

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

GTID Executed Set ba1e7829-7416-11e2-b285-0019b944b7f7:1-4 [...] Transactions purged from the servers: 0 Rows Found. Q-quit R-refresh H-health G-GTID Lists U-UUIDs

d.

Press the G key again to view the “Transactions owned by another server,” and receive the results shown: MySQL Replication Failover Utility Failover Mode = auto Next Interval = Mon Feb 11 07:58:33 2013 Master Information -----------------Binary Log File Position mysql1-bin.000002 679

Binlog_Do_DB

s

an r t n

no a s ฺ a h ) Transactions owned by another server: de i m u o ฺc nt G 0 Rows Found. n e e Q-quit R-refresh H-health G-GTID dU-UUIDs ate Lists u t w S the results shown: e. Press the U key to view the “UUIDs,” and receive @ s i n h t MySQL Replication Failover ha Utility e k ฺ s r Failover Mode =eauto u Interval = Mon Feb 11 07:58:51 2013 e e to Next f a s ns (Information Master n ha lice -----------------K r fee Binary Log File Position Binlog_Do_DB Binlog_Ignore_DB GTID Executed Set ba1e7829-7416-11e2-b285-0019b944b7f7:1-4 [...]

Sa

e

mysql1-bin.000002

679

GTID Executed Set ba1e7829-7416-11e2-b285-0019b944b7f7:1-4 [...] UUIDs +------------+-------+---------+---------------------------------------+ | host | port | role | uuid | +------------+-------+---------+---------------------------------------+ | 127.0.0.1 | 3311 | MASTER | ba1e7829-7416-11e2-b285-0019b944b7f7 | | localhost | 3312 | SLAVE | c701d6c5-7416-11e2-b285-0019b944b7f7 | | localhost | 3314 | SLAVE | 85bae58f-741f-11e2-b2be-0019b944b7f7 | +------------+-------+---------+---------------------------------------+ Q-quit R-refresh H-health G-GTID Lists U-UUIDs

f.

Press the H key to return to the Health screen.

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

Practices for Lesson 17: Replication Chapter 17 - Page 34

bl a r fe

Binlog_Ignore_DB

13. Shut down the second server from a separate terminal window. Enter the following at a terminal window.

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

$ mysqladmin -uroot -h127.0.0.1 -P3311 shutdown

14. Return to the terminal containing the mysqlfailover process, and observe the tool performing an automatic failover. The output should resemble the following: Failover starting in 'auto' mode... # Candidate slave localhost:3314 will become the new master. # Preparing candidate for failover. # Creating replication user if it does not exist. # Stopping slaves. # Performing STOP on all slaves. # Switching slaves to new master. # Starting slaves. # Performing START on all slaves. # Checking slaves for errors. # Failover complete. # Discovering slaves for master at localhost:3314

e

s

an r t n

Sa

bl a r fe

no a s ฺ a h ) de i m Failover console will restart in 5 seconds. u o c G ฺreplication t n 15. Issue a mysqlrplshow command to displayethe topology with the fourth server n e e t d a Stu as master. w @ Enter the following at a terminalnwindow, and is receive the results shown. h a t $ /usr/share/mysql-workbench/python/mysqlrplshow \ ฺkh use r e [email protected]:3314 \ e o af se t --discover-slaves-login=root --recurse s ( n n e # master on 127.0.0.1: ... connected. a c hFinding lislaves K # for master: 127.0.0.1:3314 r e e # master on localhost: ... connected. f # Finding slaves for master: localhost:3312 # master on localhost: ... connected. # Finding slaves for master: localhost:3313 # Replication Topology Graph 127.0.0.1:3314 (MASTER) | +--- localhost:3312 - (SLAVE + MASTER) | +--- localhost:3313 - (SLAVE)

16. Stop all four servers used in this lesson, and start the normal mysql service. Enter the following at a terminal window, and receive the results shown. # mysqld_multi --defaults-file=/labs/repl.cnf --user=root stop 1-4 # service mysql start Starting MySQL.. [ OK ] Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 17: Replication Chapter 17 - Page 35

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

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 17: Replication Chapter 17 - Page 36

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

e

bl a r fe

s

an r t n

er e f a

no a s ฺ 18: a Practices for Lesson h e ) toidPerformance m Introduction u o ฺc nt G n e Tuning ate Stude w @ hChapter is 18 n a t ฺkh use r e fe e to a s ( ens n a lic Kh

S

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

Practices for Lesson 18: Introduction to Performance Tuning Chapter 18 - Page 1

Practices for Lesson 18: Overview

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

Practices Overview In these practices, you test your knowledge of performance tuning topics. These hands-on practices are written for the Oracle Linux operating system environment, which is provided in Oracle classrooms. For non-Oracle classrooms, some adjustments may need to be made regarding file locations.

Assumptions •

The MySQL server installation has been completed prior to these practices.



You are logged in as the oracle user in a terminal window.



You can access the mysql client from a command-line prompt.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 18: Introduction to Performance Tuning Chapter 18 - Page 2

Practice 18-1: Quiz – Introduction to Performance Tuning Overview

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

In this practice, you answer questions about performance tuning.

Duration This practice should take approximately five minutes to complete.

Quiz Questions Choose the best answer from those provided for each multiple choice or True/False question. 1. Which of the following is not a benefit of normalization? a. Makes it easier to read queries b. Eliminates redundant data c. Minimizes data becoming inconsistent d. Provides flexible access to data 2. Choosing a data type that is larger than the space required can become a large problem when the data grows. a. True b. False 3. Querying a table with no indexes or insufficient indexes results in ______________. a. Corrupt data b. Full table scans c. Improved performance d. All of the above 4. The ________________ command describes how MySQL intends to execute a specified SQL statement, but it does not return any data from the data sets. a. ANALYZE b. DESCRIBE

s

an r t n

o

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

c. EXPLAIN d. SHOW 5. PROCEDURE ANALYZE analyzes the stored procedures in your application. a. True b. False 6. Which status variable displays the number of currently open connections? a. Key_reads b. Max_used_connections c. Open_tables d. Threads_connected

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

Practices for Lesson 18: Introduction to Performance Tuning Chapter 18 - Page 3

e

bl a r fe

7. Which server system variable defines how often the InnoDB log buffer is written out to the log file and how often the flush-to-disk operation is performed on the log file? a. innodb_buffer_pool_size

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

b. innodb_flush_log_at_trx_commit c. innodb_log_buffer_size d. innodb_log_file_size

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 18: Introduction to Performance Tuning Chapter 18 - Page 4

Solutions 18-1: Quiz – Introduction to Performance Tuning

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

Quiz Solutions 1. 2. 3. 4. 5.

a. Makes it easier to read queries a. True b. Full table scans c. EXPLAIN b. False. PROCEDURE ANALYZE analyzes the columns in a given query and provides tuning feedback on each field. 6. d. Threads_connected 7. b. innodb_flush_log_at_trx_commit

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 18: Introduction to Performance Tuning Chapter 18 - Page 5

Practice 18-2: EXPLAIN Overview

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

In this practice, you view the execution plan of several SELECT statements by using the EXPLAIN command. To accomplish this objective, do the following: •

Use the world_innodb database to view the execution plans of multiple SELECT statements.



Alter an existing table to improve the execution of a query.

Assumptions •

The MySQL server is installed and running.



The world_innodb database is installed.

e

bl a r fe

Duration This practice should take 10 minutes to complete.

Tasks

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a t WHERE Name LIKE 'A%'\G h FROM sCity EXPLAIN SELECT Name e k ฺ r e typetoforuthis query? ________________ − What is the eselect f a se indexes that this query can use? ______________ (s anyenpossible − Are there n a licrows must be examined to complete this query? ___________ K−h How many

1. Open a terminal window, start the mysql client with the admin login path, and use the world_innodb database. 2. Start over with a clean copy of the world_innodb database by re-creating it using the world_innodb.sql file. 3. Execute the following command to view the execution plan for a query against the City table in the world_innodb database:

r eExecute 4. the following command to view the execution plan for another query against the e f a City table in the world_innodb database:

S

EXPLAIN SELECT Name FROM City WHERE ID > 4070\G

− What is the select type for this query? _______________ − Are there any possible indexes that this query can use? ______________ − How many rows must be examined to complete this query? ____________ 5. Comparing the outputs from the first and second EXPLAIN statements, determine which is a better performing execution plan. ____________________________________________________________ ____________________________________________________________ 6. Improve the performance of the first query by making modifications to the City table and then rerun the EXPLAIN statement. − What is the select type for this query? _______________ − Are there any possible indexes that this query can use? _____________________________________________ − How many rows must be examined to complete this query? ____________ Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 18: Introduction to Performance Tuning Chapter 18 - Page 6

Solutions 18-2: EXPLAIN

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

Tasks 1. Open a terminal window, start the mysql client with the admin login path, and use the world_innodb database. Enter the following at a terminal window and receive the results shown: $ mysql –-login-path=admin Welcome to the MySQL monitor. ... mysql> USE world_innodb ... Database changed

Commands end with ; or \g.

2. Start over with a clean copy of the world_innodb database by re-creating it using the world_innodb.sql file.

s

an r t n

Enter the following at a mysql prompt and receive the results shown: mysql> DROP DATABASE world_innodb; Query OK, 4 rows affected (0.00 sec)

S

er e f a

o

an s ha deฺ ) mysql> CREATE DATABASE world_innodb; m ui Query OK, 1 row affected (0.00 sec) ฺco G en dent e t tu mysql> USE world_innodb; wa S @ s Database changed n hi a t h e mysql> SET AUTOCOMMIT=0; us (0.00 sec) erฺkaffected Query OK, 0fe rows o t a se s ( en/labs/world_innodb.sql an SOURCE c mysql> i h l K Query OK, 0 rows affected (0.00 sec) Query OK, 0 rows affected (0.00 sec) ... Query OK, 0 rows affected (0.00 sec) Query OK, 0 rows affected (0.00 sec) Query OK, 0 rows affected (0.00 sec) mysql> SET AUTOCOMMIT=1; Query OK, 0 rows affected (0.12 sec)

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

Practices for Lesson 18: Introduction to Performance Tuning Chapter 18 - Page 7

e

bl a r fe

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

3. Execute the following command to view the execution plan for a query against the City table in the world_innodb database. Enter the following at a mysql prompt and receive the results shown: mysql> EXPLAIN SELECT Name FROM City WHERE Name LIKE 'A%'\G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: City type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 4188 Extra: Using where 1 row in set (0.00 sec)

− What is the select type for this query? ALL

e

bl a r fe

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a h se t k ฺ r u FROM City WHERE ID > 4070\G mysql> EXPLAIN Name ee SELECT o f t a *************************** 1. row *************************** (s ense n a hselect_type: licid: 1SIMPLE K er

− Are there any possible indexes that this query can use? No − How many rows must be examined to complete this query? Approximately 3982. Your output may differ. There are 4079 rows in the table, so EXPLAIN performs an estimate. 4. Execute the following command to view the execution plan for another query against the City table in the world_innodb database. Enter the following at a mysql prompt and receive the results shown:

Sa

fe

table: City type: range possible_keys: PRIMARY key: PRIMARY key_len: 4 ref: NULL rows: 9 Extra: Using where 1 row in set (0.00 sec)

− What is the select type for this query? SIMPLE − Are there any possible indexes that this query can use? Yes, the primary key for this table can be used. − How many rows must be examined to complete this query? Nine. This is the actual number of rows returned by the query.

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

Practices for Lesson 18: Introduction to Performance Tuning Chapter 18 - Page 8

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

5. Comparing the outputs from the first and second EXPLAIN statements, determine which is a better performing execution plan. The second query takes advantage of an index and does not need to perform a full table scan. 6. Improve the performance of the first query by making modifications to the City table and then rerun the EXPLAIN statement. Enter the following statements at a mysql prompt and receive the results shown: mysql> CREATE INDEX iName ON City (Name) USING BTREE; Query OK, 0 rows affected (0.12 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> EXPLAIN SELECT Name FROM City WHERE Name LIKE 'A%'\G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: City type: range possible_keys: iName key: iName key_len: 35 ref: NULL rows: 258 Extra: Using where; Using index 1 row in set (0.00 sec)

e

an r t n

s

er e f a

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a t SIMPLE − What is the selectktype query? h for this e ฺ s r u that this query can use? − Are there any indexes eepossible o f t a Yes. (The s execution se plan uses the index created on the Name column. n n e a licrows must be examined to complete this query? 258 K−h How many

S

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

Practices for Lesson 18: Introduction to Performance Tuning Chapter 18 - Page 9

bl a r fe

Practice 18-3: PROCEDURE ANALYSE

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

Overview In this practice, you execute several SELECT statements with the PROCEDURE ANALYSE option. To accomplish this objective, do the following: • Use the world_innodb database and execute multiple SELECT statements. •

Evaluate existing tables to improve the table design.

Assumptions •

The MySQL server is installed and running.



The world_innodb database is installed.

Duration

e

bl a r fe

This practice should take 10 minutes to complete.

s

an r t n

Tasks 1.

er e f a

S

2.

no a s ฺ ANALYSE()\G a h SELECT Name, CountryCode, Population FROM City PROCEDURE ) dethe optimal field type i m u − What does the PROCEDURE ANALYSE option state would be o G data in the table? ฺc on nthet existing n for the Name column in the City tableebased _______________________________________________________________ ate Stude w @ANALYSE − What does the PROCEDURE is option state would be the optimal field type n h a t for the CountryCode ฺkh column sein the City table based on the existing data in the r u table? e fe e to a _______________________________________________________________ s ( ens n − a What does ANALYSE option state would be the optimal field type licthe PROCEDURE Kh for the Population column in the City table based on the existing data in the

Using the terminal from the previous practice, already running the mysql client and using the world_innodb database, execute the following command:

table? _______________________________________________________________ Execute the following command to view the City table design: DESC City;

Comparing the design of the City table and the recommendations from the PROCEDURE ANALYSE option run in step 1, evaluate each recommendation. _______________________________________________________________ _______________________________________________________________ _______________________________________________________________

3.

_______________________________________________________________ Execute the following command to change how PROCEDURE ANALYSE() recommends ENUM types, and compare the recommendations with those in the preceding steps: SELECT Name, CountryCode, Population FROM City PROCEDURE ANALYSE(256,1024)\G Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 18: Introduction to Performance Tuning Chapter 18 - Page 10

4.

Execute the following command to evaluate the CountryLanguage table design: SELECT * FROM CountryLanguage PROCEDURE ANALYSE(256,1024)\G

5.

Execute the following command to view the CountryLanguage table design:

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

DESC CountryLanguage;

Comparing the design of the CountryLanguage table and the recommendations from the PROCEDURE ANALYSE option run in step 3, which recommendation do you believe should be implemented? _______________________________________________________________ _______________________________________________________________ _______________________________________________________________

6.

_______________________________________________________________ Exit the mysql client session.

er e f a

S

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

Practices for Lesson 18: Introduction to Performance Tuning Chapter 18 - Page 11

s

an r t n

o

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

e

bl a r fe

Solutions 18-3: PROCEDURE ANALYSE Tasks

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

1.

Using the terminal from the previous practice, already running the mysql client and using the world_innodb database, execute the following command. Enter the following statement at a mysql prompt and receive the results shown: mysql> SELECT Name, CountryCode, Population FROM City -> PROCEDURE ANALYSE()\G *************************** 1. row *************************** Field_name: world_innodb.City.Name Min_value: A Coruña (La Coruña) Max_value: ´s-Hertogenbosch Min_length: 3 Max_length: 33 Empties_or_zeros: 0 Nulls: 0 Avg_value_or_avg_length: 8.5295 Std: NULL Optimal_fieldtype: VARCHAR(33) NOT NULL *************************** 2. row *************************** Field_name: world_innodb.City.CountryCode Min_value: ABW Max_value: ZWE Min_length: 3 Max_length: 3 Empties_or_zeros: 0 Nulls: 0 Avg_value_or_avg_length: 3.0000 Std: NULL Optimal_fieldtype: ENUM('ABW','AFG',...,'ZMB','ZWE') NOT NULL *************************** 3. row *************************** Field_name: world_innodb.City.Population Min_value: 42 Max_value: 10500000 Min_length: 2 Max_length: 8 Empties_or_zeros: 0 Nulls: 0 Avg_value_or_avg_length: 350468.2236 Std: 723686.9870 Optimal_fieldtype: MEDIUMINT(8) UNSIGNED NOT NULL 3 rows in set (0.00 sec)

s

an r t n

o

S

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

− What does the PROCEDURE ANALYSE option state would be the optimal field type for the Name column in the City table based on the existing data in the table? VARCHAR(33) NOT NULL − What does the PROCEDURE ANALYSE option state would be the optimal field type for the CountryCode column in the City table based on the existing data in the table? ENUM('ABW','AFG',...,'ZMB','ZWE') NOT NULL − What does the PROCEDURE ANALYSE option state would be the optimal field type for the Population column in the City table based on the existing data in the table? MEDIUMINT(8) UNSIGNED NOT NULL Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 18: Introduction to Performance Tuning Chapter 18 - Page 12

e

bl a r fe

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

2.

Execute the following command to view the City table design. Comparing the design of the City table and the recommendations from the PROCEDURE ANALYSE option run in step 1, evaluate each recommendation. Enter the following statement at a mysql prompt and receive the results shown: mysql> DESC City; +-------------+------------+------+-----+---------+------------+ | Field | Type | Null | Key | Default | Extra | +-------------+------------+------+-----+---------+------------+ | ID | int(11) | NO | PRI | NULL | auto_i ... | | Name | char(35) | NO | MUL | | | | CountryCode | char(3) | NO | MUL | | | | District | char(20) | NO | | | | | Population | int(11) | NO | | 0 | | +-------------+------------+------+-----+---------+------------+ 5 rows in set (0.00 sec)

s

an r t n

o

S

er e f a 3.

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

Enter the following statement at a mysql prompt and receive the results shown: mysql> SELECT Name, CountryCode, Population FROM City > PROCEDURE ANALYSE(256,1024)\G *************************** 1. row *************************** Field_name: world_innodb.City.Name Min_value: A Coruña (La Coruña) Max_value: ´s-Hertogenbosch Min_length: 3 Max_length: 33 Empties_or_zeros: 0 Nulls: 0 Avg_value_or_avg_length: 8.5295 Std: NULL Optimal_fieldtype: VARCHAR(33) NOT NULL Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 18: Introduction to Performance Tuning Chapter 18 - Page 13

e

bl a r fe

− Comparing the design of the City table and the recommendations from the PROCEDURE ANALYSE option run in step 1, which recommendation do you believe should be implemented? − Altering the Population column to a MEDIUMINT UNSIGNED field is a recommendation that suits the current data. The largest number that the MEDIUMINT UNSIGNED field can handle is 16,777,215, and it takes up only 3 bytes. For comparison, the largest number that the BIGINT UNSIGNED field can handle is 18,446,744,073,709,555,615 and it takes up 8 bytes. However, the best field type for this column to allow for future values is INT UNSIGNED because it can handle up to 4,294,967,295 and takes up 4 bytes. With cities such as Tokyo with 35 million people (as of 2013), the MEDIUMINT UNSIGNED field does not cater to the population of all cities now and into the future. − The recommendation to change the Name column does not save much space, but you should monitor the type as the table grows as new data appears. − The recommendation to change the CountryCode column to an ENUM field type is not one that you should implement; ENUM fields with a large number of values add complexity to applications, and are difficult to maintain. Execute the following command to change how PROCEDURE ANALYSE() recommends ENUM types, and compare the recommendations with those in the preceding steps.

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

*************************** 2. row *************************** Field_name: world_innodb.City.CountryCode Min_value: ABW Max_value: ZWE Min_length: 3 Max_length: 3 Empties_or_zeros: 0 Nulls: 0 Avg_value_or_avg_length: 3.0000 Std: NULL Optimal_fieldtype: CHAR(3) NOT NULL *************************** 3. row *************************** Field_name: world_innodb.City.Population Min_value: 42 Max_value: 10500000 Min_length: 2 Max_length: 8 Empties_or_zeros: 0 Nulls: 0 Avg_value_or_avg_length: 350468.2236 Std: 723686.9870 Optimal_fieldtype: MEDIUMINT(8) UNSIGNED NOT NULL 3 rows in set (0.01 sec)

e

s

an r t n

Sa

bl a r fe

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ hhasischanged to CHAR(3), the most appropriate n The recommendation for CountryCode a h se t k type. ฺ r uto evaluate the CountryLanguage table design: eecommand o f t 4. Execute the following a e CountryLanguage PROCEDURE ANALYSE(256,1024)\G s n* sFROM (SELECT mysql> n e ha lic *************************** 1. row *************************** K r e Field_name: world_innodb.CountryLanguage.CountryCode fe Min_value: ABW Max_value: ZWE Min_length: 3 Max_length: 3 Empties_or_zeros: 0 Nulls: 0 Avg_value_or_avg_length: 3.0000 Std: NULL Optimal_fieldtype: CHAR(3) NOT NULL *************************** 2. row *************************** Field_name: world_innodb.CountryLanguage.Language Min_value: Abhyasi Max_value: [South]Mande Min_length: 2 Max_length: 25 Empties_or_zeros: 0 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 18: Introduction to Performance Tuning Chapter 18 - Page 14

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

Nulls: 0 Avg_value_or_avg_length: 7.1606 Std: NULL Optimal_fieldtype: VARCHAR(25) NOT NULL *************************** 3. row *************************** Field_name: world_innodb.CountryLanguage.IsOfficial Min_value: F Max_value: T Min_length: 1 Max_length: 1 Empties_or_zeros: 0 Nulls: 0 Avg_value_or_avg_length: 1.0000 Std: NULL Optimal_fieldtype: ENUM('F','T') NOT NULL *************************** 4. row *************************** Field_name: world_innodb.CountryLanguage.Percentage Min_value: 0.1 Max_value: 100.0 Min_length: 3 Max_length: 5 Empties_or_zeros: 65 Nulls: 0 Avg_value_or_avg_length: 20.4 Std: 30.8 Optimal_fieldtype: FLOAT(4,1) NOT NULL 4 rows in set (0.00 sec)

s

an r t n

Sa

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @ his n a h se t k ฺ r ee e to u f a (s ens n 5. Execute hathe following lic command to view the CountryLanguage table design: K r fee 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.00 sec)

Comparing the design of the CountryLanguage table and the recommendations from the PROCEDURE ANALYSE option run in step 3, which recommendation do you believe should be implemented? The only changed recommendation is to set the language name to VARCHAR(25) from CHAR(30). Because VARCHAR is more space-efficient, this is a good recommendation, although you should ensure that any future values for the column fit within 25 characters.

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

Practices for Lesson 18: Introduction to Performance Tuning Chapter 18 - Page 15

e

bl a r fe

6.

Exit the mysql client session:

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

mysql> EXIT; Bye

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 18: Introduction to Performance Tuning Chapter 18 - Page 16

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

e

s

bl a r fe

an r t n

er e f a

no a s ฺ 19: a Practices for Lesson h ) de i m Conclusion u o ฺc nt G n e e u19de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 19: Conclusion Chapter 19 - Page 1

Practices for Lesson 19 Lesson Overview

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

There are no practices for this lesson.

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Practices for Lesson 19: Conclusion Chapter 19 - Page 2

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

e

bl a r fe

s

an r t n

er e f a

no a s ฺ Output a Appendix: h EXPLAIN ) de i m Columns u o ฺc nt G n e e u20de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Appendix: EXPLAIN Output Columns Chapter 20 - Page 1

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

The EXPLAIN Statement The EXPLAIN statement produces one row of output for each table named in each SELECT of the analyzed statement; a statement can have more than one SELECT if it uses subqueries or UNION. To use EXPLAIN productively, it is important to know the meaning of the columns in each row of output: • id: Indicates the SELECT in the analyzed statement to which the EXPLAIN output row refers • select_type: Categorizes the SELECT referred to by the output row. This column can have any of the values shown in the following table. The word DEPENDENT indicates that a subquery is correlated with the outer query. Meaning

select_type Value SIMPLE

Simple SELECT statement (no subqueries or unions)

PRIMARY

The outer SELECT statement

UNION

Second (or later) SELECT in union

s

an r t n

no a UNION RESULT s ฺ Second (or later) SELECT in union a h ) de SUBQUERY i First SELECT in a subquery m u o G is dependent on the outer ฺc nt that DEPENDENT SUBQUERY First SELECTeinna subquery ate Stude subquery w @ hinisthe WHERE clause DERIVED n Subquery a t e kh Materialized s MATERIALIZED erฺ subquery e e to u f a UNCACHEABLE The subquery result cannot be cached and must be res (s SUBQUERY n n e evaluated for each row of the outer query ha lic K A non-initial statement in a UNION that belongs to an erUNCACHEABLE UNION e f uncacheable subquery a Second (or later) SELECT in union

DEPENDENT UNION

S





• •



table: Is the name of the table to which the information in the row applies. The order of the tables indicates the order in which MySQL reads the tables to process the query. This is not necessarily the order in which you name them in the FROM clause, because the optimizer attempts to determine which order results in the most efficient processing. partitions: Indicates the partitions containing the data matched by the query, or NULL for nonpartitioned tables. This column appears only if you use the PARTITIONS keyword. type: Indicates the join type. The value is a measure of how efficiently MySQL can scan the table. The possible type values are described later in this section. possible_keys: Indicates which of the table’s indexes MySQL considers to be candidates for identifying rows that satisfy the query. This value can be a list of one or more index names, or NULL if there are no candidates. The word PRIMARY indicates that MySQL considers the table’s primary key to be a candidate. key: Indicates the optimizer’s decision about which of the candidate indexes listed in possible_keys yields most efficient query execution. If the key value is NULL, it Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix: EXPLAIN Output Columns Chapter 20 - Page 2

e

bl a r fe

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





Sa

means no index was chosen. This might happen either because there were no candidates or because the optimizer believes it is just as fast to scan the table rows as to use any of the possible indexes. A table scan might be chosen over an index scan if the table is small, or because the index would yield too high a percentage of the rows in the table to be of much use. key_len: Indicates the length of the key that MySQL used. From this value, you can derive how many columns from the index are used. For example, if you have an index consisting of three INT columns, each index row contains three 4-byte values. If key_len is 12, this indicates that the optimizer is using the three columns of the index when processing the query. If key_len is 4 or 8, it uses only the first one or two columns (that is, it uses a leftmost prefix of the index). If you have indexed partial values of string columns, take that into account when assessing the key_len value. Suppose that you have a composite index on two CHAR(8) columns that indexes only the first four bytes of each column. In this case, a key_len value of 8 means that both columns of the index would be used, and not just the first column. ref: Indicates which indexed column or columns are used to choose rows from the table. const means key values in the index are compared to a constant expression, such as in Code='FRA'. NULL indicates that neither a constant nor another column is being used, indicating selection by an expression or range of values. It might also indicate that the column does not contain the value specified by the constant expression. If neither NULL nor const is displayed, a table_name.column_name combination is shown, indicating that the optimizer is looking at column_name in the rows returned from table_name to identify rows for the current table.

s

an r t n

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w @of how ismany rows from the table it needs to examine. • rows: Is the optimizer’s estimate n h a t The value is an approximation e in general, MySQL cannot know the exact kh ubecause, ฺ s r e number of rowse without actually the query. For a multiple-table query, the tois an executing afrows values product of(s the estimate of the total number of row combinations that e sproduct gives you a rough n n needato be read. This measure of query performance. Smaller e h are better. lic values K er

fe • •

filtered: Indicates an estimated percentage of table rows (as shown in the rows column) that are filtered by the table condition. This column appears when you use the EXPLAIN EXTENDED syntax. Extra: Provides other information about the join. The possible values are described later in this section.

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

Appendix: EXPLAIN Output Columns Chapter 20 - Page 3

e

bl a r fe

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

EXPLAIN Output Columns for Joins The value in the type column of EXPLAIN output indicates the join type, but joins may be performed with varying degrees of efficiency. The type value provides a measure of this efficiency by indicating the basis on which rows are selected from each table. The following list shows the possible values, from the best type to the worst: • system: The table has exactly one row. •

const: The table has exactly one matching row. This type value is similar to system, except that the table may have other, non-matching rows. The EXPLAIN output from the query with WHERE Code='FRA' is an example of this: mysql> EXPLAIN SELECT * FROM Country WHERE Code = 'FRA'\G ************************* 1. row ************************* id: 1 select_type: SIMPLE table: Country type: const possible_keys: PRIMARY key: PRIMARY key_len: 3 ref: const rows: 1 Extra:

s

an r t n

Sa

no a s ฺ a h ) de i m u o ฺc nt G n e ate Stude w The query has a type value n of @ const because is only one row out of all its rows needs to h a t be read. If the table contained the row for France, there would be no non-matching ฺkhwoulduonly sesystem r e rows and the type value be rather than const. e e to f a For both system sconst, because only one row matches, any columns needed from (s eand n n it can habe readliconce and treated as constants while processing the rest of the query. K e•r eq_ref: Exactly one row is read from the table for each combination of rows from the

fe



tables listed earlier by EXPLAIN. This is common for joins where MySQL can use a primary key to identify table rows. ref: Several rows may be read from the table for each combination of rows from the tables listed earlier by EXPLAIN. This is similar to eq_ref, but can occur when a nonunique index is used to identify table rows or when only a leftmost prefix of an index is used. For example, the CountryLanguage table has a primary key on the CountryCode and Language columns. If you search using only a CountryCode value, MySQL can use that column as a leftmost prefix, but there might be several rows for a country if multiple languages are spoken there. fulltext: Indicates that the join uses a FULLTEXT index



ref_or_null: Similar to ref, but MySQL also looks for rows that contain NULL



index_merge: MySQL uses an index merge algorithm.



unique_subquery: Similar to ref, but used for IN subqueries that select from the primary key column of a single table



index_subquery: Similar to unique_subquery, but used for IN subqueries that select from an indexed column of a single table



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

Appendix: EXPLAIN Output Columns Chapter 20 - Page 4

e

bl a r fe

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



range: The index is used to select rows that fall within a given range of index values. This is common for inequality comparisons such as id < 10.



index: MySQL performs a full scan, but it scans the index rather than the data rows. An index scan is preferable: The index is sorted and index rows usually are shorter than data rows, so index rows can be read in order and more of them can be read at a time. ALL: A full table scan of all data rows. Typically, this indicates that no optimizations are done and represents the worst case. It is particularly unfortunate when tables listed later in EXPLAIN output have a join type of ALL because that indicates a table scan for every combination of rows selected from the tables processed earlier in the join.



e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Appendix: EXPLAIN Output Columns Chapter 20 - Page 5

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

EXPLAIN Output Columns for Table Processing The Extra column of EXPLAIN output provides additional information about how a table is processed. Some values indicate that the query is efficient: • Using index: MySQL can optimize the query by reading values from the index without having to read the corresponding data rows. This optimization is possible when the query selects only columns that are in the index. • Using where: MySQL uses a WHERE clause to identify rows that satisfy the query. Without a WHERE clause, you get all rows from the table. •

Distinct: MySQL reads a single row from the table for each combination of rows from the tables listed earlier in the EXPLAIN output.



Not exists: MySQL can perform a LEFT JOIN “missing rows” optimization that quickly eliminates rows from consideration. By contrast, some Extra values indicate that the query is not efficient:

Sa

e

bl a r • Using filesort: Rows that satisfy the query must be sorted, which adds an extra fe s processing step. n tra • Using temporary: A temporary table must be created to process thenquery. ninoadvance which • Range checked for each record: MySQL cannot determine a s a index from the table to use. For each combination of rows selected ฺfrom previous tables, h e is not great, but it is it checks the indexes in the table to see which one m will)be best.id This u o better than using no index at all. ฺc nt G n e ate Stude w @ his n a h se t k ฺ r ee e to u f a (s ens n ha lic K er

fe

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

Appendix: EXPLAIN Output Columns Chapter 20 - Page 6

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

EXPLAIN Output Columns for Joins To use EXPLAIN for query analysis, examine its output for clues to ways the query might be improved. Modify the query, and then run EXPLAIN again to see how its output changes. Changes might involve rewriting the query or modifying the structure of your tables. The following query rewriting techniques can be useful: • If the key value is NULL even when there are indexes available, you can try adding a USE INDEX option as a hint to the optimizer which index is relevant for the query. To force MySQL to use the index, use FORCE INDEX. To tell MySQL to ignore an index that it chose and choose a different one instead, use IGNORE INDEX. Each of these options is used in the FROM clause, following the table name containing the index you want to control. The option is followed by parentheses containing a comma-separated list of one or more index names. PRIMARY means the table's primary key. mysql> -> mysql> ->

SELECT Name FROM CountryList USE INDEX(PRIMARY) WHERE Code > 'M'; SELECT Name FROM CountryList IGNORE INDEX(Population) WHERE Code < 'B' AND Population > 50000000;

s

an r t n

no a squery ฺwith SELECT • To force MySQL to join tables in a particular order, begin the a h e desired order in the ) tables iindthe STRAIGHT_JOIN rather than SELECT, and then listm the u o FROM clause. ฺc nt G n e e available, • Sometimes a table in a query has an index de but the query is written in such a atused. u t w way that prevents the index from being If possible, rewrite the query in an S @of the hindex. s i n equivalent form that allowsause t h e k Changing the structure of your tables issanother way to provide the optimizer with better ฺ r u e e o information on which to base its decisions: f t a e s s ( • If the possible_keys is NULL in the output from EXPLAIN, it means MySQL enindexvalue anon applicable c i finds for processing the query. See whether an index can be added h l Kto the columns that identify which records to retrieve. For example, if a join is performed r e afe by matching a column in one table with a column in another table but neither of the The keyword KEY may be used instead of INDEX in all three options.

S





columns is indexed, try indexing them. Keep table index statistics up to date to help MySQL choose optimal indexes. If the table is an InnoDB and MyISAM table, you can update its statistics with the ANALYZE TABLE statement. As a table’s contents change, the statistics go out of date and become less useful to the optimizer in making good decisions about query execution strategies. You should run ANALYZE TABLE more frequently for tables that change often than for those that are updated rarely. Be careful when using EXPLAIN to analyze a statement that includes a subquery in the FROM clause, if the subquery itself is slow. For such a subquery, MySQL must execute it to determine what it returns so that the optimizer can formulate an execution plan for the outer query.

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

Appendix: EXPLAIN Output Columns Chapter 20 - Page 7

e

bl a r fe

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

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Appendix: EXPLAIN Output Columns Chapter 20 - Page 8

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

e

bl a r fe

s

an r t n

er e f a

no a s ฺ Solutions a Appendix: h Practice ) de i m Scripts u o ฺc nt G n e e u21de atChapter t w S @ s n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 1

Lesson 1: Introduction to MySQL

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

No scripts for this lesson

Lesson 2: MySQL Architecture No scripts for this lesson

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 2

Lesson 3: System Administration

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

Practice 3-1: Installing the MySQL Server -- Step 1 -- (at the linux terminal) su cd /stage/mysql rpm -hi --replacefiles MySQL-server*.rpm rpm -hi MySQL-client*.rpm rpm -hi MySQL-devel*.rpm rpm -hi MySQL-shared*.rpm rpm -hi MySQL-test*.rpm -- Step 2 service mysql start

e

-- Step 3 cat /root/.mysql_secret mysql -uroot -p

s

-- (at the mysql prompt) SET PASSWORD=PASSWORD('oracle'); EXIT

SOURCE /labs/world_innodb.sql SET autocommit=1; -- Step 2 SHOW DATABASES;

-- Step 3 SHOW VARIABLES LIKE 'datadir'\G -- Step 4 -- (at the linux terminal) cd /var/lib/mysql ls -- Step 5 su cd /var/lib/mysql/mysql ls -- Step 6 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix: Practice Solutions Scripts Chapter 21 - Page 3

an r t n

o

an s ha deฺ ) i m -- (at the linux terminal) u o c G ฺ /usr/bin/mysql_secure_installation n e dent e t a Stu Practice 3-2: MySQL Data Directoryw @ is n -- Step 1 h a t -- (at the linux ฺterminal) r kh o use e mysql -uroot e -poracle af se t s ( -- (at mysql prompt) enworld_innodb; an the c i CREATE DATABASE h l KUSE world_innodb r e afe SET autocommit=0;

S

bl a r fe

cd ../world_innodb ls

Practice 3-3: Starting and Stopping the MySQL Server

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

-- Step 1 su -- Step 2 service mysql status -- Step 3 service mysql stop -- Step 4 service mysql status

e

-- Step 5 service mysql start

s

-- Step 6 service mysql status

er e f a

bl a r fe

o

an r t n

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 4

Lesson 4: Server Configuration Practice 4-1: Quiz - MySQL Server Configuration

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

No script for this practice

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 5

Practice 4-2: Editing and Creating a Configuration File

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

-- Step 1 -- (in a Linux terminal) -- Type "su -" and enter the password cp /etc/my.cnf /root gedit /etc/my.cnf -- Steps 2, 3, 4 -- New contents of /etc/my.cnf repeated here for convenience [mysqld] datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock port=3309 user=mysql # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0 general_log log-bin=mybinlog slow_query_log

s

Sa

o

an s ha deฺ ) om Gui [client] c ฺ port=3309 en dent e t wa s Stu -- Step 5 @ -- (in a Linux terminal) n hi a t h service mysql restart e rฺk o us e e t -- Step 6 af e s s ( -- (in enterminal) an a Linux c lsh/var/lib/mysql i l er K [mysqld_safe] log-error=/var/log/mysqld.log pid-file=/var/run/mysqld/mysqld.pid

fe

an r t n

-- Step 7 -- (in a Linux terminal) cd pwd gedit my_opts.txt

-- New contents of my-opts.txt repeated here for convenience [client] password = oracle user = root [mysql] compress show-warnings prompt = \R:\m \d>\_ -- Step 8 -- (in a Linux terminal) mysql --defaults-extra-file=~/my_opts.txt

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 6

e

bl a r fe

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

-- Step 9 -- (in a mysql prompt) STATUS USE world_innodb EXIT -- Step 10 -- New contents of /etc/my.cnf repeated here for convenience [mysqld] datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock port=3309 user=mysql # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0 general_log log-bin=mybinlog slow_query_log

s

[mysqld_safe] log-error=/var/log/mysqld.log pid-file=/var/run/mysqld/mysqld.pid

Sa

an s ha deฺ [client] ) m port=3309 ui o c G ฺ user=root en dent e t [mysql] wa s Stu @ compress n hi a t show-warnings h e rฺk o us prompt = \R:\m e \d>\_ e af se t s -- Step (11 n a Linux enterminal) -- a (in c i h l er Kmysql -p

o

fe

-- Step 12 -- (in a Linux terminal) mysql_config_editor set --user=root --password -- Step 13 -- (in a Linux terminal) mysql_config_editor print --all -- Step 14 -- (in a Linux terminal) cat ~/.mylogin.cnf -- Step 15 -- (in a Linux terminal) mysql -- (in the mysql prompt) EXIT

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 7

an r t n

e

bl a r fe

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

-- Step 16 -- (in a Linux terminal) mysql_config_editor remove -- Step 17 -- (in a Linux terminal) mysql_config_editor set --login-path=admin --user=root --password -- Step 18 -- (in a Linux terminal) mysql --login-path=admin -- Step 19 -- (in a Linux terminal) cp /root/my.cnf /etc/ service mysql restart

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 8

Practice 4-3: Additional Practice – Server Configuration

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

-- Step 1 -- (in a Linux terminal) mysql --login-path=admin -- (in the mysql prompt) SHOW GLOBAL VARIABLES LIKE '%log'; SET GLOBAL general_log = ON; SET GLOBAL slow_query_log = ON; SHOW GLOBAL VARIABLES LIKE '%log';

-- Step 2 -- (in the mysql prompt) SHOW GLOBAL VARIABLES LIKE 'log_output'; SET GLOBAL log_output = 'TABLE'; SHOW GLOBAL VARIABLES LIKE 'log_output'; TRUNCATE mysql.general_log; TRUNCATE mysql.slow_log;

s

fe

SELECT SLEEP(11); SELECT * FROM mysql.slow_log\G

-- Step 6 -- (in the mysql prompt) SHOW GLOBAL VARIABLES LIKE 'log_bin'; EXIT -- Step 7 -- (in a Linux terminal) gedit /etc/my.cnf

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 9

an r t n

o

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ -- Step 4 n hi a t h -- (in the mysql ฺprompt) e k us SELECT COUNT(*)er FROM mysql.general_log e f LIKEe 'CREATE to TABLE%'; WHERE argument a s ( ens n a --hStep 5 lic K er -- (in the mysql prompt) -- Step 3 -- (in the mysql prompt) CREATE DATABASE world2; USE world2; SET autocommit=0; SOURCE /labs/world_innodb.sql SET autocommit=1;

Sa

e

bl a r fe

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

-- New contents of /etc/my.cnf repeated here for convenience [mysqld] log-bin=mysql-bin datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock user=mysql # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0 [mysqld_safe] log-error=/var/log/mysqld.log pid-file=/var/run/mysqld/mysqld.pid -- (in a Linux terminal) service mysql restart

e

-- Step 8 -- (in a Linux terminal) mysql --login-path=admin

s

DROP DATABASE foo;

-- Step 11 -- (in the mysql prompt) SHOW MASTER LOGS; SHOW BINLOG EVENTS IN 'mysql-bin.000002'; -- Step 12 -- (in the mysql prompt) PURGE MASTER LOGS TO 'mysql-bin.000002'; -- Step 13 -- (in the mysql prompt) CREATE DATABASE foo2; DROP DATABASE foo2; -- Step 14 -- (in a Linux terminal) mysqlbinlog /var/lib/mysql/mysql-bin.000002

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 10

an r t n

o

an s ha deฺ ) m ui o c G ฺ -- Step 9 en dent e -- (in the mysql prompt) t CREATE DATABASE foo; wa s Stu @ DROP DATABASE foo; n hi t SHOW BINLOG EVENTS; ha e rฺk o us e e t -- Step 10af e s s -- (in the mysql prompt) ( en FLUSH LOGS; anBINARY c i h l er KCREATE DATABASE foo; -- (in the mysql prompt) SHOW GLOBAL VARIABLES LIKE 'log_bin'; RESET MASTER;

fe Sa

bl a r fe

-- Step 15 -- No steps

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

-- Step 16 -- (in the mysql prompt) INSTALL PLUGIN audit_log SONAME 'audit_log.so'; -- Step 17 -- (in the mysql prompt) CREATE DATABASE foo; DROP DATABASE foo; -- Step 18 -- (in the mysql prompt) SHOW VARIABLES LIKE 'audit_log_file';

e

-- (in a Linux terminal) cat /var/lib/mysql/audit.log -- Step 19 -- (in the mysql prompt) UNINSTALL PLUGIN audit_log; SHOW WARNINGS;

Sa

s

an r t n

o

an s ha deฺ -- Step 20 ) m -- (in the mysql prompt) ui o c G ฺ CREATE DATABASE foo; en dent e DROP DATABASE foo; t wa s Stu @ -- Step 21 n hi a t -- (in the mysql prompt) h e rฺk o us EXIT e e af se t s -- Step (22 n a Linux enterminal) -- a (in c i h l er Kcat /var/lib/mysql/audit.log

fe

bl a r fe

-- Step 23 -- New contents of /etc/my.cnf repeated here for convenience [mysqld] plugin-load=audit_log.so audit-log=FORCE_PLUS_PERMANENT log-bin=mysql-bin datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock user=mysql # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0 [mysqld_safe] log-error=/var/log/mysqld.log pid-file=/var/run/mysqld/mysqld.pid -- (in a Linux terminal) service mysql restart

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 11

-- Step 24 -- (in a Linux terminal) mysql --login-path=admin

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

-- (in the mysql prompt) UNINSTALL PLUGIN audit_log; -- Step 25 -- (in a Linux terminal) cat /var/lib/mysql/audit.log

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 12

Lesson 5: Clients and Tools

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

Practice 5-1: Invoking the mysql Client -- Step 1 -- (at the linux terminal) mysql -V -- Step 2 -- (at the linux terminal) mysql --help -- Step 3 -- (at the linux terminal) mysql -uroot -poracle

e

bl a r fe

-- (at the mysql prompt) EXIT

s

-- Step 4 -- (at the linux terminal) mysql --login-path=admin --html -e \ "SELECT CURRENT_DATE(), CURRENT_TIME()"

S

er e f a

an s ha deฺ ) om Gui -- Step 5 c ฺ n ent -- (at the linux terminal) e e t mysql -uroot -p -P 3306 --tee=tee_1.txt a Stud w @ his -- (at the mysql prompt) n a h se t EXIT k ฺ r u ee terminal) o f t -- (at thealinux (s ense cat tee_1.txt n a K--hStep 6 lic

o

-- (at the linux terminal) mysql --login-path=admin --safe-updates -- Step 7 -- (at the mysql prompt) STATUS -- Step 8 -- (at the mysql prompt) HELP CONTENTS; HELP Account Management; HELP SET PASSWORD; -- Step 9 -- (at the mysql prompt) SHOW DATABASES; EXIT

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 13

an r t n

Practice 5-2: Invoking the mysqladmin Client

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

-- Step 1 -- (at the linux terminal) mysqladmin -V -- Step 2 -- (at the linux terminal) mysqladmin --help -- Step 3 -- (at the linux terminal) mysqladmin -uroot -poracle variables

Practice 5-3: Viewing the MySQL Enterprise Monitor Demos

e

Follow the instructions in the practice.

bl a r Practice 5-4: Performing System Administration Tasks with MySQL Workbench fe s n Follow the instructions in the practice. To replace the practice, use the following steps. tra n -- Step 1 no a -- (at the linux terminal) s ฺ a su h cd /stage/mysql m) uide rpm -hi --nodeps mysql-workbench*.rpmฺco G t n n e e -- Practice uses MySQL Workbench ateto Sload tudthe sakila database -- To replace this practice:w @ his -- (at the mysql prompt) n a h se t SOURCE /labs/sakila-db/sakila-schema.sql k ฺ r SOURCE /labs/sakila-db/sakila-data.sql ee e to u f a (s ens n ha lic K er e f a

S

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 14

Lesson 6: Data Types Practice 6-1: Quiz

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

No script for this practice

Practice 6-2: Setting a Data Type -- All steps carried out at the mysql prompt -- Step 1 CREATE DATABASE test; -- Step 2 USE test CREATE TABLE integers(n SMALLINT UNSIGNED); INSERT INTO integers VALUES (5);

e

-- Step 3 SELECT * FROM integers;

s

-- Step 4 SHOW TABLE STATUS LIKE 'integers'\G

Sa

bl a r fe

an s ha deฺ -- Step 5 ) USE world_innodb; om Gui c ฺ CREATE TABLE CityCopy LIKE City; n ent eCity; INSERT INTO CityCopy SELECT * FROM e t a Stud w -- Step 6 @ his n a DESC CityCopy; h se t k ฺ SHOW TABLE STATUS LIKE 'CityCopy'\G r ee e to u f a -- Step (7s ns MODIFY Population BIGINT; n ALTER TABLE c CityCopy e a h CityCopy; li DESC K r e SHOW TABLE STATUS LIKE 'CityCopy'\G

o

fe

-- Step 8 DROP TABLE CityCopy;

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 15

an r t n

Lesson 7: Obtaining Metadata

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

Practice 7-1: Obtaining Metadata by Using INFORMATION_SCHEMA -- Step 1 -- (at the linux terminal) mysql -uroot -poracle -- (at the mysql prompt) SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'world_innodb'\G

-- Step 2 -- (at the mysql prompt) USE INFORMATION_SCHEMA SELECT TABLE_NAME, ENGINE FROM TABLES WHERE TABLE_SCHEMA = 'world_innodb';

e

s

fe Sa

SELECT DATA_TYPE, COUNT(*) FROM COLUMNS WHERE TABLE_SCHEMA = 'world_innodb' AND DATA_TYPE IN ('CHAR', 'VARCHAR') GROUP BY DATA_TYPE;

Practice 7-2: Obtaining Metadata by Using SHOW and DESCRIBE -- All steps at the mysql prompt -- Step 1 SHOW DATABASES; -- Step 2 SHOW DATABASES LIKE '%o%'; -- Step 3 USE information_schema; SHOW TABLES;

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 16

an r t n

o

an s ha deฺ ) om Gui c ฺ en dent -- Step 4 e t -- (at the mysql prompt) wa s Stu @ SELECT TABLE_NAME, DATA_LENGTH n hi a t FROM TABLES h e rฺk= 'world_innodb' WHERE TABLE_SCHEMA us e e o AND TABLE_NAME = 'City'; f t a se s ( -- Step an 5 licen h er K-- (at the mysql prompt) -- Step 3 -- (at the mysql prompt) SELECT TABLE_SCHEMA, ENGINE, COUNT(*) FROM TABLES GROUP BY TABLE_SCHEMA, ENGINE;

bl a r fe

-- Step 4 USE world_innodb SHOW FULL COLUMNS FROM City\G

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

-- Step 5 SHOW INDEX FROM City\G -- Step 6 DESCRIBE CountryLanguage; -- Step 7 SHOW CHARACTER SET; -- Step 8 SHOW COLLATION;

e

-- Step 9 EXIT

s

an r t n

Practice 7-3: Obtaining Metadata by Using mysqlshow -- All steps at the linux terminal

er e f a

o

an -- Step 1 s ha deฺ mysqlshow -uroot -poracle ) om Gui c -- Step 2 ฺ en dent mysqlshow world_innodb -uroot -poracle e t wa s Stu -- Step 3 @ nCountryLanguage hi mysqlshow world_innodb -uroot -poracle a t h e k ฺ er to us e f a se s ( an licen h K

S

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 17

bl a r fe

Lesson 8: Transactions and Locking Practice 8-1: Quiz – Transactions and Locking

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

No script for this practice

Practice 8-2: Using Transaction Control Statements -- After Step 1, all steps use the mysql client -- Step 1 -- (at the linux terminal) mysql -uroot -poracle -- (at the mysql prompt) SHOW ENGINES\G

e

-- Step 2 SET AUTOCOMMIT = 1; SELECT @@AUTOCOMMIT;

s

an s a eฺ h ) -- Step 4 om Guid START TRANSACTION; c ฺ en dent e t -- Step 5 tu wa= 'Manta'; S SELECT * FROM City WHERE @ Name s nName = t'Manta'; DELETE FROM City WHERE hi a h e SELECT * FROM City Name s = 'Manta'; rฺkWHERE u e e o f t -- Step 6sa e s ( n ROLLBACK; eCity an * FROM c i h SELECT WHERE Name = 'Manta'; l K r e

fe

an r t n

o

-- Step 3 USE world_innodb SHOW CREATE TABLE City\G

Sa

bl a r fe

-- Step 7 START TRANSACTION;

-- Step 8 DELETE FROM City WHERE Name = 'Manta'; -- Step 9 COMMIT; -- Step 10 SELECT * FROM City WHERE Name = 'Manta'; -- Step 11 ROLLBACK; SELECT * FROM City WHERE Name = 'Manta';

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 18

Practice 8-3: Additional Practice with Transactions and Locking

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

-- Step 1 -- (at the linux terminal) mysql -uroot -poracle -- (at the mysql prompt) SELECT @@global.tx_isolation; -- Step 2 PROMPT t1> ; -- Step 3 START TRANSACTION; -- Step 4 USE world_innodb SELECT * FROM City WHERE ID > 4070; -- Step 5 -- (at a new linux terminal) mysql -uroot -poracle

fe

-- Step 9 -- (at the t1 mysql prompt) SELECT * FROM City WHERE ID > 4070; -- Step 10 -- (at the t2 mysql prompt) COMMIT; -- Step 11 -- (at the t1 mysql prompt) COMMIT; SELECT * FROM City WHERE ID > 4070; -- Step 12 START TRANSACTION; -- Step 13 DELETE FROM City WHERE ID = 4080; SELECT * FROM City WHERE ID > 4070;

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 19

s

an r t n

no a s ฺ a h ) de i m u o -- Step 6 ฺc nt G n START TRANSACTION; e ate Stude w -- Step 7 @ his USE world_innodb n a h IDse> t4070; SELECT * FROM CitykWHERE ฺ r ee e to u -- Step 8 af (s City INSERT INTO CountryCode) VALUES ('New City', 'ATA'); ns(Name, n e a c SELECT * FROM City WHERE ID > 4070; i h l er K -- (at the new mysql prompt) PROMPT t2> ;

Sa

e

bl a r fe

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

-- Step 14 -- (at the t2 mysql prompt) SET SESSION tx_isolation = 'READ-UNCOMMITTED'; SELECT @@tx_isolation; -- Step 15 START TRANSACTION; SELECT * FROM City WHERE ID > 4070; -- Step 16 -- (at the t1 mysql prompt) ROLLBACK; SELECT * FROM City WHERE ID > 4070; -- Step 17 -- (at the t2 mysql prompt) SELECT * FROM City WHERE ID > 4070;

e

-- Step 18 ROLLBACK;

s

fe

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 20

an r t n

o

an s ha deฺ ) m -- (at the Linux terminal) ui o c G ฺ exit en dent e t tu -- (at the t2 mysql prompt) wa S @ s EXIT n hi a t h e k us rฺterminal) -- (at the Linux e e f to exit a e s ( ens n a h lic K er -- Step 19 -- (at the t1 mysql prompt) EXIT

Sa

bl a r fe

Lesson 9: Storage Engines Practice 9-1: Quiz – InnoDB Storage Engine

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

No script for this practice

Practice 9-2: Setting and Confirming InnoDB Settings -- Step 1 -- (at the linux terminal) su head -1 /proc/meminfo gedit /etc/my.cnf -- The new contents of /etc/my.cnf are reproduced here for convenience [mysqld] innodb_buffer_pool_size=2GB innodb_buffer_pool_instances=2 log-bin=mysql-bin datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock user=mysql # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0

s

o

an r t n

S

er e f a

an s ha deฺ ) om Gui c ฺ [mysqld_safe] n ent log-error=/var/log/mysqld.log tee a Stud pid-file=/var/run/mysqld/mysqld.pid w @ his n a -- Step 2 h se t k -- (at the linuxrฺterminal) e to u erestart service mysql f a (3s ense n -- Step a c terminal) K--h(at the lilinux mysql -uroot -poracle

-- (at the mysql prompt) SELECT @@default_storage_engine; -- Step 4 USE INFORMATION_SCHEMA SHOW TABLES LIKE 'INNODB%'; -- Step 5 SHOW VARIABLES LIKE '%innodb%';

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 21

e

bl a r fe

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

-- Step 6 -- The new contents of /etc/my.cnf are reproduced here for convenience [mysqld] innodb_autoextend_increment=128 innodb_buffer_pool_size=2GB innodb_buffer_pool_instances=2 log-bin=mysql-bin datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock user=mysql # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0 [mysqld_safe] log-error=/var/log/mysqld.log pid-file=/var/run/mysqld/mysqld.pid

e

-- (at the linux terminal) service mysql restart

S

an r t n

o

an s ha deฺ -- (at the mysql prompt) ) SHOW VARIABLES LIKE '%innodb%'; om Gui c ฺ en dent e -- Step 8 t USE world_innodb wa s Stu @ CREATE TABLE CityLanguage n ( thi a City CHAR(35), h ฺk use r Country CHAR(35), e e e to fCHAR(3), CountryCode a s Language( CHAR(30) ns n e ) ENGINE=MEMORY; a c li Kh -- Step 7 mysql -uroot -poracle

er e f a

s

SHOW CREATE TABLE CityLanguage\G -- Step 9 ALTER TABLE CityLanguage ENGINE=InnoDB; SHOW CREATE TABLE CityLanguage\G

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 22

bl a r fe

Lesson 10: Partitioning Practice 10-1: Quiz – MySQL Partitioning

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

No script for this practice

Practice 10-2: Creating and Modifying a Partitioned Table -- Step 1 -- (at the linux terminal) mysql --login-path=admin -- (at the mysql prompt) SHOW VARIABLES LIKE 'innodb_file_per_table'; -- Step 2 USE world_innodb CREATE TABLE City_part LIKE City;

e

-- Step 3 SHOW TABLE STATUS LIKE 'City_part'\G

s

Sa

fe

an r t n

o

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t -- Step 5 h e SHOW TABLE STATUS rฺkLIKEo'City_part'\G us e e f t -- Step (6sa se SELECT * FROM City; n n INSERT INTO City_part e ha lic K er -- Step 7 -- Step 4 ALTER TABLE City_part PARTITION BY RANGE (ID) ( PARTITION p0 VALUES LESS THAN (1000), PARTITION p1 VALUES LESS THAN (2000), PARTITION p2 VALUES LESS THAN (3000), PARTITION p3 VALUES LESS THAN MAXVALUE );

-- (at the linux terminal) su cd /var/lib/mysql/world_innodb; ls -l -- Step 8 -- (at the mysql prompt) EXPLAIN PARTITIONS SELECT * FROM City_part\G -- Step 9 EXPLAIN PARTITIONS SELECT * FROM City_part WHERE ID < 2000\G -- Step 10 ALTER TABLE City_part PARTITION BY KEY (ID) PARTITIONS 3; -- Step 11 EXPLAIN PARTITIONS SELECT * FROM City_part\G

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 23

bl a r fe

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

-- Step 12 -- (at the linux terminal) cd /var/lib/mysql/world_innodb; ls -l -- Step 13 -- (at the mysql prompt) SELECT TABLE_NAME, GROUP_CONCAT(PARTITION_NAME) FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_SCHEMA='world_innodb' AND TABLE_NAME='City_part';

Practice 10-3: Removing Partitions from a Table -- Step 1 ALTER TABLE City_part DROP PARTITION p0; -- Step 2 ALTER TABLE City_part PARTITION BY RANGE (id) ( PARTITION p0 VALUES LESS THAN (1000), PARTITION p1 VALUES LESS THAN (2000), PARTITION p2 VALUES LESS THAN (3000), PARTITION p3 VALUES LESS THAN MAXVALUE );

S

er e f a

e

s

-- Step 7 -- (at the mysql prompt) ALTER TABLE City_part REMOVE PARTITIONING; -- Step 8 SHOW TABLE STATUS LIKE 'City_part'\G -- Step 9 EXPLAIN PARTITIONS SELECT * FROM City_part\G -- Step 10 -- (at the linux terminal) cd /var/lib/mysql/world_innodb; ls -l

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 24

an r t n

o

an s ha deฺ ) -- Step 3 om Gui c -- (at the linux terminal) ฺ e-ln dent cd /var/lib/mysql/world_innodb; ls e t wa s Stu -- Step 4 @ n hi -- (at the mysql prompt) a t h e ALTER TABLE City_part sPARTITION p0; rฺk oDROP u e e f t -- Step (5sa e s EXPLAIN en SELECT * FROM City_part\G an PARTITIONS c i h l K -- Step 6 -- (at the linux terminal) cd /var/lib/mysql/world_innodb; ls -l

bl a r fe

Lesson 11: User Management Practice 11-1: Quiz – MySQL User Management

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

No script for this practice

Practice 11-2: Creating, Verifying, and Dropping a User -- Step 1 -- (at the linux terminal) mysql --login-path=admin -- (at the mysql prompt) SELECT user, host, password FROM mysql.user WHERE user = ''; -- Step 2 CREATE USER ''@'localhost'; -- Step 3 SELECT user, host, password FROM mysql.user WHERE user = '';

Sa

e

s

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 25

an r t n

o

an -- Step 4 s ha deฺ DROP USER ''@'localhost'; ) SELECT user, host, password FROM mysql.user om Gui c ฺ WHERE user = ''; en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h er K

fe

bl a r fe

Practice 11-3: Setting Up a User for the world_innodb Database

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

-- All steps at the mysql prompt -- Step 1 CREATE USER 'student'@'pc.example.com'; -- Step 2 SELECT user, host, password FROM mysql.user WHERE user = 'student'; -- Step 3 GRANT SELECT, INSERT, DELETE, UPDATE ON world_innodb.* TO 'student'@'pc.example.com' IDENTIFIED BY 'student_pass'; -- Step 4 SHOW GRANTS FOR 'student'@'pc.example.com'\G -- Step 5 REVOKE DELETE, UPDATE ON world_innodb.* FROM 'student'@'pc.example.com'; SHOW GRANTS for 'student'@'pc.example.com'\G

S

er e f a

e

bl a r fe

s

an r t n

o n a -- Step 6 s ฺ a GRANT USAGE ON *.* TO 'student'@'pc.example.com' h ) IDENTIFIED BY 'NewPass'; de i m u o ฺc nt G n -- Step 7 e te tude GRANT ALL ON world_innodb.* TOa'student'@'pc.example.com' w IDENTIFIED BY 'NewPass' S @ s i n WITH MAX_CONNECTIONS_PER_HOUR 10; h ha se t SHOW GRANTS for 'student'@'pc.example.com'\G k ฺ r ee e to u -- Step 8 af (s'student'@'pc.example.com'; DROP n USER ns e a c h user, li host, password FROM mysql.user KSELECT WHERE user='student';

Practice 11-4: Using the PAM Authentication Plugin -- Step 1 -- (at the linux terminal) su useradd pamuser1 passwd pamuser1 -- Step 2 -- The new contents of /etc/pam.d/mysql-dba-course are reproduced here for convenience. #%PAM-1.0 auth include password-auth account include password-auth -- Step 3 chmod 440 /etc/shadow chgrp mysql /etc/shadow

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 26

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

-- Step 4 -- (at the mysql prompt) INSTALL PLUGIN authentication_pam SONAME 'authentication_pam.so'; -- Step 5 SHOW PLUGINS; -- Step 6 CREATE USER pamuser1@localhost IDENTIFIED WITH authentication_pam AS 'mysql-dba-course'; -- Step 7 GRANT SELECT ON world_innodb.City TO pamuser1@localhost; -- Step 8 -- (at the linux terminal) mysql --enable-cleartext-plugin -upamuser1 -p

e

s

-- Step 9 -- (at the mysql prompt) SELECT CURRENT_USER();

an r t n

o

n a s -- Step 10 ha deฺ EXIT ) m ui o c G ฺ -- Step 11 en dent e -- (at the linux terminal) t useradd pamuser2 wa s Stu @ passwd pamuser2 n hi a t h e rฺk o us -- Step 12 e e f t groupadd dba adba e s s usermod (-G pamuser2 an licen h er K-- Step 13

fe Sa

bl a r fe

-- (at the mysql prompt) CREATE USER world_admin@localhost IDENTIFIED BY 'u=aX;yö#Qq'; GRANT ALL PRIVILEGES ON world_innodb.* TO world_admin@localhost; -- Step 14 CREATE USER ''@'' IDENTIFIED WITH authentication_pam AS 'mysql-dba-course, dba=world_admin'; -- Step 15 GRANT PROXY ON world_admin@localhost TO ''@''; -- Step 16 -- (at the linux terminal) mysql --enable-cleartext-plugin -upamuser2 -p

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 27

-- Step 17 -- (at the mysql prompt) SELECT CURRENT_USER();

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

-- Step 18 EXIT

Practice 11-5: Additional Practice -- Step 1 -- (at the linux terminal) mysql --login-path=admin -- (at the mysql prompt) SELECT user, host, password FROM mysql.user WHERE user=''; DROP USER ''@''; -- Step 2 CREATE USER 'Stefan'@'localhost' IDENTIFIED BY 'weak'; SELECT user, host, password FROM mysql.user WHERE user = 'Stefan';

S

er e f a

e

an r t n

no a s ฺ a -- Step 3 h ) de GRANT ALL ON world_innodb.* TO 'Stefan'@'localhost'; i m u o SHOW GRANTS FOR 'Stefan'@'localhost'\G ฺc nt G n e ate Stude -- Step 4 w mysql -uStefan -pweak @ his n a h se t k -- Step 5 ฺ r u e 'Stefan'@'localhost' SET PASSWORDfe FOR = PASSWORD('new_pass'); o t a EXIT e s ( ens n a c terminal) K--h(at the lilinux mysql -uStefan -pnew_pass -- Step 6 mysql -uroot -p -- (at the mysql prompt) REVOKE ALL ON world_innodb.* FROM 'Stefan'@'localhost'; GRANT ALL ON world_innodb.Country TO 'Stefan'@'localhost'; GRANT ALL ON world_innodb.CountryLanguage TO 'Stefan'@'localhost'; SHOW GRANTS FOR 'Stefan'@'localhost'\G -- Step 7 GRANT SELECT (Name, Population) ON world_innodb.City TO 'Stefan'@'localhost'; SHOW GRANTS FOR 'Stefan'@'localhost'\G EXIT -- Step 8 -- (at the linux terminal) mysql -uStefan -pnew_pass Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix: Practice Solutions Scripts Chapter 21 - Page 28

s

bl a r fe

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

-- (at the mysql prompt) USE world_innodb SELECT * from Country\G SELECT * from CountryLanguage; SELECT * FROM City; SELECT Name FROM City; EXIT -- Step 9 CREATE USER 'UserGroup4_01'@'localhost' IDENTIFIED BY '0004nq2'; GRANT ALL ON world_innodb.Country TO 'UserGroup4_01'@'localhost'; GRANT ALL ON world_innodb.CountryLanguage TO 'UserGroup4_01'@'localhost'; GRANT SELECT ON world_innodb.City TO 'UserGroup4_01'@'localhost'; SHOW GRANTS FOR 'UserGroup4_01'@'localhost'\G -- Step 10 DROP USER 'UserGroup4_01'@'localhost'; SHOW GRANTS FOR 'UserGroup4_01'@'localhost'\G

e

s

USE test;

-- Step 12 -- at the t1 prompt SELECT SLEEP(60); -- at the t2 prompt SELECT Code FROM City, Country, CountryLanguage LIMIT 10000000; -- at the t3 prompt SHOW PROCESSLIST; SHOW PROCESSLIST\G

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 29

an r t n

o

n a s -- Step 11 ha deฺ -- (at the mysql prompt) ) m PROMPT t1> ; ui o c G ฺ SHOW PROCESSLIST; en dent e t tu -- (at another Linux prompt)wa S @ s mysql -uStefan -pnew_pass n hi a t PROMPT t2> ; h e rฺk o us USE world_innodb; e e f t aanother e s s -- (at yet Linux prompt) ( n n e mysql --login-path=admin a c h li K PROMPT t3> ; r e

fe Sa

bl a r fe

Lesson 12: Security Practice 12-1: Quiz – MySQL Security

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

No script for this practice

Practice 12-2: Determining the Status of SSL Connectivity -- Step 1 -- (at the linux terminal) mysql --login-path=admin -- (at the mysql prompt) SHOW VARIABLES LIKE 'have_ssl'; -- Step 2 SHOW STATUS LIKE 'Ssl_cipher'; EXIT

e

no a s ฺ a h ) de i m u o cd /etc ฺc nt G n e mkdir newcerts ate Stude cd newcerts w openssl genrsa 2048 > ca-key.pem @ his 1000 \ n openssl req -new -x509 -nodes t-days a e -key ca-key.pem ฺkh u> sca-cert.pem r e -- follow the practice esequence toin the-days af-newkey openssl (req rsa:2048 1000 -nodes \ e s s n -keyout server-key.pem > server-req.pem n e a lic sequence in the practice --hfollow the K er openssl x509 -req -in server-req.pem -days 1000 -CA ca-cert.pem \ -- Step 1 -- (at the linux terminal) su -

Sa

s

an r t n

Practice 12-3: Additional Practice – Enabling MySQL Support for SSL Connections

fe

-CAkey ca-key.pem -set_serial 01 > server-cert.pem openssl req -newkey rsa:2048 -days 1000 -nodes \ -keyout client-key.pem > client-req.pem -- follow the sequence in the practice openssl x509 -req -in client-req.pem -days 1000 -CA ca-cert.pem \ -CAkey ca-key.pem -set_serial 01 > client-cert.pem -- Step 2 ls

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 30

bl a r fe

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

-- Step 3 -- (at the linux terminal) mysql --login-path=admin -- (at the mysql prompt) GRANT SELECT ON mysql.user TO 'Stefan'@'localhost' IDENTIFIED BY 'new_pass' REQUIRE SSL; SHOW GRANTS FOR 'Stefan'@'localhost'\G EXIT

-- Step 4 -- (at the linux terminal) service mysql restart --ssl-ca=/etc/newcerts/ca-cert.pem \ --ssl-cert=/etc/newcerts/server-cert.pem \ --ssl-key=/etc/newcerts/server-key.pem

s

-- Step 5 mysql -uStefan -pnew_pass

o

an r t n

an s ha deฺ ) m -- Step 7 ui o c G ฺ -- (at the mysql prompt) en dent SHOW VARIABLES LIKE 'have_ssl'; te SHOW STATUS LIKE 'Ssl_cipher'; wa s Stu @ n hi a t -- Step 8 h e rฺk o us EXIT e e af se t -- Step (9s en terminal) -- (at an the lilinux c h er Kservice mysql restart

-- Step 6 mysql -uStefan -pnew_pass --ssl-ca=/etc/newcerts/ca-cert.pem

Sa

e

bl a r fe

fe

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 31

Lesson 13: Table Maintenance Practice 13-1: Quiz – Table Maintenance

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

No script for this practice

Practice 13-2: Using Table Maintenance SQL Statements -- Step 1 -- (at the linux terminal) mysql --login-path=admin -- (at the mysql prompt) USE world_innodb CREATE TABLE City_temp LIKE City; INSERT INTO City_temp SELECT * FROM City; SHOW TABLE STATUS LIKE 'City_temp' \G

e

-- Step 2 CHECK TABLE City_temp\G

s

-- Step 3 DELETE FROM City_temp WHERE Id BETWEEN 1001 AND 2000; SHOW TABLE STATUS LIKE 'City_temp' \G

-- Step 3 mysqlcheck --login-path=admin --all-databases --analyze

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 32

an r t n

o

an s a eฺ h ) -- Step 4 om Guid ANALYZE TABLE City_temp; c ฺ SHOW TABLE STATUS LIKE 'City_temp' e\Gn dent e t EXIT wa s Stu @ n hiUtilities a t Practice 13-3: Using Table h Maintenance e rฺk o us -- Step 1 e e f terminal) t -- (at thealinux e s s ( mysqlcheck -uroot -p n --databases world_innodb n e a c h li K -- Step 2 r e afe mysqlcheck --login-path=admin --all-databases

S

bl a r fe

Lesson 14: Exporting and Importing Data

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

Practice 14-1: Exporting MySQL Data -- Step 1 -- (at the linux terminal) mysql -uroot -poracle -- (at the mysql prompt) USE world_innodb; SELECT * INTO OUTFILE '/tmp/CountryLanguage.txt' FROM CountryLanguage; -- Step 2 -- (at the linux terminal) more /tmp/CountryLanguage.txt -- Step 3 -- (at the mysql prompt) SELECT * INTO OUTFILE '/tmp/CountryLanguage.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' FROM CountryLanguage;

e

s

-- Step 3 LOAD DATA INFILE '/tmp/CountryLanguage.txt' INTO TABLE CountryLanguage2; -- Step 4 SELECT * FROM CountryLanguage2; EXIT

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 33

an r t n

o

an s ha deฺ ) i m -- Step 4 u o c G ฺ -- (at the linux terminal) n ent more /tmp/CountryLanguage.csv tee a Stud w Practice 14-2: Importing Dataan@ this -- Step 1 kh use ฺprompt) r e -- (at the mysql feCountryLanguage2 to a CREATE TABLE LIKE CountryLanguage; e s s ( n an 2 lice --hStep K er SHOW TABLES; e f a

S

bl a r fe

Lesson 15: Programming Inside MySQL

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

Practice 15-1: Creating Stored Routines -- Step 1 -- (at the linux terminal) mysql --login-path=admin -- (at the mysql prompt) USE world_innodb; DELIMITER // CREATE PROCEDURE record_count () BEGIN SELECT 'Country count ', COUNT(*) FROM Country; SELECT 'City count ', COUNT(*) FROM City; SELECT 'CountryLanguage count', COUNT(*) FROM CountryLanguage; END//

e

DELIMITER ;

s

Sa

fe

an r t n

o

an s ha deฺ ) -- Step 3 om Gui c ฺ USE test; en dent e CALL record_count(); t wa s Stu @ -- Step 4 n hi a t h CALL world_innodb.record_count(); e rฺk o us e e t -- Step 5 af e s s ( USE world_innodb; an licen h er KDELIMITER // -- Step 2 CALL record_count();

CREATE FUNCTION pay_check (gross_pay FLOAT(9,2), tax_rate FLOAT(3,2)) RETURNS FLOAT(9,2) NO SQL BEGIN DECLARE net_pay FLOAT(9,2) DEFAULT 0; SET net_pay=gross_pay - gross_pay * tax_rate; RETURN net_pay; END// DELIMITER ; -- Step 6 SELECT pay_check (100000, 0.05);

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 34

bl a r fe

Practice 15-2: Reviewing Stored Routines

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

-- Step 1 SHOW CREATE PROCEDURE record_count\G -- Step 2 SHOW PROCEDURE STATUS LIKE 'record%'\G -- Step 3 SHOW FUNCTION STATUS\G -- Step 4 USE INFORMATION_SCHEMA; SELECT * FROM ROUTINES\G

Practice 15-3: Creating a Trigger

e

-- Step 1 USE world_innodb;

s

CREATE TABLE DeletedCity ( ID INT UNSIGNED, Name VARCHAR(50), When_Deleted timestamp);

DELETE FROM City WHERE Name = 'Dallas';

-- Step 5 SELECT * FROM City WHERE Name = 'Dallas'; -- Step 6 SELECT * FROM DeletedCity;

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 35

an r t n

o

an s ha deฺ ) i m -- Step 2 u o c G ฺ CREATE TRIGGER City_AD AFTER DELETE n t n e ON City FOR EACH ROW e e t a Stud INSERT INTO DeletedCity (ID,wName) @ his VALUES (OLD.ID, OLD.Name); n a h se t k ฺ r ee e to u -- Step 3 f a SHOW TRIGGERS\G (s ens n a ic --hStep 4 l K er

fe Sa

bl a r fe

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

Practice 15-4: Creating and Testing an Event -- Step 1 DELIMITER // CREATE EVENT kill_user ON SCHEDULE EVERY 20 SECOND DO BEGIN DECLARE var_id INT; DECLARE procs CURSOR FOR SELECT id FROM INFORMATION_SCHEMA.PROCESSLIST WHERE TIME>30 AND Command != 'Sleep' AND USER != 'root'; OPEN procs; BEGIN DECLARE EXIT HANDLER FOR NOT FOUND BEGIN CLOSE procs; END; LOOP FETCH procs INTO var_id; KILL var_id; END LOOP; END; END// DELIMITER ;

Sa

e

s

-- (at the linux terminal) mysql -utester -p -- Step 6 -- (at the mysql prompt) SELECT SLEEP(60); -- Step 7 EXIT

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 36

an r t n

o

an s ha deฺ ) om Gui c ฺ n ent -- Step 2 e e t SET GLOBAL event_scheduler = ON; a Stud w @ his -- Step 3 n a t h se IDENTIFIED CREATE USER tester@localhost BY 'secret'; k ฺ r u e e e to -- Step 4 af s s TO tester@localhost; ( ON GRANTnSELECT n*.* e a c h li K -- Step 5 r e

fe

bl a r fe

Lesson 16: MySQL Backup and Recovery Practice 16-1: Quiz – Introduction to Backups

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

No script for this practice

Practice 16-2: MySQL Enterprise Backup -- Step 1 -- (at the linux terminal) su mkdir /backups chown mysql:mysql /backups -- Step 2, Step 3, Step 4, Step 5 -- The contents of the new my.cnf file are reproduced here for convenience [mysqld] innodb_autoextend_increment=128 innodb_buffer_pool_size=2GB innodb_buffer_pool_instances=2 log-bin=mybinlog innodb_log_files_in_group = 2 innodb_log_file_size = 256M innodb_data_file_path=ibdata1:12M:autoextend datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock user=mysql # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0

s

o

an r t n

Sa

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e [mysqld_safe] af se t s log-error=/var/log/mysqld.log ( pid-file=/var/run/mysqld/mysqld.pid an licen h er K[mysqlbackup]

fe

backup-dir=/backups/meb1 user=backupuser socket=/var/lib/mysql/mysql.sock -- Step 6 rm -f /var/lib/mysql/ib_logfile* -- Step 7 service mysql restart -- Step 8 mysql --login-path=admin

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 37

e

bl a r fe

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

-- Step 9 -- (at the mysql prompt) CREATE USER 'backupuser'@'localhost' IDENTIFIED BY 'oracle'; GRANT RELOAD ON *.* TO 'backupuser'@'localhost'; GRANT CREATE, INSERT, DROP ON mysql.ibbackup_binlog_marker TO 'backupuser'@'localhost'; GRANT CREATE, INSERT, DROP ON mysql.backup_progress TO 'backupuser'@'localhost'; GRANT CREATE, INSERT, DROP ON mysql.backup_history TO 'backupuser'@'localhost'; GRANT REPLICATION CLIENT ON *.* TO 'backupuser'@'localhost'; GRANT SUPER ON *.* TO 'backupuser'@'localhost'; GRANT CREATE TEMPORARY TABLES ON mysql.* TO 'backupuser'@'localhost'; -- Step 10 USE world_innodb; CREATE TABLE City_Large LIKE City; -- Step 11 INSERT INTO City_Large (Name, CountryCode, District, Population) SELECT Name, CountryCode, District, Population FROM City;

S

er e f a

e

s

-- Step 14 FLUSH LOGS;

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 38

an r t n

o

an s ha deฺ -- Step 12 ) mDistrict, INSERT INTO City_Large (Name, CountryCode, ui o c G ฺ Population) SELECT Name, CountryCode, t n en District, e e Population FROM City_Large; t a Stud w @ his -- Step 13 n a INSERT INTO City_Large (Name, h se tCountryCode, District, k ฺ r Population) SELECT Name, u CountryCode, District, e City_Large; e o f t Population FROM a City_Large s se (Name, CountryCode, District, INSERT INTO ( n n e Population) SELECT Name, CountryCode, District, ha licFROM KPopulation City_Large; INSERT INTO City_Large (Name, CountryCode, District, Population) SELECT Name, CountryCode, District, Population FROM City_Large; INSERT INTO City_Large (Name, CountryCode, District, Population) SELECT Name, CountryCode, District, Population FROM City_Large; INSERT INTO City_Large (Name, CountryCode, District, Population) SELECT Name, CountryCode, District, Population FROM City_Large; INSERT INTO City_Large (Name, CountryCode, District, Population) SELECT Name, CountryCode, District, Population FROM City_Large; INSERT INTO City_Large (Name, CountryCode, District, Population) SELECT Name, CountryCode, District, Population FROM City_Large;

bl a r fe

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

-- Step 15 INSERT INTO City_Large (Name, CountryCode, District, Population) SELECT Name, CountryCode, District, Population FROM City_Large; -- Step 16 -- (at the linux terminal) su mysql mysqlbackup --defaults-file=/etc/my.cnf -p backup-and-apply-log -- Step 17 ls /backups/meb1/ -- Step 18 exit cd /var/lib/mysql rm -f ibdata1 rm -rf world_innodb

e

s

-- Step 19 -- (at the mysql prompt) SHOW DATABASES;

an r t n

o

n a s -- Step 20 ha deฺ EXIT; ) m ui o c G ฺ -- Step 21 en dent e -- (at the linux terminal) t service mysql stop wa s Stu @ n hi a t -- Step 22 h e rฺk o us su mysql e e t mysqlbackup copy-back af--defaults-file=/etc/my.cnf e s s ( an licen h er K-- Step 23

fe Sa

bl a r fe

exit service mysql start

-- Step 24 mysql --login-path=admin -- (at the mysql prompt) SHOW DATABASES; -- Step 25 USE world_innodb SHOW TABLES; -- Step 26 EXIT -- (at the linux terminal) exit

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 39

Practice 16-3: mysqldump

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

-- Step 1 -- (at the linux terminal) mysqldump -uroot -p --tab=/backups world_innodb -- Step 2 ls /backups -l -- Step 3 more /backups/Country.sql -- Step 4 head /backups/Country.txt -- Step 5 mysqladmin -uroot -p create world3 -- Step 6 cd /backups mysql -uroot -poracle world3 < Country.sql mysql -uroot -poracle world3 < CountryLanguage.sql mysql -uroot -poracle world3 < City.sql

S

er e f a

e

an r t n

no a s ฺ a h ) -- Step 7 de i m u o mysqlimport -uroot -poracle world3 /backups/Country.txt ฺc nt G n mysqlimport -uroot -poracle world3e/backups/CountryLanguage.txt de mysqlimport -uroot -poracle world3 ate /backups/City.txt u t w S @ s i n -- Step 8 h ha se t mysql -uroot -poracle k ฺ r u ee prompt) o f t -- (at the mysql a (s ense USE world3 n haTABLES; lic KSHOW -- Step 9 SELECT COUNT(*) FROM world3.City; SELECT COUNT(*) FROM world_innodb.City; -- Step 10 SELECT COUNT(*) SELECT COUNT(*) SELECT COUNT(*) SELECT COUNT(*)

FROM FROM FROM FROM

world3.Country; world_innodb.Country; world3.CountryLanguage; world_innodb.CountryLanguage;

-- Step 11 EXIT

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 40

s

bl a r fe

Practice 16-4: Backup and Recovery Using LVM Snapshots and the Binary Log

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

-- Step 1 -- (at the linux terminal) service mysql stop -- Step 2 dd if=/dev/zero of=/var/local/mysqldisk bs=1M count=2000 losetup /dev/loop2 /var/local/mysqldisk vgcreate VG_MYSQL /dev/loop2 lvcreate -l50%VG -n lv_datadir VG_MYSQL mkfs.ext4 /dev/VG_MYSQL/lv_datadir mkdir -p /datadir mount /dev/VG_MYSQL/lv_datadir /datadir rmdir /datadir/lost+found cp -a /var/lib/mysql/* /datadir/ chown mysql:mysql /datadir

e

-- Step 3 mkdir /binlogs chown mysql:mysql /binlogs

s

an r t n

o

S

er e f a

bl a r fe

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

-- Step 4 -- The contents of the my.cnf file are reproduced here for convenience [root@EDTDR20P1 backups]# cat /etc/my.cnf [mysqld] innodb_autoextend_increment=128 innodb_buffer_pool_size=2GB innodb_buffer_pool_instances=2 log-bin=/binlogs/mysql-bin innodb_log_files_in_group = 2 innodb_log_file_size = 256M innodb_data_file_path=ibdata1:12M:autoextend datadir=/datadir socket=/var/lib/mysql/mysql.sock user=mysql # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0 [mysqld_safe] log-error=/var/log/mysqld.log pid-file=/var/run/mysqld/mysqld.pid [mysqlbackup] backup-dir=/backups/meb1 user=backupuser socket=/var/lib/mysql/mysql.sock -- Step 5 service mysql start -- Step 6 ls /binlogs

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 41

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

-- Step 7 mysql --login-path=admin -- (at the mysql prompt) DROP DATABASE world_innodb; CREATE DATABASE world_innodb; USE world_innodb SET autocommit=0; SOURCE /labs/world_innodb.sql SET autocommit=1; -- Step 8 SHOW TABLES; -- Step 9 SHOW PROCESSLIST; -- Step 10 CREATE TABLE City_Large LIKE City; INSERT INTO City_Large (Name, CountryCode, District, Population) SELECT Name, CountryCode, District, Population FROM City;

S

er e f a

e

s

an r t n

o

n a s SET autocommit=0; ha deฺ ) mDistrict, INSERT INTO City_Large (Name, CountryCode, ui o c G ฺ Population) SELECT Name, CountryCode, t n en District, e e Population FROM City_Large; t aCountryCode, tud District, INSERT INTO City_Large (Name, w S @CountryCode, Population) SELECT Name, is District, n h a t Population FROM City_Large; ฺkh (Name, se CountryCode, District, r INSERT INTO City_Large u e feSELECTe Name, to CountryCode, District, Population) a s Population ( FROM nsCity_Large; n e INSERT INTOic City_Large (Name, CountryCode, District, a h l SELECT Name, KPopulation) CountryCode, District, Population FROM City_Large; INSERT INTO City_Large (Name, CountryCode, District, Population) SELECT Name, CountryCode, District, Population FROM City_Large; INSERT INTO City_Large (Name, CountryCode, District, Population) SELECT Name, CountryCode, District, Population FROM City_Large; INSERT INTO City_Large (Name, CountryCode, District, Population) SELECT Name, CountryCode, District, Population FROM City_Large; INSERT INTO City_Large (Name, CountryCode, District, Population) SELECT Name, CountryCode, District, Population FROM City_Large;

-- Step 11 -- (at the linux terminal) mysqladmin -uroot -poracle flush-logs lvcreate -s -n lv_datadirbackup -L 500M /dev/VG_MYSQL/lv_datadir -- Step 12 SET autocommit=1; Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Appendix: Practice Solutions Scripts Chapter 21 - Page 42

bl a r fe

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

-- Step 13 -- (at the mysql prompt) INSERT INTO City(Name, CountryCode) VALUES ('Sakila', 'SWE'); SELECT * FROM City ORDER BY ID DESC LIMIT 1; DROP TABLE City; -- Step 14 -- (at the linux terminal) mkdir /root/snapshot mount /dev/VG_MYSQL/lv_datadirbackup /root/snapshot cd /root/snapshot tar -czf /root/mysqldatadir.tgz . cd umount /root/snapshot -- Step 15 lvremove VG_MYSQL/lv_datadirbackup -f

e

-- Step 16 lvresize -fL 1M VG_MYSQL/lv_datadir

fe

an r t n

o

an s ha deฺ ) m ui o c G ฺ -- Step 18 en dent e -- (at the linux terminal) t service mysql stop wa s Stu @ mysqladmin -uroot -poracle n shutdown hi a t h e rฺk o us -- Step 19 e e t ps ax | grep af mysqld e s s ( -- Step an 20 licen h er Kkillall -9 mysqld_safe -- Step 17 -- (at the mysql prompt) SHOW DATABASES; DROP DATABASE world3;

Sa

s

-- Step 21 ps ax | grep mysqld -- Step 22 umount /datadir lvremove -f VG_MYSQL/lv_datadir lvcreate -l50%VG -n lv_datadir VG_MYSQL mkfs.ext4 /dev/VG_MYSQL/lv_datadir mount /dev/VG_MYSQL/lv_datadir /datadir rmdir /datadir/lost+found chown mysql:mysql /datadir -- Step 23 cd /datadir tar -xzf /root/mysqldatadir.tgz -- Step 24 service mysql start

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 43

bl a r fe

-- Step 25 mysql --login-path=admin

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

-- (at the mysql prompt) USE world_innodb SELECT * FROM City ORDER BY ID DESC LIMIT 1; -- Step 26 -- (at the linux terminal) ls /binlogs -l -- Step 27 mysqlbinlog /binlogs/mysql-bin.000002 | more -- Step 28 cd /binlogs mysqlbinlog --disable-log-bin --stop-position=807 \ mysql-bin.000002 | mysql -uroot -poracle

e

s

bl a r fe

-- Step 29 -- (at the mysql prompt) SELECT * FROM world_innodb.City WHERE ID > 4070;

Sa

an s ha deฺ -- Step 30 ) m -- (at the linux terminal) ui o c G ฺ service mysql stop t n enpractice e e -- change the my.cnf file as in tthe a Stud service mysql start w @ his n a h se t k ฺ r ee e to u f a (s ens n ha lic K er

o

fe

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 44

an r t n

Lesson 17: Replication Practice 17-1: Quiz – Replication

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

No script for this practice

e

s

bl a r fe

o

an r t n

er e f a

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 45

Practice 17-2: Configuring Replication

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

-- Step 1 -- (at the linux terminal) service mysql stop -- Step 2 cat /labs/repl.cnf -- Step 3 mysqld_multi --defaults-file=/labs/repl.cnf start 1-4 -- Step 4 mysql -uroot -h127.0.0.1 -P3311 -- (at the mysql prompt) PROMPT 1> ;

e

-- Step 5 SHOW MASTER STATUS \G

s

-- Step 6 CREATE USER 'repl'@'127.0.0.1' IDENTIFIED BY 'oracle'; GRANT REPLICATION SLAVE ON *.* TO 'repl'@'127.0.0.1';

S

er e f a

bl a r fe

an s ha deฺ ) -- Step 7 om Gui CREATE DATABASE world_innodb; c ฺ n ent USE world_innodb e e t SET autocommit=0; a Stud w SOURCE /labs/world_innodb.sql @ his SET autocommit=1; n a h se t k ฺ r u -- Step 8 ee terminal) o f t -- (at thealinux se (s -h127.0.0.1 mysqln-uroot -P3312 n e a c i h l K-- (at the mysql prompt)

o

PROMPT 2> ; -- Step 9 CHANGE MASTER TO MASTER_HOST='127.0.0.1', MASTER_PORT=3311, MASTER_LOG_FILE='mysql1-bin.000001', MASTER_LOG_POS=120, MASTER_USER='repl', MASTER_PASSWORD='oracle'; SHOW WARNINGS\G -- Step 10 SHOW DATABASES;

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 46

an r t n

-- Step 11 START SLAVE;

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

-- Step 12 SHOW PROCESSLIST\G SHOW PROCESSLIST\G -- Step 13 SHOW DATABASES;

Practice 17-3: Adding a New Slave -- Step 1 -- (at the linux terminal) mysqldump -uroot -h127.0.0.1 -P3312 --master-data=2 \ -B world_innodb > /tmp/server2.sql

e

-- Step 2 -- Edit the file as described in the practice -- Step 3 mysql -uroot -h127.0.0.1 -P3313

Sa

s

an r t n

o

an -- (at the mysql prompt) s PROMPT 3> ; ha deฺ ) om Gui c -- Step 4 ฺ en dent SOURCE /tmp/server2.sql e t wa s Stu -- Step 5 @ n hi START SLAVE; a t h e SHOW SLAVE STATUS\G rฺk o us e e f t -- Step (6sa e s -- (on 1st enserver) an the c i h l DELETE FROM world_innodb.City WHERE ID > 4070; K r e

fe

-- (on the 2nd server) SELECT * FROM world_innodb.City ORDER BY Id DESC LIMIT 5; -- (on the 3rd server) SELECT * FROM world_innodb.City ORDER BY Id DESC LIMIT 5; -- Step 7 CREATE USER 'repl'@'127.0.0.1' IDENTIFIED BY 'oracle'; GRANT REPLICATION SLAVE ON *.* TO 'repl'@'127.0.0.1';

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 47

bl a r fe

Practice 17-4: Enabling GTID and Configuring Circular Replication

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

-- Step 1 -- (at the linux terminal) mysqld_multi --defaults-file=/labs/repl.cnf --user=root stop 1-4 -- Step 2 -- Follow the step in the practice -- Step 3 mysqld_multi --defaults-file=/labs/repl.cnf start 1-4 -- Step 4 -- (on the second server) STATUS STOP SLAVE;

e

-- (on the third server) STATUS STOP SLAVE;

s

-- Step 5 -- (on the first server) STATUS RESET MASTER;

Sa

an r t n

o

an s ha deฺ ) om Gui -- (on the second server) c ฺ RESET MASTER; en dent e t wa s Stu -- (on the third server) @ RESET MASTER; n hi a t h e rฺk o us -- Step 6 e e f t -- (on theasecond server) e s s ( CHANGE eTOn MASTER_AUTO_POSITION=1; an MASTER c i h l er K-- (on the third server)

fe

bl a r fe

CHANGE MASTER TO MASTER_AUTO_POSITION=1; -- Step 7 -- (on the second server) START SLAVE; -- (on the third server) START SLAVE;

-- Step 8 -- (on the first server) DELETE FROM world_innodb.City WHERE ID > 4060; -- (on the second server) SELECT * FROM world_innodb.City ORDER BY Id DESC LIMIT 5; -- (on the third server) SELECT * FROM world_innodb.City ORDER BY Id DESC LIMIT 5;

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 48

-- Step 9 -- (on the first server) SELECT @@server_uuid;

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

-- (on the second server) SELECT @@server_uuid; -- (on the third server) SELECT @@server_uuid; -- Step 10 SHOW SLAVE STATUS\G -- Step 11 -- (on the first server) CHANGE MASTER TO MASTER_HOST='127.0.0.1', MASTER_PORT=3313, MASTER_USER='repl', MASTER_PASSWORD='oracle', MASTER_AUTO_POSITION=1;

e

bl a r fe

s

START SLAVE;

an r t n

no a s ฺ a h ) de i m -- (on the first server) u o G LIMIT 5; ฺcBY IdnDESC SELECT * FROM world_innodb.City ORDER t n e ate Stude -- (on the third server) w @ hORDER SELECT * FROM world_innodb.City is BY Id DESC LIMIT 5; n a t se and Performing a Failover rฺkh Utilities u e Practice 17-5: UsingeMySQL f to -- Step (1sa e nsserver) -- (on the first n e a c h SLAVE;li STOP K r RESET SLAVE ALL; e e f a -- Step 12 -- (on the second server) DELETE FROM world_innodb.City WHERE ID > 4050;

S

-- Step 2 -- (at the linux terminal) mysql -uroot -h127.0.0.1 -P3314 -- (at the mysql prompt) PROMPT 4> ; -- Step 3 -- (at the fourth server) SOURCE /tmp/server2.sql

-- Step 4 -- (at the linux terminal) /usr/share/mysql-workbench/python/mysqldbcompare \ [email protected]:3311 \ [email protected]:3314 --changes-for=server2 \ --difftype=sql -a world_innodb:world_innodb > /tmp/diff.sql

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 49

-- Step 5 cat /tmp/diff.sql

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

-- Step 6 -- (at the fourth server mysql prompt) SOURCE /tmp/diff.sql -- Step 7 CHANGE MASTER TO MASTER_PORT=3311, MASTER_AUTO_POSITION=1; START SLAVE; -- Step 8 -- (at the linux terminal) /usr/share/mysql-workbench/python/mysqlrplshow \ [email protected]:3311 \ --discover-slaves-login=root --recurse -- Step 9 -- (at the fourth server) CREATE USER 'repl'@'127.0.0.1' IDENTIFIED BY 'oracle'; GRANT REPLICATION SLAVE ON *.* TO 'repl'@'127.0.0.1';

e

an r t n

no a s ฺ a h ) de i m u o ฺc nt G -- Step 11 n e -- (at the linux terminal) ate Stude \ /usr/share/mysql-workbench/python/mysqlfailover w @ his\ [email protected]:3311 n a --discover-slaves-login=root h se t --rpl-user=repl:[email protected] k ฺ r ee e to u f a s ns -- Step (12 n -- Follow the a licesteps in the practice Kh -- Step 10 CREATE USER 'repl'@'localhost' IDENTIFIED BY 'oracle'; GRANT REPLICATION SLAVE ON *.* TO 'repl'@'localhost';

S

er e f a

s

-- Step 13 -- (at the linux terminal) mysqladmin -uroot -h127.0.0.1 -P3311 shutdown -- Step 14 -- No script -- Step 15 /usr/share/mysql-workbench/python/mysqlrplshow \ [email protected]:3314 \ --discover-slaves-login=root --recurse -- Step 16 mysqld_multi --defaults-file=/labs/repl.cnf --user=root stop 1-4 service mysql start

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 50

bl a r fe

Lesson 18: Introduction to Performance Tuning Practice 18-1: Quiz – Introduction to Performance Tuning

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

No script for this practice

Practice 18-2: EXPLAIN -- Step 1 -- (at the linux terminal) mysql --login-path=admin -- (at the mysql prompt) USE world_innodb

-- Step 2 DROP DATABASE world_innodb; CREATE DATABASE world_innodb; USE world_innodb; SET AUTOCOMMIT=0; SOURCE /labs/world_innodb.sql SET AUTOCOMMIT=1;

Sa

e

s

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 51

an r t n

o

an s ha deฺ -- Step 3 ) m 'A%'\G EXPLAIN SELECT Name FROM City WHERE NameoLIKE ui c G ฺ en dent -- Step 4 e t EXPLAIN SELECT Name FROM City ID tu> 4070\G waWHERE S @ s n hi a t -- Step 5 h e -- No script rฺk o us e e af se t -- Step (6s n INDEXiciName en ON City (Name) USING BTREE; CREATE a h l EXPLAIN SELECT Name FROM City WHERE Name LIKE 'A%'\G er K

fe

bl a r fe

Practice 18-3: PROCEDURE ANALYSE

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

-- Step 1 -- (at the mysql prompt) SELECT Name, CountryCode, Population FROM City PROCEDURE ANALYSE()\G -- Step 2 DESC City; -- Step 3 SELECT Name, CountryCode, Population FROM City PROCEDURE ANALYSE(256,1024)\G -- Step 4 SELECT * FROM CountryLanguage PROCEDURE ANALYSE(256,1024)\G

e

bl a r fe

-- Step 5 DESC CountryLanguage;

s

-- Step 6 EXIT

er e f a

o

an r t n

an s ha deฺ ) om Gui c ฺ en dent e t wa s Stu @ n hi a t h e rฺk o us e e af se t s ( an licen h K

S

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

Appendix: Practice Solutions Scripts Chapter 21 - Page 52