Académique Documents
Professionnel Documents
Culture Documents
of Contents
Introduction 1.1
MySQL Architecture 1.2
Client\/Server Overview 1.2.1
Communication Protocols 1.2.2
Connecting to MySQL Server 1.2.3
The SQL Parser and Storage Engines 1.2.4
How MySQL uses Disk Space 1.2.5
How MySQL Uses Memory 1.2.6
Monitoring MySQL Memory Usage 1.2.7
System Administration 1.3
Types of MySQL Distributions 1.3.1
Starting and Stopping MySQL Server on Unix 1.3.2
Runtime Configuration 1.3.3
Loading Timezone Tables 1.3.4
Setting Default SQL Mode 1.3.5
Upgrading MySQL Server 1.3.6
Client Programs for DBA Work 1.4
MySQL WorkBench 1.4.1
Command Line Clients 1.4.2
mysqladmin - Client for Administering a MySQL Server 1.4.3
mysqlcheck - A Table Maintenance Program 1.4.4
mysqldump - A Database Backup Program 1.4.5
mysqlimport - A Data Import Program 1.4.6
mysqlshow - Display Database, Table, and Column Information 1.4.7
mysqlslap - Load Emulation Client 1.4.8
MySQL Workbench 1.5
User Management 1.6
1
Data Types 1.7
Character Set Support 1.7.1
Transactions and Locking 1.8
Locking Concepts 1.8.1
Advisory Locks 1.8.2
Obtaining Metadata 1.9
Storage Engines 1.10
MySQL Storage Engines Overview 1.10.1
MyISAM Storage Engine 1.10.2
InnoDB Storage Engine 1.10.3
InnoDB Memcached Storage Plugin 1.10.4
Memory Engine 1.10.5
Federated Engine 1.10.6
Partitioning 1.11
Why Partition 1.11.1
Types of Partitioning 1.11.2
Creating Partitioned Tables 1.11.3
Obtaining Partition Metadata 1.11.4
Security 1.12
Table Maintenance 1.13
Exporting and Importing Data 1.14
Programming inside MySQL 1.15
MySQL Backup and Recovery 1.16
Replication 1.17
Setting Master Server 1.17.1
Setting Up Replication on the Salve Database 1.17.2
Introduction to Performance Tuning 1.18
Index Types 1.18.1
Clustered Index 1.18.2
Secondary Index 1.18.3
2
Basic Indexing 1.18.4
Order of Indexes 1.18.5
OR Conditional with Indexes 1.18.6
3
Introduction
4
MySQL Architecture
MySQL Architecture
1. The client\/server architectural design of MySQL
3. The relationship between the server's storage engines and its SQL parser
and optimizer
5
Client\/Server Overview
MySQL Server
The mysqld program is the MySQL server database program that manages the
database and tables.
Client Programs
Client programs communicate with the server by sending request over a network
connection. Examples of client programs are mysql and mysqladmin
6
Communication Protocols
Communication Protocols
MySQL supports different types of connections from the client to the server.
Disabling TCP\/IP
TCP\/IP can be disabled by using the start-up option passed to the mysqld
command line --skip-networking .
[mysqld]
skip-networking
Named Pipes
Names pipes are disabled by default and can be enabled by using the - -enable-
named-pipe option
Shared Memory
Shared memory is disabled by default and can be enabled by using the startup
option --shared-memory
7
Connecting to MySQL Server
$ mysql
If you use -p or --password option but do not specify the password value,
the client program prompts to enter the passowrd. This is the recommend option.
The password is not displayed as you ente it.
8
Connecting to MySQL Server
is equivalent to
9
Connecting to MySQL Server
10
The SQL Parser and Storage Engines
The MySQL server executes SQL statements independent of the storage engines.
The server executes each statement using a two-tier model :
The upper tier includes the SQL parser and optimizer. The tier does not
interact with the tables directly
The lower tier comprises of a set of storage engines. The engines are used
for managging tables of a particular type. The storage engine associated with
a table directly accesses it to store or retrieve data.
11
How MySQL uses Disk Space
Data Directories
MySQL stores the location to the folder containing the database in the variable
called datadir and the binaries in basedir .
Database Folder
Each database corresponds to a single folder under the datadir variable value
regardless of what tables you created. The database is storage engine
independent. One database can contain tables with different storage engines.
12
How MySQL uses Disk Space
root@ubuntu:/var/lib/mysql# ls -l
total 122912
-rw-r----- 1 mysql mysql 56 Aug 11 11:19 auto.cnf
-rw-r--r-- 1 root root 0 Aug 11 11:19 debian-5.7.flag
-rw-r----- 1 mysql mysql 291 Aug 11 16:11 ib_buffer_pool
-rw-r----- 1 mysql mysql 12582912 Aug 11 17:28 ibdata1
-rw-r----- 1 mysql mysql 50331648 Aug 11 17:28 ib_logfile0
-rw-r----- 1 mysql mysql 50331648 Aug 11 11:19 ib_logfile1
-rw-r----- 1 mysql mysql 12582912 Aug 11 16:11 ibtmp1
drwxr-x--- 2 mysql mysql 4096 Aug 11 11:19 mysql
drwxr-x--- 2 mysql mysql 4096 Aug 11 11:19 performance_schema
drwxr-x--- 2 mysql mysql 12288 Aug 11 11:19 sys
Check the file system in the /var/lib/mysql folder and notice the test directory
created for the test database.
root@ubuntu:/var/lib/mysql# pwd
/var/lib/mysql
root@ubuntu:/var/lib/mysql# ls -l
-rw-r----- 1 mysql mysql 414 Aug 11 11:19 ib_buffer_pool
-rw-r----- 1 mysql mysql 12582912 Aug 11 11:19 ibdata1
-rw-r----- 1 mysql mysql 50331648 Aug 11 11:19 ib_logfile0
-rw-r----- 1 mysql mysql 50331648 Aug 11 11:19 ib_logfile1
-rw-r----- 1 mysql mysql 12582912 Aug 11 11:19 ibtmp1
drwxr-x--- 2 mysql mysql 4096 Aug 11 11:19 mysql
drwxr-x--- 2 mysql mysql 4096 Aug 11 11:19 performance_schema
drwxr-x--- 2 mysql mysql 12288 Aug 11 11:19 sys
drwxr-x--- 2 mysql mysql 4096 Aug 11 15:40 test
Tables
A table format file (.frm) is created for each table regardless of the
storage engine. The file are placed under the specific database folder.
13
How MySQL uses Disk Space
MyISAM creates a .myd for for stroing the table data and .myi for indexes.
Check the filesystem and notice the person.ibd tablespace created for the
person table.
root@ubuntu:/var/lib/mysql/test# ls -l
total 112
-rw-r----- 1 mysql mysql 65 Aug 11 17:27 db.opt
-rw-r----- 1 mysql mysql 8572 Aug 11 17:28 person.frm
-rw-r----- 1 mysql mysql 98304 Aug 11 17:28 person.ibd
The default tablespace name is ibdata1 and the default log files are named
ib_logfile0 and ib_logfile1 .
14
How MySQL uses Disk Space
DDL
Metadata operations performed by DDL statements
log(metadata log)
15
How MySQL uses Disk Space
Administrative queries and queries without using indexes are not logged.
16
How MySQL uses Disk Space
17
How MySQL Uses Memory
Buffer Pool
The memory area where InnoDB caches data and indexes. The default value is
128MB. The value is set using the innodb_buffer_pool_size .
You can also see the status of the InnoDB buffer pool and memory usage.
Check memory usage under the section BUFFER POOL AND MEMORY
18
How MySQL Uses Memory
On a dedicated server, you can set the pool size to 80% of the machine's physical
memory. The buffer pool size can be set dynamically as of MySQL 5.7.5 without
restarting the server.
19
How MySQL Uses Memory
Thread Stack
The stack for each thread. The default siaze is 192KB(256KB for 64-bit systems).
The stack is large enough for normal operations. If the thread stack is too small, it
limits the complexity of the SQL statements that the server can handle, the
recursion depth of stored procedures.
Temporary Tables
20
How MySQL Uses Memory
Grant Tables
The grant tables store information about MySQL user accounts and privileges
they have. The server loads a copy of the grant tables in memory for fast access.
The memory is not released and can only be freed by FLUSH PRIVILEGES .
Open Tables
A tabke cache holds descriptors of open tables. For frequently used tables,
keeping the descriptors in memory avoids having to open the again and again.
21
How MySQL Uses Memory
22
Monitoring MySQL Memory Usage
Enabling Instruments
To enable all memory instruments, add the following line to the my.cnf config file :
[mysqld]
performance-schema-instrument='memory/%=COUNTED'
23
Monitoring MySQL Memory Usage
24
Monitoring MySQL Memory Usage
By Code Area
25
System Administration
System Administration
1. Types of MySQL distributions
7. Loading the time zone tables for named time zone support
26
Types of MySQL Distributions
27
Starting and Stopping MySQL Server on Unix
when using binary installations MySQL can be started and stopped with the
startup scripts in /etc/init.d
Start MySQL
Stopping MySQL
Check Status
28
Starting and Stopping MySQL Server on Unix
29
Runtime Configuration
Runtime Configuration
The MySQL server maintains sytem variables that indicate how it is configured.
Each system variable has a default value. System variables can be set at server
startup using options on the command line or in an options file.
Some system variables can be dynamically changed whilst the system is running
by using the SET statement without having to stop and restart the server.
[mysqld]
query_cache_size=16M
max_allowed_packet=1G
30
Runtime Configuration
31
Runtime Configuration
Some variables are not available as SESSION variaables and will give an error
Setting Variables
You can use the SET statment with scope of either GLOBAL or SESSION to set
the value of the variable
Using the qualify of K for Kilobytes, M for megabytes or G for Gigabytes is not
allowed when setting value during runtime
32
Runtime Configuration
and checking again, the max_allowed_packet has been reset to the default.
The value will persist as long the server has not been restarted.
However, to set such a variable on the command line or in an option file, you must
set it to 1 or 0 , setting it to ON or OFF will not work.
33
Runtime Configuration
By default the SHOW statement displays session variables. Use SHOW GLOBAL
to show global variables
and you can also use wildcards like _ for a single character and % any character
34
Runtime Configuration
35
Loading Timezone Tables
Check the time_zone table and you will notice its empty
On Unix you can find the system time zone files located in
/usr/share/zoneinfo . These files needs to be converted into a format that
can be located into MySQL.
joseph@ubuntu:/usr/share/zoneinfo$ ls -l
total 324
drwxr-xr-x 2 root root 4096 Jul 17 18:49 Africa
drwxr-xr-x 6 root root 20480 Jul 17 18:49 America
drwxr-xr-x 2 root root 4096 Jul 17 18:49 Antarctica
drwxr-xr-x 2 root root 4096 Jul 17 18:49 Arctic
drwxr-xr-x 2 root root 12288 Jul 17 18:49 Asia
drwxr-xr-x 2 root root 4096 Jul 17 18:49 Atlantic
drwxr-xr-x 2 root root 4096 Jul 17 18:49 Australia
drwxr-xr-x 2 root root 4096 Jul 17 18:49 Brazil
drwxr-xr-x 2 root root 4096 Jul 17 18:49 Canada
drwxr-xr-x 2 root root 4096 Jul 17 18:49 Chile
36
Loading Timezone Tables
Note - You might need to restart the server touse the new time zone data.
Windows distriution comes preloaded with the time zone tables as it does not
support time zone files for the operating system.
37
Setting Default SQL Mode
$ mysqld --sql-mode="TRADITIONAL"
[mysqld]
sql-mode=TRADITIONAL
38
Setting Default SQL Mode
Important Modes
ANSI DB2 MAXDB MYSQL323 MYSQL40 ORACLE POSTGRESQL
TRADITIONAL
39
Upgrading MySQL Server
Upgrading MySQL
In-place upgrade
Involves shutting down the old MySQL version, replacing the old MySQL binaries
or packages with the new ones, restarting MySQL on the existing data directory,
and running mysql_upgrade .
Logical Upgrade
Involves exporting existing data from the old MySQL version using mysqldump ,
installing the new MySQL version, loading the dump file into the new MySQL
version, and running mysql_upgrade
3. Upgrade the MySQL binaries or packages in place, replacing the old binaries
or packages with the new ones.
5. Run mysql_upgrade .
40
Upgrading MySQL Server
5. Start the MySQL 5.7 server, using the new data directory. shell>
bin/mysqld_safe --user=mysql --datadir=/path/to/5.7-datadir
7. Load the previously created dump file into the new MySQL server. shell>
bin/mysql -u root -p password --execute="source data-for-
upgrade.sql" --force
10. Shut down and restart the MySQL server to ensure a clean shutdown and
startup. shell> bin/mysqladmin -u root -p password shutdown
shell> bin/mysqld_safe --user=mysql --datadir=/path/to/5.7-
datadir
41
Client Programs for DBA Work
2. The mysql
42
MySQL WorkBench
MySQL Workbench
MySQL is a graphical client for easier management of a MySQL database.
43
Command Line Clients
mysql
Is a simple shell with input line editing capabilites. It supports interactive and
noninteractive use. Whe used interactively,q query results are presented in an
ASCII-table format.
joseph@ubuntu:~$ mysql
or with options
44
mysqladmin - Client for Administering a MySQL Server
45
mysqladmin - Client for Administering a MySQL Server
46
mysqladmin - Client for Administering a MySQL Server
47
mysqladmin - Client for Administering a MySQL Server
48
mysqladmin - Client for Administering a MySQL Server
49
mysqlcheck - A Table Maintenance Program
50
mysqldump - A Database Backup Program
51
mysqlimport - A Data Import Program
52
mysqlshow - Display Database, Table, and Column Information
53
mysqlslap - Load Emulation Client
54
MySQL Workbench
MySQL Workbench
1. An overview of MySQL Workbench features
55
User Management
User Management
1. Requirements for user authentication
7. Types of privileges
56
Data Types
Data Types
1. Major categories of data types
2. Meaning of NULL
3. Column attributes
57
Character Set Support
Character Set Support What is Character Set A character set is a set of symbols
and encodings. Suppose that we have an alphabet with four letters: A, B, a,
b . We give each letter a number: A = 0, B = 1, a = 2, b = 3 . The letter
A is a symbol, the number 0 is the encoding for A , and the combination
of all four letters and their encodings is a character set .
MySQL includes character set support that enables you to store data using a
variety of character sets and perfrom comparisons according to a variety of
collations. You can specifiy character sets at the server, database, table and
column level. MySQL supports the use of character sets for the MyISAM,
MEMORY,a dn InnoDB storage engines.
Performance Issues
MySQL will need tobe compiled from the source to remove unnecessary character
sets.
Notice the length of the character set. utf8 requires 3 bytes per character.
So a column with CHAR(32) will require 96 bytes using utf8
58
Character Set Support
59
Character Set Support
60
Character Set Support
Show Server Character Set mysql> show variables like 'character_set_server'; +--
--------------------+--------+ | Variable_name | Value | +----------------------+--------+ |
character_set_server | latin1 | +----------------------+--------+
Set Server Character Set You can specifiy the character set and collation during
startup
Database Character Set and Collation Every database has a character set and a
collation.
61
Character Set Support
62
Transactions and Locking
3. Locking concepts
63
Locking Concepts
Locking Concepts
The effect of the locking mechanism is to serialize access to data so that when
multiple clients want to perform conflicting operations, each must wait its turn.
If a client wants to read data, other clients that want to read the same data do not
produce a conflict, and they all can read at the same time. A client that wants to
write must wait until the read has finside.
If a client wants to write data, all other clients must wait until the write has finished,
regardless of whether those clients want to read or write.
A reader must block writers, but not other readers\/ A writer must block both
readers and writers.
Acquiring Locks
For a client that does nothing special to acquire locks, the MySQL Server impicitly
acquires locks as necessary to process the client's statmenets safely. For
example, the server acquires a read lock when the client issues a SELECT
statmenet.
LOCK TABLES
and check that the lock has been acquired, table shows its in use
64
Locking Concepts
There's no need to pass in the table names. All the locks are realesed for the
current client.
READ
Locks a table for reading. A READ lock locks a table for read quieries such as
SELECT that retrieve data from a table. It does not allow write operations such as
INSERT, DELETE, or UPDATE that modify the table, even by the client that holds
the lock.
WRITE
Locks a table for wiriting. A WRITE lock is an exclsive lock. Once acquired, only
the client holding the write lock can read from or write to the table. Other clients
can neither read from nor write to it.
READ LOCAL
Locks a table for reading, but allows concurrent inserts. Only applies to MyISAM
table. Insert will be appended at the end. Will not work if the table have holes,
(deletes inside the table).
LOW_PRIORITY_WRITE
65
Locking Concepts
Locks a table for writing, but acquires the lock with a lower priority.That is, if the
client must wait for the lock, other clients that request read locks during the wait
are allowed to get their lock first.
66
Advisory Locks
Advisory Locks Also called a cooperative lock. Advisory locks do not lock data and
they do not prevent access to data by clients except to the extent that they
cooperate with each other. Unlike implicit and explicit locks, advisory locks are not
managed by the server. Clients manage advisory lcoks using a set of function
calls to cooperate among themselves.
The first argument is the name ofbe locked, and the second the argument is the
timeout value in seconds that indicates hwo long to wait for the lock if it cannot be
acquired. Returns 1 for success, 0 if a timeout occured and the lock cannot be
acquired, NULL if an error occured.
67
Advisory Locks
Return the connection id of the client that holds the lock on the name, or NULL if
the name is not locked.
68
Obtaining Metadata
Obtaining Metadata
1. Available metadata access methods
4. Limitation of INFORMATION_SCHEMA
69
Storage Engines
Storage Engines
1. An overview of storage engines in MySQL
7. InnoDB locking
70
MySQL Storage Engines Overview
MySQL uses a pluggable architecture for the sotrage engines. Each table is
created using a specific storage engine.
71
MySQL Storage Engines Overview
mysql>
mysql> select table_name, engine from information_schema.tables
where table_name = 'person';
+------------+--------+
| table_name | engine |
+------------+--------+
| person | InnoDB |
+------------+--------+
1 row in set (0.01 sec)
72
MyISAM Storage Engine
73
InnoDB Storage Engine
74
InnoDB Memcached Storage Plugin
75
Memory Engine
Memory Engine
76
Federated Engine
Federated Engine
77
Partitioning
Partitioning
1. Partitions and its use in MySQL
3. Types of partitioning
5. Subpartitioning
78
Why Partition
Why Partition
Makes it possible to store more data in one table more than cab ne held on a
single disk or file system.
Easy to add and drop partitions.
Improves query performance by retrieving data from specific partitions using
a technique called partition pruning
Partitioning applies to all data and indexes of a table, you cannot partition only the
data and not the indexes, or vice versa, nor can you partion only a portion of the
table.
79
Types of Partitioning
Partion Types
Range
List
Columns
Hash
Key
Sub partitioning
Range Partitioning
A table that is partitioned by range is partitioned in such a way that each partition
contains rows for which the partitioning expression value lies within a given range.
or we can alternatively partition by store_id and have the other values that do
no match the partions go into a catch-all partition. We use the MAXVALUE to
specify all the other values.
80
Types of Partitioning
81
Types of Partitioning
If you try to insert values that are not within range, you will get an error.
82
Types of Partitioning
Hash Partitioning
Partitioning by HASH is used primarily to ensure an even distribution of data
among a predetermined number of partitions. MySQL takes care of calculating the
hash function for you.
83
Types of Partitioning
or we can pass an SQL expression that returns an integer and MySQL will
calculate the hash for us.
CREATE TABLE k1 (
id INT NOT NULL PRIMARY KEY,
name VARCHAR(20)
)
PARTITION BY KEY()
PARTITIONS 2;
84
Types of Partitioning
Sub Partitioning
Subpartitioning—also known as composite partitioning—is the further division of
each partition in a partitioned table.
85
Creating Partitioned Tables
Partitoning Tables
+----------------------------+----------+--------------------+--
-------+---------+
+----------------------------+----------+--------------------+--
-------+---------+
mysql> SELECT
+--------------------+---------+----------+
+--------------------+---------+----------+
86
Creating Partitioned Tables
+--------------------+---------+----------+
87
Security
Security
1. Recognizing common security risks
88
Table Maintenance
Table Maintenance
1. Type of table maintenance operations
89
Exporting and Importing Data
2. Importing Data
90
Programming inside MySQL
Programming MySQL
1. Creating and executing Stored Procedures
91
MySQL Backup and Recovery
92
Replication
Replication
1. Managing the MySQL binary log
93
Setting Master Server
[mysqld]
log_bin
[mysqld]
master-id = 1
[mysqld]
binlog_do_db = employees
94
Setting Master Server
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| bind_address | * |
+---------------+-------+
Or should return an ip address not 127.0.0.1 . Replication does not use the
Unix socket, it requires TCP/IP.
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| skip_networking | OFF |
+-----------------+-------+
95
Setting Master Server
Flush the privileges cache tables for the new login to take effect.
FLUSH PRIVILEGES;
use employees;
FLUSH TABLES WITH READ LOCK;
Show the master status to find the position in the binary log
96
Setting Master Server
+-------------------+----------+------------------+-------------
-----+-------------------+
+-------------------+----------+------------------+-------------
-----+-------------------+
+-------------------+----------+------------------+-------------
-----+-------------------+
Record the position and take note of the name of the binary log.
with the --master-data option set, the mysqldump will write the the CHANGE
TO MASTER line in the dump file.
97
Setting Master Server
98
Setting Up Replication on the Salve Database
Setup server-id
Change the slave server server-id in the options file /etc/mysql/my.cnf
[mysqld]
server-id = 2
99
Setting Up Replication on the Salve Database
Enter password:
CHANGE MASTER TO
MASTER_HOST='master',
MASTER_USER='slave_user',
MASTER_PASSWORD='password';
CHANGE MASTER TO
MASTER_HOST='master',
MASTER_USER='slave_user',
MASTER_PASSWORD='password',
MASTER_LOG_FILE='master-bin',
MASTER_LOG_POS=595;
100
Introduction to Performance Tuning
5. Overview of PERFORMANCE_SCHEMA
101
Index Types
Index Types
102
Clustered Index
Types of Indexes
B-Tree Index
When you hear in the industry the word index, they often mean a B-tree index.
Most of the MySQL storage engine supports B-tree indexes. In B-tree index, each
leaf node contains a link to the next node for the fast range traversal. All the
values are stored in order and each leaf page is at the same distance from root
level.
103
Clustered Index
104
Clustered Index
105
Clustered Index
106
Secondary Index
Clustered Index
107
Basic Indexing
Basic Indexing
+-------+------------+-------------------+--------------+-------
------+-----------+-------------+----------+--------+------+----
--------+---------+---------------+
+-------+------------+-------------------+--------------+-------
------+-----------+-------------+----------+--------+------+----
--------+---------+---------------+
+-------+------------+-------------------+--------------+-------
------+-----------+-------------+----------+--------+------+----
--------+---------+---------------+
108
Basic Indexing
+-------+------------+-------------------+--------------+-------
------+-----------+-------------+----------+--------+------+----
--------+---------+---------------+
+-------+------------+-------------------+--------------+-------
------+-----------+-------------+----------+--------+------+----
--------+---------+---------------+
+-------+------------+-------------------+--------------+-------
------+-----------+-------------+----------+--------+------+----
--------+---------+---------------+
Use INFORMATION_SCHEMA.STATISTICS to
show indexes
The INFORMATION_SCHEMA.STATISTICS contains index information for all tables;
109
Basic Indexing
+------------+------------+-------------------+-------------+---
----------+
+------------+------------+-------------------+-------------+---
----------+
+------------+------------+-------------------+-------------+---
----------+
110
Basic Indexing
+---------+--------+
| film_id | length |
+---------+--------+
| 65 | 100 |
| 71 | 100 |
| 221 | 100 |
| 236 | 100 |
| 322 | 100 |
| 387 | 100 |
| 399 | 100 |
| 445 | 100 |
| 681 | 100 |
| 703 | 100 |
| 979 | 100 |
| 994 | 100 |
+---------+--------+
111
Basic Indexing
+----+-------------+-------+------------+------+---------------+
------+---------+------+------+----------+-------------+
+----+-------------+-------+------------+------+---------------+
------+---------+------+------+----------+-------------+
+----+-------------+-------+------------+------+---------------+
------+---------+------+------+----------+-------------+
You can notive no indexes are being used for this query, in the possible_keys
column there's no index that can satisfy this query.
We can also enable profiling and see how the query was run until we got the
result sback.
Enable Profiling
Notice the warning. Oracle recommends to use the performance schema instead.
112
Basic Indexing
Run the query again and now use the SHOW PROFILES statements to see the
gathered shows.
+----------+------------+---------------------------------------
--------------+
+----------+------------+---------------------------------------
--------------+
+----------+------------+---------------------------------------
--------------+
113
Basic Indexing
+--------------------------------+----------+
| Status | Duration |
+--------------------------------+----------+
| starting | 0.000106 |
| starting | 0.000005 |
| cleaning up | 0.000009 |
+--------------------------------+----------+
Install pt-visual-explain
114
Basic Indexing
+- Table scan
rows 1000
+- Table
table film
We can notice that we are doing an index scan on the table and touching 1000
row.
Create an index
Lets create an index on the length column.
115
Basic Indexing
+----+-------------+-------+------------+------+----------------
+----------------+---------+-------+------+----------+----------
---+
+----+-------------+-------+------------+------+----------------
+----------------+---------+-------+------+----------+----------
---+
+----+-------------+-------+------------+------+----------------
+----------------+---------+-------+------+----------+----------
---+
Notice now we are using an index on the possible_keys . The index name is
ix_film_length our newly created index. Also the extra column shows that
we are now using an index.
116
Order of Indexes
Order of Indexes
Although the CREATE INDEX allows specifying the ORDER , ASC or DESC it
does not matter on an index, since the travesal is the same.
Show indexes
+-------+------------+-----------------------------+------------
--+----------------------+-----------+-------------+----------+-
-------+------+------------+---------+---------------+
+-------+------------+-----------------------------+------------
--+----------------------+-----------+-------------+----------+-
-------+------+------------+---------+---------------+
+-------+------------+-----------------------------+------------
--+----------------------+-----------+-------------+----------+-
-------+------+------------+---------+---------------+
117
Order of Indexes
+----+-------------+-------+------------+------+---------------+
------+---------+------+------+----------+-------------+
+----+-------------+-------+------------+------+---------------+
------+---------+------+------+----------+-------------+
+----+-------------+-------+------------+------+---------------+
------+---------+------+------+----------+-------------+
118
Order of Indexes
+----+-------------+-------+------------+------+----------------
-+-----------------+---------+-------+------+----------+--------
-----+
+----+-------------+-------+------------+------+----------------
-+-----------------+---------+-------+------+----------+--------
-----+
+----+-------------+-------+------------+------+----------------
-+-----------------+---------+-------+------+----------+--------
-----+
You will notice our newly created index is now being used.
119
Order of Indexes
+----+-------------+-------+------------+------+----------------
----------------------+-----------------+---------+-------+-----
-+----------+-------------+
+----+-------------+-------+------------+------+----------------
----------------------+-----------------+---------+-------+-----
-+----------+-------------+
+----+-------------+-------+------------+------+----------------
----------------------+-----------------+---------+-------+-----
-+----------+-------------+
Notice they are now two possible indexes to satisfy this query, the
idx_file_length and idx_film_length_desc . The optimize does chose the
first one, which is by default in ascending order
120
OR Conditional with Indexes
+----+-------------+-------+------------+------+----------------
----------------------+------+---------+------+------+----------
+-------------+
+----+-------------+-------+------------+------+----------------
----------------------+------+---------+------+------+----------
+-------------+
+----+-------------+-------+------------+------+----------------
----------------------+------+---------+------+------+----------
+-------------+
Notice they are two possible keys for the query but none of the keys was used.
121
OR Conditional with Indexes
+----+-------------+-------+------------+------+----------------
----------+------+---------+------+------+----------+-----------
--+
+----+-------------+-------+------------+------+----------------
----------+------+---------+------+------+----------+-----------
--+
+----+-------------+-------+------------+------+----------------
----------+------+---------+------+------+----------+-----------
--+
+-------+------+--------
122
OR Conditional with Indexes
and we also change the order of the columns in the SELECT query
123
OR Conditional with Indexes
+----+-------------+-------+------------+------+----------------
------------------------------------------+------+---------+----
--+------+----------+-------------+
+----+-------------+-------+------------+------+----------------
------------------------------------------+------+---------+----
--+------+----------+-------------+
+----+-------------+-------+------------+------+----------------
------------------------------------------+------+---------+----
--+------+----------+-------------+
124
OR Conditional with Indexes
125
OR Conditional with Indexes
id: 1
select_type: SIMPLE
table: film
partitions: NULL
type: ref
possible_keys: idx_film_rental_duration,idx_film_rental_duration
_length
key: idx_film_rental_duration
key_len: 1
ref: const
rows: 212
filtered: 100.00
Extra: NULL
and
126
OR Conditional with Indexes
+----+-------------+-------+------------+------+----------------
-----------------+---------------------------------+---------+--
-----+------+----------+-------+
+----+-------------+-------+------------+------+----------------
-----------------+---------------------------------+---------+--
-----+------+----------+-------+
+----+-------------+-------+------------+------+----------------
-----------------+---------------------------------+---------+--
-----+------+----------+-------+
127