1. <Insert Picture Here>
MySQL: What do I have or do now?
Keith Larson
keith.larson@oracle.com
MySQL Community Manager
www.sqlhjalp.com/pdf/mysql_nowwhat.pdf
2. The following is intended to outline our general product
direction. It is intended for information purposes only, and
may not be incorporated into any contract. It is not a
commitment to deliver any material, code, or
functionality, and should not be relied upon in making
purchasing decisions.
The development, release, and timing of any features or
functionality described for Oracle’s products remains at
the sole discretion of Oracle.
Safe Harbor Statement
3. Show you code and options so you understand:
– Access
– Databases
– Tablespace
– Datatypes
– Selects
– Indexes
– Stored Routines
– Triggers
– Views
– Transactions
– Backups
– Replicated
MySQL: Agenda
Copyright Oracle Corporation 2011 3
4. Oracle MySQL
Database (files) == Database Server Instance
Database Instance (memory) == Database Server Instance
Schema User == Database
User == User
Table Space == Table Space
Storage Engine
MySQL Terminology
Copyright Oracle Corporation 2011 4
5. $ mysql -u root
ERROR 1045 (28000): Access denied for user 'root'@'localhost'
(using password: NO)
$ mysql -u root -p
Enter password:
$ mysqladmin -u root -p password <passwordhere>
mysql> UPDATE mysql.user
SET Password=PASSWORD('<passwordhere>')
WHERE User='root';
mysql> FLUSH PRIVILEGES;
Copyright Oracle Corporation 2011 5
MySQL: Account Access
6. http://dev.mysql.com/doc/refman/5.5/en/resetting-permissions.html
Do not know the root password?
Stop the service: # /etc/init.d/mysql stop
Restart with skip grand: # mysqld_safe … --skip-grant-tables &
/usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --
user=mysql --log-error=/var/log/mysqld.log --pid-file=/var/lib/mysql/kdlarson-pc.pid
Connect as root: # mysql -u root
Set new password :
use mysql;
mysql> update user set password=PASSWORD("NEW-ROOT-
PASSWORD") where User='root';
mysql> flush privileges;
mysql> quit
Stop and Start then log in as root with password.
MySQL: Account Access
Copyright Oracle Corporation 2011 6
8. http://dev.mysql.com/doc/refman/5.6/en/grant.html
mysql> CREATE USER ’clark'@'localhost' IDENTIFIED BY
'some_pass';
mysql> GRANT ALTER, CREATE VIEW, CREATE, DELETE,
DROP, GRANT OPTION, INDEX, INSERT, SELECT,
SHOW VIEW, TRIGGER, UPDATE ON *.* TO
’clark'@'localhost' ;
mysql> CREATE USER ’clark'@'%' IDENTIFIED BY
'some_pass';
mysql> GRANT ALTER, CREATE VIEW, CREATE, DELETE,
DROP, GRANT OPTION, INDEX, INSERT, SELECT,
SHOW VIEW, TRIGGER, UPDATE ON *.* TO ’clark'@'%';
mysql> flush privileges ;
MySQL: Account Access-- Users
Copyright Oracle Corporation 2011 8
9. http://dev.mysql.com/doc/refman/5.6/en/grant.html
CREATE USER 'adminhelp'@'%' IDENTIFIED BY 'some_pass';
GRANT ALTER, CREATE VIEW, CREATE, DELETE, DROP, GRANT OPTION,
INDEX, INSERT, SELECT, SHOW VIEW, TRIGGER, UPDATE , RELOAD ON
*.* TO 'adminhelp'@'%' WITH GRANT OPTION;
flush privileges ;
CREATE USER 'adminuser'@'%' IDENTIFIED BY 'some_pass';
GRANT ALTER, CREATE VIEW, CREATE, DELETE, DROP, GRANT OPTION,
INDEX, INSERT, SELECT, UPDATE ON *.* TO 'adminuser'@'%' ;
flush privileges ;
MySQL: Account Access-- Users
Copyright Oracle Corporation 2011 9
10. http://dev.mysql.com/doc/refman/5.6/en/show-grants.html
mysql [localhost] {root} (mysql) > select Host , User FROM mysql.user;
+-----------+----------+
| Host | User |
+-----------+----------+
| % | kdladmin |
| localhost | root |
| localhost | kdladmin |
+-----------+----------+
mysql> SHOW GRANTS FOR CURRENT_USER();
mysql> SHOW GRANTS FOR 'root'@'localhost';
+----------------------------------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost |
+----------------------------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*8CD56861FDADF7A264741F27D502D1A8DAE0A8F7'
WITH GRANT OPTION |
+----------------------------------------------------------------------------------------------------------------------------------------+
MySQL: What User Accounts
Copyright Oracle Corporation 2011 10
16. http://dev.mysql.com/doc/refman/5.6/en/show.html
SHOW CREATE TABLE tbl_name
SHOW CREATE PROCEDURE proc_name
SHOW CREATE TRIGGER trigger_name
SHOW CREATE VIEW view_name
SHOW PROCEDURE CODE proc_name
SHOW PROCEDURE STATUS [like_or_where]
SHOW [FULL] PROCESSLIST
SHOW GRANTS [FOR user]
SHOW WARNINGS [LIMIT [offset,] row_count]
SHOW {DATABASES | SCHEMAS} [LIKE 'pattern' | WHERE expr]
SHOW OPEN TABLES [{FROM | IN} db_name] [LIKE 'pattern' | WHERE expr]
SHOW BINARY LOGS
SHOW MASTER LOGS
MySQL: Show Commands
Copyright Oracle Corporation 2011 16
17. Use SHOW processlist to find out what is going on:
+----+-------+-----------+----+---------+------+--------------+-------------------------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+-------+-----------+----+---------+------+--------------+-------------------------------------+
| 6 | monty | localhost | bp | Query | 15 | Sending data | select * from station,station as s1 |
| 8 | monty | localhost | | Query | 0 | | show processlist |
+----+-------+-----------+----+---------+------+--------------+-------------------------------------+
Use KILL in mysql or mysqladmin to kill off runaway threads.
How to find out how MySQL solves a query
Run the following commands and try to understand the output:
* SHOW VARIABLES;
* SHOW COLUMNS FROM City; (same as Describe City; || Desc City;)
* EXPLAIN SELECT ...G
* FLUSH STATUS;
* SELECT ...;
* SHOW STATUS;
MySQL: Show Processlist
Copyright Oracle Corporation 2011 17
18. A few ways to see what databases you have on your system:
– Review the directories
– Log in to MySQL server
– mysql> create database World;
– mysql> drop database World;
– Show databases
mysql> show databases;
– +--------------------+
– | Database |
– +--------------------+
– | information_schema |
– | db_example |
– | employees |
– | exampledb |
– | mysql |
– | orig |
– | performance_schema |
– +--------------------+
MySQL: Databases/Schema
Copyright Oracle Corporation 2011 18
20. mysql> SHOW ENGINES;
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Engine | Support | Comment | Transactions | XA | Savepoints |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| InnoDB | DEFAULT | Supports transactions, row-level locking, and foreign keys | YES | YES | YES |
| CSV | YES | CSV storage engine | NO | NO | NO |
| MyISAM | YES | MyISAM storage engine | NO | NO | NO |
| BLACKHOLE | YES | /dev/null storage engine (anything you write to it disappears) | NO | NO | NO |
| MEMORY | YES | Hash based, stored in memory, useful for temporary tables | NO | NO | NO |
| ARCHIVE | YES | Archive storage engine | NO | NO | NO |
| PERFORMANCE_SCHEMA | YES | Performance Schema | NO | NO | NO |
| FEDERATED | NO | Federated MySQL storage engine | NULL | NULL | NULL |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
MySQL: Engines
Copyright Oracle Corporation 2011 20
21. mysql> use world;
mysql> show tables;
+-----------------+
| Tables_in_world |
+-----------------+
| City |
| Country |
| CountryLanguage |
+-----------------+
3 rows in set (0.00 sec)
MySQL: Table Space
Copyright Oracle Corporation 2011 21
22. mysql> show create table City;
CREATE TABLE `City` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` char(35) NOT NULL DEFAULT '',
`CountryCode` char(3) NOT NULL DEFAULT '',
`District` char(20) NOT NULL DEFAULT '',
`Population` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`),
KEY `CountryCode` (`CountryCode`),
CONSTRAINT `city_ibfk_1` FOREIGN KEY (`CountryCode`) REFERENCES
`Country` (`Code`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1
MySQL: Table Space
Copyright Oracle Corporation 2011 22
23. mysql > desc City;
+-------------+----------+------+-----+---------+----------------+
| 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.06 sec)
MySQL: Table Space
Copyright Oracle Corporation 2011 23
25. http://dev.mysql.com/doc/refman/5.5/en/data-types.html
TEXT TYPES
CHAR( ) A fixed section from 0 to 255 characters long. 4 bytes
VARCHAR( ) A variable section from 0 to 255 characters long.
TINYTEXT A string with a maximum length of 255 characters.
TEXT A string with a maximum length of 65535 characters.
BLOB A string with a maximum length of 65535 characters.
MEDIUMTEXT A string with a maximum length of 16777215 characters.
MEDIUMBLOB A string with a maximum length of 16777215 characters.
LONGTEXT A string with a maximum length of 4294967295 characters.
LONGBLOB A string with a maximum length of 4294967295 characters.
CREATE TABLE `example_table` (
...
`value` varchar(100) DEFAULT NULL,
...
MySQL: Datatypes
Copyright Oracle Corporation 2011 25
26. http://dev.mysql.com/doc/refman/5.5/en/data-types.html
NUMBER TYPES
TINYINT( ) -128 to 127 normal 0 to 255 UNSIGNED. 1 byte storage
SMALLINT( ) -32768 to 32767 normal 0 to 65535 UNSIGNED. 2 byte storage
MEDIUMINT( ) -8388608 to 8388607 normal 0 to 16777215 UNSIGNED. 3 byte storage
INT( ) -2147483648 to 2147483647 normal 0 to 4294967295 UNSIGNED. 4 byte storage
BIGINT( ) -9223372036854775808 to 9223372036854775807 normal
0 to 18446744073709551615 UNSIGNED. 8 byte storage
FLOAT A small number with a floating decimal point.
DOUBLE( , ) A large number with a floating decimal point.
DECIMAL( , ) A DOUBLE stored as a string , allowing for a fixed decimal point.
MySQL uses 4 bytes for single-precision values and 8 bytes for double-precision values
Create Table: CREATE TABLE `example_table` (
`example_table_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
.....or
`example_table_id` bigint(12) unsigned NOT NULL auto_increment
MySQL: Datatypes
Copyright Oracle Corporation 2011 26
28. http://dev.mysql.com/doc/refman/5.5/en/data-types.html
MISC TYPES
ENUM ( ) Short for ENUMERATION which
means that each column may have one of a
specified possible values.
SET Similar to ENUM except each column
may have more than one of the specified
possible values.
…..
`transfer_method` enum('OFF','EMAIL','FTP','BATCH POST','FTP-SSL','REAL TIME
POST','CUSTOM') default NULL,
`transfer_method` SET('OFF','EMAIL','FTP','BATCH POST','FTP-SSL’) default NULL,
….
MySQL: Datatypes
Copyright Oracle Corporation 2011 28
29. extract basic database information using the SELECT command
What is wrong?
mysql> SELECT
-> C.Name , C.Population , CY.LifeExpectancy
-> FROM City C
-> INNER JOIN Country CY ON C.CountryCode = CY.Code
-> WHERE CY.CountryCode = 'USA' limit 5;
MySQL: Selects
Copyright Oracle Corporation 2011 29
30. extract basic database information using the SELECT command
mysql> SELECT
-> C.Name , C.Population , CY.LifeExpectancy
-> FROM City C
-> INNER JOIN Country CY ON C.CountryCode = CY.Code
-> WHERE CY.CountryCode = 'USA' limit 5;
ERROR 1054 (42S22): Unknown column 'CY.CountryCode' in 'where clause'
MySQL: Selects
Copyright Oracle Corporation 2011 30
31. Use IN not ranges!
Joins and IN are better than sub-queries!
SELECT C.Name , C.Population , CY.LifeExpectancy
FROM City C
INNER JOIN Country CY ON C.CountryCode = CY.Code
WHERE C.CountryCode = 'USA' limit 5;
+--------------+------------+----------------+
| Name | Population | LifeExpectancy |
+--------------+------------+----------------+
| New York | 8008278 | 77.1 |
| Los Angeles | 3694820 | 77.1 |
| Chicago | 2896016 | 77.1 |
| Houston | 1953631 | 77.1 |
| Philadelphia | 1517550 | 77.1 |
+--------------+------------+----------------+
MySQL: Selects
Copyright Oracle Corporation 2011 31
32. SELECT Continent , AVG(LifeExpectancy) as LifeExpectancy , AVG(Population) as
Population
FROM Country
GROUP BY Continent
ORDER BY Continent DESC;
+---------------+----------------+---------------+
| Continent | LifeExpectancy | Population |
+---------------+----------------+---------------+
| South America | 70.94615 | 24698571.4286 |
| Antarctica | NULL | 0.0000 |
| Oceania | 69.71500 | 1085755.3571 |
| Africa | 52.57193 | 13525431.0345 |
| North America | 72.99189 | 13053864.8649 |
| Europe | 75.14773 | 15871186.9565 |
| Asia | 67.44118 | 72647562.7451 |
+---------------+----------------+---------------
MySQL: Selects
Copyright Oracle Corporation 2011 32
33. Joins and IN are better than sub-queries!
SELECT C.Name , C.Population , CY.LifeExpectancy
FROM City C INNER JOIN Country CY ON C.CountryCode = CY.Code
WHERE C.CountryCode IN (SELECT CountryCode FROM City CC WHERE
Population > 3694820);
+------------------+------------+----------------+
| Name | Population | LifeExpectancy |
+------------------+------------+----------------+
| Mumbai (Bombay) | 10500000 | 62.5 |
| Seoul | 9981619 | 74.4 |
| Shanghai | 9696300 | 71.4 |
| Jakarta | 9604900 | 68.0 |
| Karachi | 9269265 | 61.1 |
| Istanbul | 8787958 | 71.0 |
| Moscow | 8389200 | 67.2 |
| New York | 8008278 | 77.1 |
MySQL: Selects with sub-queries
Copyright Oracle Corporation 2011 33
34. MySQL
Data Dictionary = INFORMATION_SCHEMA
See aggregated size per schema per engine:
SELECT TABLE_SCHEMA, ENGINE, COUNT(*) AS count_tables,
SUM(DATA_LENGTH+INDEX_LENGTH) AS size,
SUM(INDEX_LENGTH) AS index_size FROM
INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA NOT IN ('mysql', 'INFORMATION_SCHEMA')
AND ENGINE IS NOT NULL GROUP BY TABLE_SCHEMA, ENGINE
http://code.openark.org/blog/mysql/useful-database-analysis-queries-with-
information_schema
38. MySQL: Performance options
MySQL startup options
Innodb can handle more memory and more cores..
The buffer pool is for caching data and indexes in memory so set the
following to < 80% of the machine physical memory.
Important performance options for indexes are:
innodb_buffer_pool_size < 80% of memory. # default value is 8M
innodb_buffer_pool_instances = 1 #Increase for multi-core boxes
innodb_log_file_size=2G. #dependent on recovery speed required.
innodb_thread_concurrency= (Cores/threads *2) + disks
innodb_flush_log_at_trx_commit = 1
# innodb_file_per_table #depends on how many tables used. Get the big picture 1st.
Copyright Oracle Corporation 2011 38
39. Laptop example for my.cnf
[mysql.server]
key_buffer_size=16M
sort_buffer_size=4M
read_buffer_size=256K
binlog_cache_size=64K
max_connections=500
wait_timeout=1800
bulk_insert_buffer_size= 16M
max_allowed_packet = 50M
tmp_table_size= 1G
tmpdir= /tmp/
table_cache= 1024
query_cache_size=128M
default-table-type= innodb
relay-log =/var/lib/mysql/kdlarson-relay-bin
Copyright Oracle Corporation 2011 39
#innodb
innodb_data_home_dir = /var/lib/mysql
innodb_log_group_home_dir = /var/lib/mysql
innodb_data_file_path = ibdata1:10G:autoextend
innodb_buffer_pool_size=1G
innodb_additional_mem_pool_size=40M
innodb_log_files_in_group=2
# Set the log file size to about
# 25 % of the buffer pool size
innodb_log_file_size=100M
innodb_log_buffer_size=128M
innodb_lock_wait_timeout=600
innodb_table_locks = 0
innodb_status_file = 1
MySQL: Performance options
40. URLS to help for later:
http://dev.mysql.com/doc/refman/5.6/en/mysql-indexes.html
http://dev.mysql.com/doc/refman/5.6/en/show-index.html
http://dev.mysql.com/doc/refman/5.6/en/create-index.html
http://learnmysql.blogspot.com/2010/11/mysql-query-and-index-tuning.html
http://www.slideshare.net/manikandakumar/mysql-query-and-index-tuning
http://www.slideshare.net/osscube/indexing-the-mysql-index-key-to-performance-tuning
http://effectivemysql.com/downloads/ImprovingPerformanceWithBetterIndexes-OOW-2011.pdf
http://prajwal-tuladhar.net.np/2009/09/23/474/things-you-should-know-about-mysql-index/
http://dev.mysql.com/doc/refman/5.5/en/innodb-monitors.html
http://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html
http://dev.mysql.com/doc/refman/5.5/en/innodb-buffer-pool.html
http://www.mysqlperformanceblog.com/2006/07/17/show-innodb-status-walk-through/
http://dev.mysql.com/doc/refman/5.5/en/server-parameters.html
http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_key_buffer_size
http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_table_open_cache
http://www.mysqlperformanceblog.com/2007/11/01/innodb-performance-optimization-basics/
http://www.mysqlperformanceblog.com/2007/11/03/choosing-innodb_buffer_pool_size/
MySQL: Indexes
Copyright Oracle Corporation 2011 40
41. MySQL: Indexes (keys)
When MySQL uses indexes
Using >, >=, =, <, <=, IF NULL and BETWEEN on a key.
o SELECT * FROM table_name WHERE key_part1=1 and key_part2 > 5;
o SELECT * FROM table_name WHERE key_part1 IS NULL;
* When you use a LIKE that doesn't start with a wildcard.
o SELECT * FROM table_name WHERE key_part1 LIKE 'jani%'
* Retrieving rows from other tables when performing joins.
o SELECT * from t1,t2 where t1.col=t2.key_part
* Find the MAX() or MIN() value for a specific index.
o SELECT MIN(key_part2),MAX(key_part2) FROM table_name where
key_part1=10
* ORDER BY or GROUP BY on a prefix of a key.
o SELECT * FROM foo ORDER BY key_part1,key_part2,key_part3
* When all columns used in the query are part of one key.
o SELECT key_part3 FROM table_name WHERE key_part1=1
Copyright Oracle Corporation 2011 41
42. MySQL: Indexes (keys)
When MySQL doesn't use an index
* Indexes are NOT used if MySQL can calculate that it will probably be faster to
scan the whole table.
For example if key_part1 is evenly distributed between 1 and 100, it's not good to use
an index in the following query:
o SELECT * FROM table_name where key_part1 > 1 and key_part1 < 90
* If you are using HEAP tables and you don't search on all key parts with =
* When you use ORDER BY on a HEAP table
* If you are not using the first key part
o SELECT * FROM table_name WHERE key_part2=1
* If you are using LIKE that starts with a wildcard
o SELECT * FROM table_name WHERE key_part1 LIKE '%jani%'
* When you search on one index and do an ORDER BY on another
o SELECT * from table_name WHERE key_part1 = # ORDER BY key2
Copyright Oracle Corporation 2011 42
43. MySQL: Indexes (keys)
Optimizing tables
Use NOT NULL for columns which will not store null values. This is particularly
important for columns which you index.
`e_id` bigint(12) unsigned NOT NULL
Don't create indexes you are not going to use.
Use the fact that MySQL can search on a prefix of an index; If you have and INDEX
(a,b), you don't need an index on (a).
UNIQUE KEY `uq_id` (`u_id`,`q_id`),
KEY `q_id` (`q_id`),
Instead of creating an index on long CHAR/VARCHAR column, index just a prefix of
the column to save space.
CREATE TABLE `table_name` (
`hostname` varchar(255) NOT NULL,
KEY `hostname` (`hostname`(10))
) ENGINE=InnoDB
Copyright Oracle Corporation 2011 43
44. MySQL: Indexes (keys)
SHOW INDEXES FROM CityG
*************************** 1. row ***************************
Table: City
Non_unique: 0
Key_name: PRIMARY
Seq_in_index: 1
Column_name: ID
Collation: A
Cardinality: 4051
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:
Copyright Oracle Corporation 2011 44
*************************** 2. row ***************************
Table: City
Non_unique: 1
Key_name: CountryCode
Seq_in_index: 1
Column_name: CountryCode
Collation: A
Cardinality: 506
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:
2 rows in set (0.02 sec)
45. More Urls for you to use later
http://effectivemysql.com/downloads/ExplainingTheMySQLEXPLAIN-OOW-2011.pdf
http://prajwal-tuladhar.net.np/2009/09/26/481/know-more-about-mysql-explain/
http://www.slideshare.net/ligaya/explain
MySQL: Index – Use Explain!
Copyright Oracle Corporation 2011 45
46. Use EXPLAIN on every query that you think is too slow!
mysql> explain select t3.DateOfAction, t1.TransactionID
-> from t1 join t2 join t3
-> where t2.ID = t1.TransactionID and t3.ID = t2.GroupID
-> order by t3.DateOfAction, t1.TransactionID;
+-------+--------+---------------+---------+---------+------------------+------+---------------------------------+
| table | type | possible_keys | key | key_len | ref | rows | Extra |
+-------+--------+---------------+---------+---------+------------------+------+---------------------------------+
| t1 | ALL | NULL | NULL | NULL | NULL | 11 | Using temporary; Using filesort |
| t2 | ref | ID | ID | 4 | t1.TransactionID | 13 | |
| t3 | eq_ref | PRIMARY | PRIMARY | 4 | t2.GroupID | 1 | |
+-------+--------+---------------+---------+---------+------------------+------+---------------------------------+
Types ALL and range signal a potential problem.
MySQL: Index – Use Explain!
Copyright Oracle Corporation 2011 46
47. mysql> EXPLAIN SELECT C.Name , T.Name FROM world.City C INNER JOIN
world.Country T ON C.CountryCode = T.Code;
+----+-------------+-------+------+---------------+-------------+---------+--------------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
|
+----+-------------+-------+------+---------------+-------------+---------+--------------+------+-------+
| 1 | SIMPLE | T | ALL | PRIMARY | NULL | NULL | NULL | 264 |
|
| 1 | SIMPLE | C | ref | CountryCode | CountryCode | 3 | world.T.Code | 8 |
|
+----+-------------+-------+------+---------------+-------------+---------+--------------+------+-------+
MySQL: Index – Use Explain!
Copyright Oracle Corporation 2011 47
48. MySQL: Index – Use Explain!
Copyright Oracle Corporation 2011 48
49. http://dev.mysql.com/doc/refman/5.5/en/stored-routines.html
The CREATE ROUTINE , ALTER ROUTINE , EXECUTE privilege is needed for stored
routines.
mysql> delimiter //
mysql> CREATE PROCEDURE simpleproc (OUT param1 INT)
BEGIN
SELECT COUNT(*) INTO param1 FROM t;
END//
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> CALL simpleproc(@a);
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @a;
+------+
| @a |
+------+
| 3 |
+------+
1 row in set (0.00 sec)
MySQL: Stored Routines
Copyright Oracle Corporation 2011 49
57. http://dev.mysql.com/doc/refman/5.5/en/commit.html
To disable autocommit mode, use the following statement:
mysql> show variables like '%autocommit%';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| autocommit | ON |
+---------------+-------+
1 row in set (0.00 sec)
mysql> SET autocommit=0;
Query OK, 0 rows affected (0.00 sec)
mysql> show variables like '%autocommit%';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| autocommit | OFF |
+---------------+-------+
1 row in set (0.01 sec)
MySQL: Transactions
Copyright Oracle Corporation 2011 57
58. http://dev.mysql.com/doc/refman/5.5/en/commit.html
To disable autocommit mode for a single series of statements
use the START TRANSACTION statement:
START TRANSACTION;
SELECT @A:=SUM(salary) FROM table1 WHERE type=1;
UPDATE table2 SET summary=@A WHERE type=1;
COMMIT;
MySQL: Transactions
Copyright Oracle Corporation 2011 58
59. The best way to backup depends on the application
Possible solutions:
MySQL Enterprise Backup
Replication
mysqldump
…
Best solution is using all three, I will explain.
# mysqldump -p --all-databases --master-data=1 > /tmp/
example_dump.sql
Not an online solution. Can/will lock tables.
Copyright Oracle Corporation 2011 59
MySQL: Backups
60. MySQL Enterprise Backup
• Online Backup for InnoDB
• Full, Incremental, Partial Backups (scriptable interface)
• Compression
• Point in Time, Full, Partial Recovery options
• Metadata on status, progress, history
• Unlimited Database Size
• Cross-Platform
• Windows, Linux, Unix
• Certified with Oracle Secure Backup
MEB Backup
Files
MySQL
Database Files
mysqlbackup
Ensures quick, online backup and recovery of your MySQL apps.
Copyright Oracle Corporation 2011 60
61. MySQL Enterprise Backup
Usage:
ibbackup [--incremental lsn] [--sleep ms] [--suspend-at-end] [--compress [level]] [--include regexp] my.cnf backup-
my.cnf
or
ibbackup --apply-log [--use-memory mb] [--uncompress] backup-my.cnf
or
ibbackup --apply-log --incremental [--use-memory mb] [--uncompress] incremental-backup-my.cnf full-backup-my.cnf
The backup program does NOT make a backup of the .frm files of the tables,
and it does not make backups of MyISAM tables. To back up these items, either:
- Use the mysqlbackup program.
- Make backups of the .frm files with the Unix 'tar' or the Windows WinZip or an equivalent tool both BEFORE and
AFTER ibbackup finishes its work,and also store the MySQL binlog segment that is generated between the
moment
you copy the .frm files to a backup and the moment ibbackup finishes its work.
For extra safety, also use:
mysqldump -l -d yourdatabasename
to dump the table CREATE statements in a human-readable form before
ibbackup finishes its work.
Copyright Oracle Corporation 2011 61
MySQL: Backups
62. MySQL: Replication Overview
Native in MySQL
Used for Scalability and HA
Asynchronous as standard
Semi-Synchronous support
added in MySQL 5.5
Each slave adds minimal load on
master
Copyright Oracle Corporation 2011 62
64. MySQL: Replication Overview
Native in MySQL
Used for Scalability and HA
Asynchronous as standard
Semi-Synchronous support
added in MySQL 5.5
Each slave adds minimal load on
master
Copyright Oracle Corporation 2011 64
66. MySQL: Replicated Set up
Copyright Oracle Corporation 2011 66
http://dev.mysql.com/doc/refman/5.5/en/replication-howto.html
Master Bin logs enabled.
[mysqld]
log-bin=mysql-bin
server-id=1
Backup ( mysqldump or enterprise backup)
# mysqldump -p --all-databases --master-data=1 > /tmp/example_dump.sql
Slave my.cnf server id
[mysqld]
server-id=2
Replication user
mysql> CREATE USER 'repl'@'%.mydomain.com' IDENTIFIED BY
'slavepass';
mysql> GRANT REPLICATION SLAVE ON *.* TO
'repl'@'%.mydomain.com';
67. MySQL: Replicated Set up
Copyright Oracle Corporation 2011 67
http://dev.mysql.com/doc/refman/5.5/en/replication-howto.html
Import data into slave
shell> mysql < /tmp/example_dump.sql
Start the slave, using the --skip-slave-start
Set master relationship with information from your dump
CHANGE MASTER TO
-> MASTER_HOST='master_host_name',
-> MASTER_USER='replication_user_name',
-> MASTER_PASSWORD='replication_password',
-> MASTER_LOG_FILE='recorded_log_file_name',
-> MASTER_LOG_POS=recorded_log_position;
Start slave
68. Application
MySQL Server
SE2SE1
Storage Engines
Master
Binlog
Replication
MySQL Server
Application
Slave
Relay
Binlog
L R R A
SE2SE1
Storage Engines
Logging/
Replication
Semi-Sync
Replicator
Relay Log/
Applier
Semi-Sync
Receiver
Ack
Available as two separate loadable components
for the master and the slave
Copyright Oracle Corporation 2011 68
MySQL: 5.5 Semisynchronous Replication
Copyright Oracle Corporation 2011 68
69. MySQL: Migrating to Semisynchronous Replication
1. Install the plugin for the master and slave(s)
master> INSTALL PLUGIN rpl_semi_sync_master SONAME
'semisync_master.so';
slave> INSTALL PLUGIN rpl_semi_sync_slave SONAME 'semisync_slave.so';
2. Enable semisynchronous replication
master> SET GLOBAL rpl_semi_sync_master_enabled = on;
slave> SET GLOBAL rpl_semi_sync_slave_enabled = on;
slave> STOP SLAVE IO_THREAD; START SLAVE IO_THREAD;
3. Confirm that there is now 1 semisynchronous slave
master> SHOW STATUS LIKE 'Rpl_semi_sync_master_clients';
+------------------------------+-------+
| Variable_name | Value |
+------------------------------+-------+
| Rpl_semi_sync_master_clients | 1 |
+------------------------------+-------+
Copyright Oracle Corporation 2011 69
71. • Auto-detects, groups/maintains
Master/Slave topologies
• Consolidated, real time status/
synch check
• Notifications on Synch Issues
• Proactive vs reactive
Saves you time monitoring and
collecting replication status/synch
data from MySQL command line.
Copyright Oracle Corporation 2011 71
MySQL: Automated Replication Monitor
72. • Centralized monitoring of queries
without Slow Query Log, SHOW
PROCESSLIST;
• Enabled via MySQL Connectors
• Aggregated view of query
execution counts, time, and rows
• Visual “grab and go” correlation
with Monitor graphs
• Traces query executions back to
source code
Saves you time parsing atomic
executions from logs. Finds
problems you cannot find yourself.
MySQL: Query Analyzer
73. Example query exec
with variable
substitution
Trace query exec
back to source code
Full exec EXPLAIN
MySQL: Query Execution Drill Downs
74. • 24 X 7 Problem Resolution
Services
• Unlimited Support Incidents
• Knowledge Base
• Maintenance Releases, Bug
fixes, Patches, Updates
• MySQL Consultative Support
• Staffed by experienced,
seasoned MySQL Engineers
Oracle Premier Support for MySQL
75. http://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=402&p_nl=JMSQ
An Oracle certification recognizes and rewards your skills, dedication, and
motivation in the highly competitive technology industry.
– Oracle Certified Associate, MySQL 5.0/5.1/5.5
• Exam Number: 1Z0-870
– Oracle Certified Professional, MySQL 5.0 Developer
• Exam Number: 1Z0-871
• Exam Number: 1Z0-872
– Oracle Certified Professional, MySQL 5.0 Database Administrator
• Exam Number: 1Z0-873
• Exam Number: 1Z0-874
– Oracle Certified Expert, MySQL 5.1 Cluster Database
Administrator
• PRIOR CERTIFICATION :Oracle Certified Professional, MySQL 5 Database
Administrator
• Exam Number: 1Z0-875
Copyright Oracle Corporation 2011 75
MySQL: Certifications
76. mysql.com
• Download MySQL 5.5, MySQL Cluster 7.1 GA, GPL Products
• MySQL Products, Editions, Licensing Options
• TCO calculator
• Upcoming Events
• Customer use cases and success stories
dev.mysql.com
• Download MySQL 5.6 DMR and Labs “early access” features
• Developer Zone Articles, How to’s
• Community Resources
eDelivery.com
• Download and evaluate all MySQL products
Copyright Oracle Corporation 2011 76
MySQL: Additional Resources
77. Planet.mysql.com
• Blog feeds from the experts and the community
Books:
• MySQL by Paul DuBois
• MySQL Administrator's Bible
• High Performance MySQL: Optimization, Backups, Replication
• Effective MySQL book
forums.mysql.com
Community interaction
Workbench
– http://www.mysql.com/products/workbench/demo.html
Copyright Oracle Corporation 2011 77
MySQL: Additional Resources
78. Video by Oracle ACE and MySQL expert Ronald Bradford: Top 20 Database Design Tips Every
Architect Needs To Know : http://ow.ly/6FpzB
Need examples to apply immediately to improve database and application performances?
This MySQL book can help. http://ow.ly/6TYpu
Free download of chapter 1 "The Five Minute DBA" of Effective MySQL book by Ronald
Bradford at http://ow.ly/6TYSR
Free chapter describes analysis tools used to help optimize a MySQL statement including
EXPLAIN and SHOW CREATE TABLE http://ow.ly/6TZhk
Test Data used in this presentation is available at : http://dev.mysql.com/doc/
index-other.html
Copyright Oracle Corporation 2011 78
MySQL: Additional Resources
79. Facebook: http://www.facebook.com/groups/mysqlcolorado/
Meetup.com : http://www.meetup.com/Colorado-MySQL-Meetup-Group
Copyright Oracle Corporation 2011 79
MySQL: Colorado Meetup Group
Meet other Colorado users of MySQL for
conversation and fun! Come to a local
MySQL Meetup to talk about the world's
most popular open source database, get
great tips and share new ideas. All levels
of experience welcome!
80. Movies http://www.buzzom.com/wp-content/uploads/2011/06/atthemovies.jpg
Superman http://www.supermanfun.com/wp-content/uploads/2011/08/Superman-Clark-Kent-Old-Pics-217x300.jpg
clark kent http://1.bp.blogspot.com/-QO-jbX7c2Mk/TqkUu-Pad2I/AAAAAAAAKV8/DUTB60Fe1QI/s1600/clark%2Bkent.jpg
Kent a& superman http://www.toptenz.net/wp-content/uploads/2009/06/clark-kent-superman.jpg
Supermanlogo http://www.superman-picture.com/images/superad.gif
Books http://publishingperspectives.com/wp-content/uploads/2011/05/stack-of-books.jpg
Pull back curtain on Oz http://911u.org/CoDR/images/TWOO1.jpg
Organized movies http://www.whirlwind.nu/images/journal_101119_movies_and_books_rainbow.jpg
Show tables http://storefixtures.files.wordpress.com/2008/12/tables.jpg?w=200&h=192
Datatypes http://mysql.lamphost.net/tech-resources/articles/mysql-cluster-50.gif
the riddler http://3.bp.blogspot.com/_57XeKo2AVGk/TNfvV8CmamI/AAAAAAAADds/zG9SGr3Dv9s/s1600/The_Riddler_3%5B1%5D.png
World http://www.scientificamerican.com/media/inline/3E0F9160-E7F2-99DF-358998AA3C1A910F_1.jpg
Pile of VHS http://punksonfilm.com/wordpress/wp-content/uploads/2010/07/vhs-pile.jpg
Organized movies http://1.bp.blogspot.com/_Yz5dzGyEAnQ/S0EHwl-_-ZI/AAAAAAAAAA8/bbSuUFf8Zpw/s320/IMG_0644.JPG
Index Cards' "DNA" By ayalan http://prajwal-tuladhar.net.np/2009/09/23/474/things-you-should-know-about-mysql-index/
Safe http://www.thomasgregory.com/Portals/40231/images//Vault.JPG
Copyright Oracle Corporation 2011 80
Credits