SlideShare a Scribd company logo
1 of 81
Download to read offline
<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
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
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
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
$ 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
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
http://dev.mysql.com/doc/refman/5.6/en/grant.html
mysql> CREATE USER 'admin'@'localhost' IDENTIFIED BY 'admin_pass';
GRANT ALL ON *.* TO 'admin'@'localhost';
mysql> flush privileges ;
MySQL: Super User Accounts
Copyright Oracle Corporation 2011 7
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
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
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
http://www.mysql.com/products/workbench/
MySQL: WB User Accounts
Copyright Oracle Corporation 2011 11
MySQL Logs for the DBAs
http://dev.mysql.com/doc/refman/5.5/en/server-logs.html
http://dev.mysql.com/doc/refman/5.5/en/slave-logs.html
Error Log
–  log-error
Binary Log
–  Log-bin custom set via my.cnf
Relay Log
–  Log-bin custom set via my.cnf
Slow Query Log
–  Log-slow-queries
–  Slow-query-time
–  log-queries-not-using-indexes
General Log
–  Log
MySQL Logs for the DBAs
SHOW VARIABLES like '%log%';
+-----------------------------------------+-------------------------------------+
| Variable_name | Value |
+-----------------------------------------+-------------------------------------+
| back_log | 50 |
| binlog_cache_size | 32768 |
| binlog_checksum | NONE |
| binlog_direct_non_transactional_updates | OFF |
| binlog_format | MIXED |
| binlog_row_image | FULL |
| binlog_rows_query_log_events | OFF |
| binlog_stmt_cache_size | 32768 |
| expire_logs_days | 0 |
| general_log | OFF |
| general_log_file | /var/lib/mysql/kdlarson-pc.log |
…...
MySQL Logs for the DBAs
… |
| max_binlog_cache_size | 18446744073709547520 |
| max_binlog_size | 1073741824 |
| max_binlog_stmt_cache_size | 18446744073709547520 |
| max_relay_log_size | 0 |
| relay_log | |
| relay_log_basename | |
| relay_log_index | |
| relay_log_info_file | relay-log.info |
| relay_log_info_repository | FILE |
| relay_log_purge | ON |
| relay_log_recovery | OFF |
| relay_log_space_limit | 0 |
| slow_query_log | OFF |
| slow_query_log_file | /var/lib/mysql/kdlarson-pc-slow.log |
| sql_log_bin | ON |
| sql_log_off | OFF |
| sync_binlog | 0 |
| sync_relay_log | 0 |
| sync_relay_log_info | 0 |
+-----------------------------------------+-------------------------------------+
MySQL Logs for the DBAs in WB
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
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
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
http://www.mysql.com/products/workbench/
MySQL: WB Databases
Copyright Oracle Corporation 2011 19
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
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
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
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
http://www.mysql.com/products/workbench/
MySQL: WB Table Space
Copyright Oracle Corporation 2011 24
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
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
http://dev.mysql.com/doc/refman/5.5/en/data-types.html
DATE TYPES
DATE YYYY-MM-DD.
DATETIME YYYY-MM-DD HH:MM:SS.
TIMESTAMP YYYYMMDDHHMMSS.
TIME HH:MM:SS.
Create Table: CREATE TABLE `example_table` (
`example_table_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(9) unsigned DEFAULT NULL,
`date_recorded` datetime DEFAULT NULL,
PRIMARY KEY (`example_table_id`),
UNIQUE KEY `user_id` (`user_id`),
KEY `date_recorded` (`date_recorded`)
) ENGINE=InnoDB
MySQL: Datatypes
Copyright Oracle Corporation 2011 27
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
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
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
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
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
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
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
MySQL
Data Dictionary = INFORMATION_SCHEMA
+--------------------+--------------------+--------------+------------+------------+
| TABLE_SCHEMA | ENGINE | count_tables | size | index_size |
+--------------------+--------------------+--------------+------------+------------+ |
| performance_schema | PERFORMANCE_SCHEMA | 48 | 0 | 0 |
| telco | InnoDB | 1 | 143425536 | 52592640 |
| test | InnoDB | 1 | 16384 | 0 |
| test | MyISAM | 2 | 2048 | 2048 |
| wb | MyISAM | 10 | 320223 | 47104 |
| world | InnoDB | 3 | 802816 | 196608 |
+--------------------+--------------------+--------------+------------+------------+
http://code.openark.org/blog/mysql/useful-database-analysis-queries-with-
information_schema
MySQL Performance Schema
use performance_schema;
mysql> SELECT THREAD_ID, NUMBER_OF_BYTES
-> FROM events_waits_history
-> WHERE EVENT_NAME LIKE 'wait/io/file/%'
-> AND NUMBER_OF_BYTES IS NOT NULL;
+-----------+-----------------+
| THREAD_ID | NUMBER_OF_BYTES |
+-----------+-----------------+
| 11 | 66 |
| 11 | 47 |
| 11 | 139 |
| 5 | 24 |
| 5 | 834 |
+-----------+-----------------+
MySQL Performance
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
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
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
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
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
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
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)
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
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
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
MySQL: Index – Use Explain!
Copyright Oracle Corporation 2011 48
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
MySQL: Stored Routines
Copyright Oracle Corporation 2011 50
http://dev.mysql.com/doc/refman/5.5/en/create-trigger.html
CREATE TABLE test1(a1 INT);
CREATE TABLE test2(a2 INT);
CREATE TABLE test3(a3 INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
CREATE TABLE test4(
a4 INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
b4 INT DEFAULT 0
);
delimiter |
CREATE TRIGGER testref BEFORE INSERT ON test1
FOR EACH ROW BEGIN
INSERT INTO test2 SET a2 = NEW.a1;
DELETE FROM test3 WHERE a3 = NEW.a1;
UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;
END; |
delimiter ;
MySQL: Triggers
Copyright Oracle Corporation 2011 51
mysql> INSERT INTO test3 (a3)
VALUES (NULL), (NULL), (NULL), (NULL), (NULL), (NULL), (NULL), (NULL), (NULL), (NULL);
Query OK, 10 rows affected (0.04 sec)
Records: 10 Duplicates: 0 Warnings: 0
mysql> INSERT INTO test4 (a4) VALUES (0), (0), (0), (0), (0), (0), (0), (0), (0), (0);
Query OK, 10 rows affected (0.01 sec)
Records: 10 Duplicates: 0 Warnings: 0
INSERT INTO test1 VALUES (1), (3), (1), (7), (1), (8), (4), (4);
Query OK, 8 rows affected (0.01 sec)
Records: 8 Duplicates: 0 Warnings: 0
## Warnings: 1
Statement is unsafe because it invokes a trigger or a stored function that inserts into an
AUTO_INCREMENT column. Inserted values cannot be logged correctly.
set BINLOG_FORMAT = MIXED;
MySQL: Triggers
Copyright Oracle Corporation 2011 52
http://dev.mysql.com/doc/refman/5.5/en/create-
trigger.html
mysql> SELECT * FROM test1;
+------+
| a1 |
+------+
| 1 |
| 3 |
| 1 |
| 7 |
| 1 |
| 8 |
| 4 |
| 4 |
+------+
8 rows in set (0.00 sec)
MySQL: Triggers
Copyright Oracle Corporation 2011 53
mysql> SELECT * FROM test3;
+----+
| a3 |
+----+
| 2 |
| 5 |
| 6 |
| 9 |
| 10 |
+----+
5 rows in set (0.00 sec)
mysql> SELECT * FROM test4;
+----+------+
| a4 | b4 |
+----+------+
| 1 | 3 |
| 2 | 0 |
| 3 | 1 |
| 4 | 2 |
| 5 | 0 |
| 6 | 0 |
| 7 | 1 |
| 8 | 1 |
| 9 | 0 |
| 10 | 0 |
+----+------+
10 rows in set (0.00 sec)
mysql> SELECT * FROM test2;
+------+
| a2 |
+------+
| 1 |
| 3 |
| 1 |
| 7 |
| 1 |
| 8 |
| 4 |
| 4 |
+------+
8 rows in set (0.00 s
MySQL: Triggers
Copyright Oracle Corporation 2011 54
> CREATE VIEW `world`.`city_view` AS
SELECT C.Name as cityname , T.Name as countryname
FROM world.City C
INNER JOIN world.Country T ON C.CountryCode = T.Code;
Query OK, 0 rows affected (0.16 sec)
SELECT cityname , countryname from city_view where countryname = "Zimbabwe";
+--------------+-------------+
| cityname | countryname |
+--------------+-------------+
| Harare | Zimbabwe |
| Bulawayo | Zimbabwe |
| Chitungwiza | Zimbabwe |
| Mount Darwin | Zimbabwe |
| Mutare | Zimbabwe |
| Gweru | Zimbabwe |
+--------------+-------------+
6 rows in set (0.13 sec)
MySQL: Views
Copyright Oracle Corporation 2011 55
MySQL: Views
Copyright Oracle Corporation 2011 56
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
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
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
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
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
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
MySQL: Replication Topologies
Multi-Master Ring
Copyright Oracle Corporation 2011 63
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
MySQL: Replicated?
Copyright Oracle Corporation 2011 65
Is your database replicated?
mysql> SHOW MASTER STATUS;
+---------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+---------------+----------+--------------+------------------+
| mysql-bin.003 | 73 | test | manual,mysql |
+---------------+----------+--------------+------------------+
mysql> SHOW SLAVE HOSTS;
+------------+-----------+------+-----------+
| Server_id | Host | Port | Master_id |
+------------+-----------+------+-----------+
| 192168010 | iconnect2 | 3306 | 192168011 |
| 1921680101 | athena | 3306 | 192168011 |
+------------+-----------+------+-----------+
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';
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
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
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
Copyright Oracle Corporation 2011 70
MySQL: Enterprise Monitor 2.3
•  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
• 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
Example query exec
with variable
substitution
Trace query exec
back to source code
Full exec EXPLAIN
MySQL: Query Execution Drill Downs
• 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
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
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
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
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
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!
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
<Insert Picture Here>
Thanks for attending!
keith.larson@oracle.com

More Related Content

What's hot

MySQL Performance Best Practices
MySQL Performance Best PracticesMySQL Performance Best Practices
MySQL Performance Best PracticesOlivier DASINI
 
MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...
MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...
MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...Dave Stokes
 
MySQL Shell - The Best MySQL DBA Tool
MySQL Shell - The Best MySQL DBA ToolMySQL Shell - The Best MySQL DBA Tool
MySQL Shell - The Best MySQL DBA ToolMiguel Araújo
 
MySQL 5.7 in a Nutshell
MySQL 5.7 in a NutshellMySQL 5.7 in a Nutshell
MySQL 5.7 in a NutshellEmily Ikuta
 
NoSQL and MySQL: News about JSON
NoSQL and MySQL: News about JSONNoSQL and MySQL: News about JSON
NoSQL and MySQL: News about JSONMario Beck
 
MySQL 5.7 - What's new and How to upgrade
MySQL 5.7 - What's new and How to upgradeMySQL 5.7 - What's new and How to upgrade
MySQL 5.7 - What's new and How to upgradeAbel Flórez
 
My sql 5.7-upcoming-changes-v2
My sql 5.7-upcoming-changes-v2My sql 5.7-upcoming-changes-v2
My sql 5.7-upcoming-changes-v2Morgan Tocker
 
MySQL High Availability Solutions - Avoid loss of service by reducing the r...
MySQL High Availability Solutions  -  Avoid loss of service by reducing the r...MySQL High Availability Solutions  -  Avoid loss of service by reducing the r...
MySQL High Availability Solutions - Avoid loss of service by reducing the r...Olivier DASINI
 
MySQL 5.7: What's New, Nov. 2015
MySQL 5.7: What's New, Nov. 2015MySQL 5.7: What's New, Nov. 2015
MySQL 5.7: What's New, Nov. 2015Mario Beck
 
MySQL for Software-as-a-Service (SaaS)
MySQL for Software-as-a-Service (SaaS)MySQL for Software-as-a-Service (SaaS)
MySQL for Software-as-a-Service (SaaS)Mario Beck
 
MySQL 5.7: Focus on InnoDB
MySQL 5.7: Focus on InnoDBMySQL 5.7: Focus on InnoDB
MySQL 5.7: Focus on InnoDBMario Beck
 
MySQL High Availability -- InnoDB Clusters
MySQL High Availability -- InnoDB ClustersMySQL High Availability -- InnoDB Clusters
MySQL High Availability -- InnoDB ClustersMatt Lord
 
New awesome features in MySQL 5.7
New awesome features in MySQL 5.7New awesome features in MySQL 5.7
New awesome features in MySQL 5.7Zhaoyang Wang
 
MySQL Group Replication - an Overview
MySQL Group Replication - an OverviewMySQL Group Replication - an Overview
MySQL Group Replication - an OverviewMatt Lord
 
Oracle Unified Directory. Lessons learnt. Is it ready for a move from OID? (O...
Oracle Unified Directory. Lessons learnt. Is it ready for a move from OID? (O...Oracle Unified Directory. Lessons learnt. Is it ready for a move from OID? (O...
Oracle Unified Directory. Lessons learnt. Is it ready for a move from OID? (O...Andrejs Prokopjevs
 
Exploring mysql cluster 7.4
Exploring mysql cluster 7.4Exploring mysql cluster 7.4
Exploring mysql cluster 7.4Ivan Ma
 

What's hot (20)

MySQL Performance Best Practices
MySQL Performance Best PracticesMySQL Performance Best Practices
MySQL Performance Best Practices
 
MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...
MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...
MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...
 
MySQL Shell - The Best MySQL DBA Tool
MySQL Shell - The Best MySQL DBA ToolMySQL Shell - The Best MySQL DBA Tool
MySQL Shell - The Best MySQL DBA Tool
 
MySQL 5.7 in a Nutshell
MySQL 5.7 in a NutshellMySQL 5.7 in a Nutshell
MySQL 5.7 in a Nutshell
 
NoSQL and MySQL: News about JSON
NoSQL and MySQL: News about JSONNoSQL and MySQL: News about JSON
NoSQL and MySQL: News about JSON
 
MySQL 5.7 + JSON
MySQL 5.7 + JSONMySQL 5.7 + JSON
MySQL 5.7 + JSON
 
MySQL 5.7 - What's new and How to upgrade
MySQL 5.7 - What's new and How to upgradeMySQL 5.7 - What's new and How to upgrade
MySQL 5.7 - What's new and How to upgrade
 
My sql 5.7-upcoming-changes-v2
My sql 5.7-upcoming-changes-v2My sql 5.7-upcoming-changes-v2
My sql 5.7-upcoming-changes-v2
 
MySQL High Availability Solutions - Avoid loss of service by reducing the r...
MySQL High Availability Solutions  -  Avoid loss of service by reducing the r...MySQL High Availability Solutions  -  Avoid loss of service by reducing the r...
MySQL High Availability Solutions - Avoid loss of service by reducing the r...
 
MySQL 5.7: What's New, Nov. 2015
MySQL 5.7: What's New, Nov. 2015MySQL 5.7: What's New, Nov. 2015
MySQL 5.7: What's New, Nov. 2015
 
MySQL for Software-as-a-Service (SaaS)
MySQL for Software-as-a-Service (SaaS)MySQL for Software-as-a-Service (SaaS)
MySQL for Software-as-a-Service (SaaS)
 
MySQL 5.7: Focus on InnoDB
MySQL 5.7: Focus on InnoDBMySQL 5.7: Focus on InnoDB
MySQL 5.7: Focus on InnoDB
 
MySQL High Availability -- InnoDB Clusters
MySQL High Availability -- InnoDB ClustersMySQL High Availability -- InnoDB Clusters
MySQL High Availability -- InnoDB Clusters
 
New awesome features in MySQL 5.7
New awesome features in MySQL 5.7New awesome features in MySQL 5.7
New awesome features in MySQL 5.7
 
MySQL JSON Functions
MySQL JSON FunctionsMySQL JSON Functions
MySQL JSON Functions
 
MySQL Group Replication - an Overview
MySQL Group Replication - an OverviewMySQL Group Replication - an Overview
MySQL Group Replication - an Overview
 
MySQL Monitoring 101
MySQL Monitoring 101MySQL Monitoring 101
MySQL Monitoring 101
 
MySQL Security
MySQL SecurityMySQL Security
MySQL Security
 
Oracle Unified Directory. Lessons learnt. Is it ready for a move from OID? (O...
Oracle Unified Directory. Lessons learnt. Is it ready for a move from OID? (O...Oracle Unified Directory. Lessons learnt. Is it ready for a move from OID? (O...
Oracle Unified Directory. Lessons learnt. Is it ready for a move from OID? (O...
 
Exploring mysql cluster 7.4
Exploring mysql cluster 7.4Exploring mysql cluster 7.4
Exploring mysql cluster 7.4
 

Similar to Mysql nowwhat

The MySQL SYS Schema
The MySQL SYS SchemaThe MySQL SYS Schema
The MySQL SYS SchemaMark Leith
 
Performance schema and sys schema
Performance schema and sys schemaPerformance schema and sys schema
Performance schema and sys schemaMark Leith
 
Basic MySQL Troubleshooting for Oracle DBAs
Basic MySQL Troubleshooting for Oracle DBAsBasic MySQL Troubleshooting for Oracle DBAs
Basic MySQL Troubleshooting for Oracle DBAsSveta Smirnova
 
MySQL sys schema deep dive
MySQL sys schema deep diveMySQL sys schema deep dive
MySQL sys schema deep diveMark Leith
 
DB Floripa - ProxySQL para MySQL
DB Floripa - ProxySQL para MySQLDB Floripa - ProxySQL para MySQL
DB Floripa - ProxySQL para MySQLMarcelo Altmann
 
MySQL Performance Schema in 20 Minutes
 MySQL Performance Schema in 20 Minutes MySQL Performance Schema in 20 Minutes
MySQL Performance Schema in 20 MinutesSveta Smirnova
 
제3회난공불락 오픈소스 인프라세미나 - MySQL
제3회난공불락 오픈소스 인프라세미나 - MySQL제3회난공불락 오픈소스 인프라세미나 - MySQL
제3회난공불락 오픈소스 인프라세미나 - MySQLTommy Lee
 
MySQL server security
MySQL server securityMySQL server security
MySQL server securityDamien Seguy
 
Memcached Functions For My Sql Seemless Caching In My Sql
Memcached Functions For My Sql Seemless Caching In My SqlMemcached Functions For My Sql Seemless Caching In My Sql
Memcached Functions For My Sql Seemless Caching In My SqlMySQLConference
 
Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012Roland Bouman
 
Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012Roland Bouman
 
Percona Live 2019 - MySQL Security
Percona Live 2019 - MySQL SecurityPercona Live 2019 - MySQL Security
Percona Live 2019 - MySQL SecurityVinicius M Grippa
 
Percona Live 2012PPT:mysql-security-privileges-and-user-management
Percona Live 2012PPT:mysql-security-privileges-and-user-managementPercona Live 2012PPT:mysql-security-privileges-and-user-management
Percona Live 2012PPT:mysql-security-privileges-and-user-managementmysqlops
 
20151010 my sq-landjavav2a
20151010 my sq-landjavav2a20151010 my sq-landjavav2a
20151010 my sq-landjavav2aIvan Ma
 

Similar to Mysql nowwhat (20)

The MySQL SYS Schema
The MySQL SYS SchemaThe MySQL SYS Schema
The MySQL SYS Schema
 
Curso de MySQL 5.7
Curso de MySQL 5.7Curso de MySQL 5.7
Curso de MySQL 5.7
 
Performance schema and sys schema
Performance schema and sys schemaPerformance schema and sys schema
Performance schema and sys schema
 
Basic MySQL Troubleshooting for Oracle DBAs
Basic MySQL Troubleshooting for Oracle DBAsBasic MySQL Troubleshooting for Oracle DBAs
Basic MySQL Troubleshooting for Oracle DBAs
 
MySQL sys schema deep dive
MySQL sys schema deep diveMySQL sys schema deep dive
MySQL sys schema deep dive
 
My sql 5.6&MySQL Cluster 7.3
My sql 5.6&MySQL Cluster 7.3My sql 5.6&MySQL Cluster 7.3
My sql 5.6&MySQL Cluster 7.3
 
Mysql tracing
Mysql tracingMysql tracing
Mysql tracing
 
Mysql tracing
Mysql tracingMysql tracing
Mysql tracing
 
DB Floripa - ProxySQL para MySQL
DB Floripa - ProxySQL para MySQLDB Floripa - ProxySQL para MySQL
DB Floripa - ProxySQL para MySQL
 
MySQL Performance Schema in 20 Minutes
 MySQL Performance Schema in 20 Minutes MySQL Performance Schema in 20 Minutes
MySQL Performance Schema in 20 Minutes
 
MySQL Quick Dive
MySQL Quick DiveMySQL Quick Dive
MySQL Quick Dive
 
제3회난공불락 오픈소스 인프라세미나 - MySQL
제3회난공불락 오픈소스 인프라세미나 - MySQL제3회난공불락 오픈소스 인프라세미나 - MySQL
제3회난공불락 오픈소스 인프라세미나 - MySQL
 
MySQL server security
MySQL server securityMySQL server security
MySQL server security
 
Memcached Functions For My Sql Seemless Caching In My Sql
Memcached Functions For My Sql Seemless Caching In My SqlMemcached Functions For My Sql Seemless Caching In My Sql
Memcached Functions For My Sql Seemless Caching In My Sql
 
Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012
 
Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012
 
SQL Server 2014 Backup to Azure - SQL Saturday CR 2015
SQL Server 2014 Backup to Azure - SQL Saturday CR 2015SQL Server 2014 Backup to Azure - SQL Saturday CR 2015
SQL Server 2014 Backup to Azure - SQL Saturday CR 2015
 
Percona Live 2019 - MySQL Security
Percona Live 2019 - MySQL SecurityPercona Live 2019 - MySQL Security
Percona Live 2019 - MySQL Security
 
Percona Live 2012PPT:mysql-security-privileges-and-user-management
Percona Live 2012PPT:mysql-security-privileges-and-user-managementPercona Live 2012PPT:mysql-security-privileges-and-user-management
Percona Live 2012PPT:mysql-security-privileges-and-user-management
 
20151010 my sq-landjavav2a
20151010 my sq-landjavav2a20151010 my sq-landjavav2a
20151010 my sq-landjavav2a
 

Recently uploaded

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 

Recently uploaded (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 

Mysql nowwhat

  • 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
  • 7. http://dev.mysql.com/doc/refman/5.6/en/grant.html mysql> CREATE USER 'admin'@'localhost' IDENTIFIED BY 'admin_pass'; GRANT ALL ON *.* TO 'admin'@'localhost'; mysql> flush privileges ; MySQL: Super User Accounts Copyright Oracle Corporation 2011 7
  • 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
  • 11. http://www.mysql.com/products/workbench/ MySQL: WB User Accounts Copyright Oracle Corporation 2011 11
  • 12. MySQL Logs for the DBAs http://dev.mysql.com/doc/refman/5.5/en/server-logs.html http://dev.mysql.com/doc/refman/5.5/en/slave-logs.html Error Log –  log-error Binary Log –  Log-bin custom set via my.cnf Relay Log –  Log-bin custom set via my.cnf Slow Query Log –  Log-slow-queries –  Slow-query-time –  log-queries-not-using-indexes General Log –  Log
  • 13. MySQL Logs for the DBAs SHOW VARIABLES like '%log%'; +-----------------------------------------+-------------------------------------+ | Variable_name | Value | +-----------------------------------------+-------------------------------------+ | back_log | 50 | | binlog_cache_size | 32768 | | binlog_checksum | NONE | | binlog_direct_non_transactional_updates | OFF | | binlog_format | MIXED | | binlog_row_image | FULL | | binlog_rows_query_log_events | OFF | | binlog_stmt_cache_size | 32768 | | expire_logs_days | 0 | | general_log | OFF | | general_log_file | /var/lib/mysql/kdlarson-pc.log | …...
  • 14. MySQL Logs for the DBAs … | | max_binlog_cache_size | 18446744073709547520 | | max_binlog_size | 1073741824 | | max_binlog_stmt_cache_size | 18446744073709547520 | | max_relay_log_size | 0 | | relay_log | | | relay_log_basename | | | relay_log_index | | | relay_log_info_file | relay-log.info | | relay_log_info_repository | FILE | | relay_log_purge | ON | | relay_log_recovery | OFF | | relay_log_space_limit | 0 | | slow_query_log | OFF | | slow_query_log_file | /var/lib/mysql/kdlarson-pc-slow.log | | sql_log_bin | ON | | sql_log_off | OFF | | sync_binlog | 0 | | sync_relay_log | 0 | | sync_relay_log_info | 0 | +-----------------------------------------+-------------------------------------+
  • 15. MySQL Logs for the DBAs in WB
  • 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
  • 24. http://www.mysql.com/products/workbench/ MySQL: WB Table Space Copyright Oracle Corporation 2011 24
  • 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
  • 27. http://dev.mysql.com/doc/refman/5.5/en/data-types.html DATE TYPES DATE YYYY-MM-DD. DATETIME YYYY-MM-DD HH:MM:SS. TIMESTAMP YYYYMMDDHHMMSS. TIME HH:MM:SS. Create Table: CREATE TABLE `example_table` ( `example_table_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(9) unsigned DEFAULT NULL, `date_recorded` datetime DEFAULT NULL, PRIMARY KEY (`example_table_id`), UNIQUE KEY `user_id` (`user_id`), KEY `date_recorded` (`date_recorded`) ) ENGINE=InnoDB MySQL: Datatypes Copyright Oracle Corporation 2011 27
  • 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
  • 35. MySQL Data Dictionary = INFORMATION_SCHEMA +--------------------+--------------------+--------------+------------+------------+ | TABLE_SCHEMA | ENGINE | count_tables | size | index_size | +--------------------+--------------------+--------------+------------+------------+ | | performance_schema | PERFORMANCE_SCHEMA | 48 | 0 | 0 | | telco | InnoDB | 1 | 143425536 | 52592640 | | test | InnoDB | 1 | 16384 | 0 | | test | MyISAM | 2 | 2048 | 2048 | | wb | MyISAM | 10 | 320223 | 47104 | | world | InnoDB | 3 | 802816 | 196608 | +--------------------+--------------------+--------------+------------+------------+ http://code.openark.org/blog/mysql/useful-database-analysis-queries-with- information_schema
  • 36. MySQL Performance Schema use performance_schema; mysql> SELECT THREAD_ID, NUMBER_OF_BYTES -> FROM events_waits_history -> WHERE EVENT_NAME LIKE 'wait/io/file/%' -> AND NUMBER_OF_BYTES IS NOT NULL; +-----------+-----------------+ | THREAD_ID | NUMBER_OF_BYTES | +-----------+-----------------+ | 11 | 66 | | 11 | 47 | | 11 | 139 | | 5 | 24 | | 5 | 834 | +-----------+-----------------+
  • 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
  • 50. MySQL: Stored Routines Copyright Oracle Corporation 2011 50
  • 51. http://dev.mysql.com/doc/refman/5.5/en/create-trigger.html CREATE TABLE test1(a1 INT); CREATE TABLE test2(a2 INT); CREATE TABLE test3(a3 INT NOT NULL AUTO_INCREMENT PRIMARY KEY); CREATE TABLE test4( a4 INT NOT NULL AUTO_INCREMENT PRIMARY KEY, b4 INT DEFAULT 0 ); delimiter | CREATE TRIGGER testref BEFORE INSERT ON test1 FOR EACH ROW BEGIN INSERT INTO test2 SET a2 = NEW.a1; DELETE FROM test3 WHERE a3 = NEW.a1; UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1; END; | delimiter ; MySQL: Triggers Copyright Oracle Corporation 2011 51
  • 52. mysql> INSERT INTO test3 (a3) VALUES (NULL), (NULL), (NULL), (NULL), (NULL), (NULL), (NULL), (NULL), (NULL), (NULL); Query OK, 10 rows affected (0.04 sec) Records: 10 Duplicates: 0 Warnings: 0 mysql> INSERT INTO test4 (a4) VALUES (0), (0), (0), (0), (0), (0), (0), (0), (0), (0); Query OK, 10 rows affected (0.01 sec) Records: 10 Duplicates: 0 Warnings: 0 INSERT INTO test1 VALUES (1), (3), (1), (7), (1), (8), (4), (4); Query OK, 8 rows affected (0.01 sec) Records: 8 Duplicates: 0 Warnings: 0 ## Warnings: 1 Statement is unsafe because it invokes a trigger or a stored function that inserts into an AUTO_INCREMENT column. Inserted values cannot be logged correctly. set BINLOG_FORMAT = MIXED; MySQL: Triggers Copyright Oracle Corporation 2011 52
  • 53. http://dev.mysql.com/doc/refman/5.5/en/create- trigger.html mysql> SELECT * FROM test1; +------+ | a1 | +------+ | 1 | | 3 | | 1 | | 7 | | 1 | | 8 | | 4 | | 4 | +------+ 8 rows in set (0.00 sec) MySQL: Triggers Copyright Oracle Corporation 2011 53 mysql> SELECT * FROM test3; +----+ | a3 | +----+ | 2 | | 5 | | 6 | | 9 | | 10 | +----+ 5 rows in set (0.00 sec) mysql> SELECT * FROM test4; +----+------+ | a4 | b4 | +----+------+ | 1 | 3 | | 2 | 0 | | 3 | 1 | | 4 | 2 | | 5 | 0 | | 6 | 0 | | 7 | 1 | | 8 | 1 | | 9 | 0 | | 10 | 0 | +----+------+ 10 rows in set (0.00 sec) mysql> SELECT * FROM test2; +------+ | a2 | +------+ | 1 | | 3 | | 1 | | 7 | | 1 | | 8 | | 4 | | 4 | +------+ 8 rows in set (0.00 s
  • 54. MySQL: Triggers Copyright Oracle Corporation 2011 54
  • 55. > CREATE VIEW `world`.`city_view` AS SELECT C.Name as cityname , T.Name as countryname FROM world.City C INNER JOIN world.Country T ON C.CountryCode = T.Code; Query OK, 0 rows affected (0.16 sec) SELECT cityname , countryname from city_view where countryname = "Zimbabwe"; +--------------+-------------+ | cityname | countryname | +--------------+-------------+ | Harare | Zimbabwe | | Bulawayo | Zimbabwe | | Chitungwiza | Zimbabwe | | Mount Darwin | Zimbabwe | | Mutare | Zimbabwe | | Gweru | Zimbabwe | +--------------+-------------+ 6 rows in set (0.13 sec) MySQL: Views Copyright Oracle Corporation 2011 55
  • 56. MySQL: Views Copyright Oracle Corporation 2011 56
  • 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
  • 63. MySQL: Replication Topologies Multi-Master Ring Copyright Oracle Corporation 2011 63
  • 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
  • 65. MySQL: Replicated? Copyright Oracle Corporation 2011 65 Is your database replicated? mysql> SHOW MASTER STATUS; +---------------+----------+--------------+------------------+ | File | Position | Binlog_Do_DB | Binlog_Ignore_DB | +---------------+----------+--------------+------------------+ | mysql-bin.003 | 73 | test | manual,mysql | +---------------+----------+--------------+------------------+ mysql> SHOW SLAVE HOSTS; +------------+-----------+------+-----------+ | Server_id | Host | Port | Master_id | +------------+-----------+------+-----------+ | 192168010 | iconnect2 | 3306 | 192168011 | | 1921680101 | athena | 3306 | 192168011 | +------------+-----------+------+-----------+
  • 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
  • 70. Copyright Oracle Corporation 2011 70 MySQL: Enterprise Monitor 2.3
  • 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
  • 81. <Insert Picture Here> Thanks for attending! keith.larson@oracle.com