mysql explain

https://mariadb.com/kb/en/mariadb/explain/

The columns in EXPLAIN ... SELECT

Column nameDescription
idSequence number that shows in which order tables are joined.
select_typeWhat kind of SELECT the table comes from.
tableAlias name of table. Materialized temporary tables for sub queries are named <subquery#>
typeHow rows are found from the table (join type).
possible_keyskeys in table that could be used to find rows in the table
keyThe name of the key that is used to retrieve rows. NULL is no key was used.
key_lenHow many bytes of the key that was used (shows if we are using only parts of the multi-column key).
refThe reference that is used to as the key value.
rowsAn estimate of how many rows we will find in the table for each key lookup.
ExtraExtra information about this join.
Here are descriptions of the values for some of the more complex columns in EXPLAIN ... SELECT:

"select_type" column

The select_type column can have the following values:
ValueDescription
PRIMARYThe SELECT is a PRIMARY one.
SIMPLEThe SELECT is a SIMPLE one.
DERIVEDThe SELECT is DERIVED from the PRIMARY.
SUBQUERYThe SELECT is a SUBQUERY of the PRIMARY.
DEPENDENT SUBQUERYThe SUBQUERY is DEPENDENT.
UNCACHEABLE SUBQUERYThe SUBQUERY is UNCACHEABLE.
UNIONThe SELECT is a UNION of the PRIMARY.
UNION RESULTThe result of the UNION.
DEPENDENT UNIONThe UNION is DEPENDENT.
UNCACHEABLE UNIONThe UNION is UNCACHEABLE.

"Type" column

This column contains information on how the table is accessed.
ValueDescription
ALLA full table scan is done for the table (all rows are read). This is bad if the table is large and the table is joined against a previous table! This happens when the optimizer could not find any usable index to access rows.
constThere is only one possibly matching row in the table. The row is read before the optimization phase and all columns in the table are treated as constants.
eq_refA unique index is used to find the rows. This is the best possible plan to find the row.
fulltextA fulltext index is used to access the rows.
index_mergeA 'range' access is done for for several index and the found rows are merged. The key column shows which keys are used.
index_subqueryThis is similar as ref, but used for sub queries that are transformed to key lookups.
indexA full scan over the used index. Better than ALL but still bad if index is large and the table is joined against a previous table.
rangeThe table will be accessed with a key over one or more value ranges.
ref_or_nullLike 'ref' but in addition another search for the 'null' value is done if the first value was not found. This happens usually with sub queries.
refA non unique index or prefix of an unique index is used to find the rows. Good if the prefix doesn't match many rows.
systemThe table has 0 or 1 rows.
unique_subqueryThis is similar as eq_ref, but used for sub queries that are transformed to key lookups

"Extra" column

This column consists of one or more of the following values, separated by ';'
Note that some of these values are detected after the optimization phase.
The optimization phase can do the following changes to the WHERE clause:
  • Add the expressions from the ON and USING clauses to the WHERE clause.
  • Constant propagation: If there is column=constant, replace all column instances with this constant.
  • Replace all columns from 'const' tables with their values.
  • Remove the used key columns from the WHERE (as this will be tested as part of the key lookup).
  • Remove impossible constant sub expressions. For example WHERE '(a=1 and a=2) OR b=1' becomes 'b=1'.
  • Replace columns with other columns that has identical values: Example: WHERE a=b and a=c may be treated as'WHERE a=b and a=c and b=c'.
  • Add extra conditions to detect impossible row conditions earlier. This happens mainly with OUTER JOIN where we in some cases add detection of NULL values in the WHERE (Part of 'Not exists' optimization). This can cause an unexpected 'Using where' in the Extra column.
  • For each table level we remove expressions that have already been tested when we read the previous row. Example: When joining tables t1 with t2 using the following WHERE 't1.a=1 and t1.a=t2.b', we don't have to test 't1.a=1' when checking rows in t2 as we already know that this expression is true.
ValueDescription
const row not foundThe table was a system table (a table with should exactly one row), but no row was found.
DistinctIf distinct optimization (remove duplicates) was used. This is marked only for the last table in the SELECT.
Full scan on NULL keyThe table is a part of the sub query and if the value that is used to match the sub query will be NULL, we will do a full table scan.
Impossible HAVINGThe used HAVING clause is always false so the SELECT will return no rows.
Impossible WHERE noticedafter reading consttables.The used WHERE clause is always false so the SELECT will return no rows. This case was detected after we had read all 'const' tables and used the column values as constant in the WHERE clause. For example: WHERE const_column=5 and const_column had a value of 4.
Impossible WHEREThe used WHERE clause is always false so the SELECT will return no rows. For example: WHERE 1=2
No matching min/max rowDuring early optimization of MIN()/MAX() values it was detected that no row could match the WHERE clause. The MIN()/MAX() function will return NULL.
no matching row in consttableThe table was a const table (a table with only one possible matching row), but no row was found.
No tables usedThe SELECT was a sub query that did not use any tables. For example a there was no FROM clause or a FROM DUAL clause.
Not existsStop searching after more row if we find one single matching row. This optimization is used with LEFT JOIN where one is explicitly searching for rows that doesn't exists in the LEFT JOIN TABLE. Example: SELECT * FROM t1 LEFT JOIN t2 on (...) WHERE t2.not_null_column IS NULL. As t2.not_null_column can only be NULL if there was no matching row for on condition, we can stop searching if we find a single matching row.
Open_frm_onlyFor INFORMATION_SCHEMA tables. Only the frm (table definition file was opened) was opened for each matching row.
Open_full_tableFor INFORMATION_SCHEMA tables. A full table open for each matching row is done to retrieve the requested information. (Slow)
Open_trigger_onlyFor INFORMATION_SCHEMA tables. Only the trigger file definition was opened for each matching row.
Range checked for eachrecord (index map: ...)This only happens when there was no good default index to use but there may some index that could be used when we can treat all columns from previous table as constants. For each row combination the optimizer will decide which index to use (if any) to fetch a row from this table. This is not fast, but faster than a full table scan that is the only other choice. The index map is a bitmask that shows which index are considered for each row condition.
Scanned 0/1/all databasesFor INFORMATION_SCHEMA tables. Shows how many times we had to do a directory scan.
Select tables optimizedawayAll tables in the join was optimized away. This happens when we are only using COUNT(*), MIN() and MAX() functions in the SELECT and we where able to replace all of these with constants.
Skip_open_tableFor INFORMATION_SCHEMA tables. The queried table didn't need to be opened.
unique row not foundThe table was detected to be a const table (a table with only one possible matching row) during the early optimization phase, but no row was found.
Using filesortFilesort is needed to resolve the query. This means an extra phase where we first collect all columns to sort, sort them with a disk based merge sort and then use the sorted set to retrieve the rows in sorted order. If the column set is small, we store all the columns in the sort file to not have to go to the database to retrieve them again.
Using indexOnly the index is used to retrieve the needed information from the table. There is no need to perform an extra seek to retrieve the actual record.
Using index conditionLike 'Using where' but the where condition is pushed down to the table engine for internal optimization at the index level.
Using index condition(BKA)Like 'Using index condition' but in addition we use batch key access to retrieve rows.
Using index for group-byThe index is being used to resolve a GROUP BY or DISTINCT query. The rows are not read. This is very efficient if the table has a lot of identical index entries as duplicates are quickly jumped over.
Using intersect(...)For index_merge joins. Shows which index are part of the intersect.
Using join bufferWe store previous row combinations in a row buffer to be able to match each row against all of the rows combinations in the join buffer at one go.
Using sort_union(...)For index_merge joins. Shows which index are part of the union.
Using temporaryA temporary table is created to hold the result. This typically happens if you are using GROUP BY, DISTINCT or ORDER BY.
Using whereA WHERE expression (in additional to the possible key lookup) is used to check if the row should be accepted. If you don't have 'Using where' together with a join type of ALL, you are probably doing something wrong!
Using where with pushedconditionLike 'Using where' but the where condition is pushed down to the table engine for internal optimization at the row level.
Using bufferThe UPDATE statement will first buffer the rows, and then run the updates, rather than do updates on the fly. See Using Buffer UPDATE Algorithm for a detailed explanation.

EXPLAIN EXTENDED

The EXTENDED keyword adds another column, filtered, to the output. This is a percentage estimate of the table rows that will be filtered by the condition.
An EXPLAIN EXTENDED will always throw a warning, as it adds extra Message information to a subsequent SHOW WARNINGSstatement. This includes what the SELECT query would look like after optimizing and rewriting rules are applied and how the optimizer qualifies columns and tables.

php opcache

With the release of Ubuntu 14.04 and the proliferation of PHP 5.5, there is going to be a migration away from Alternative Performance Cache (APC) and toward PHP’s new built-in OPcache.

This is a logical move that seems destined for any interpreted language.  As websites have become more and more complicated with many processes running, opcode caching has become a necessity – fortunately, it’s simple to implement.

The php.net site has a nice page of all the runtime options available, but we will cover the basics here to get you started quickly.

All you need to do to get OPcache set up is to make changes in the php.ini file on your server.

Open php.ini In Your Favorite Text Editor
To get started open your php.ini file.

Apache web-servers

/etc/php5/apache2/php.ini
Nginx web-servers with PHP-FPM

/etc/php5/fpm/php.ini
Enable the OPcache
To enable the OPcache, change to the following lines — easy enough!


;opcache.enable=0
Change to:


opcache.enable=1
Note: you have to uncomment this line as well as change the “0″ to “1″.

Modify the Amount of RAM the OPcache Will Use
With OPcache, there is a trade-off between speed and the amount of RAM used. The more RAM you are willing to dedicate to storing opcode, the more opcode that can be stored. There is a diminishing return at some point, because some code will execute rarely, or your code base might not be that big. It is worth playing with this setting to see where you get the best performance-versus-RAM trade-off.  This setting is in megabytes.


;opcache.memory_consumption=64
Change to:


opcache.memory_consumption=128
Boost the Number of Scripts that Can Be Cached
OPcache has a strange setting that requires you to not only adjust the amount of RAM, but also define the number of scripts that can be cached. You have the option of tuning this parameter for your own application too, especially if you find that your hit rate is not close to 100 percent.


;opcache.max_accelerated_files=2000
Change to:


opcache.max_accelerated_files=4000
Change the Revalidate Frequency
To make sure that the OPcache notices when you change your PHP code, you can set the revalidate frequency. Basically, this will tell the cache how often to check the timestamp on the files. This is measured in seconds.


;opcache_revalidate_freq = 2
Change to:


opcache_revalidate_freq = 240
Verify that the PHP OPcache Mod is Enabled
Believe it or not, that converts most of the settings you will need to get started. PHP5 has its own module system (since 5.4), so make sure that OPcache is enabled.


sudo php5enmod opcache
Restart PHP and Your Server
You should now be all set to start using PHP 5.5’s OPcache. You just need to restart your server to get it going.

Apache Web-Servers

sudo service apache2 restart
Nginx Web-Servers

sudo service nginx restart

mysql isolation level

https://www.facebook.com/note.php?note_id=244956410932
There is a lot of documentation available on transaction isolation levels for InnoDB includingthe InnoDB transaction model, a description of the isolation levels, notes on locks, locks set by statements and notes on consistent non-locking reads.

There is another issue that has not been documented. The code that creates a read view(snapshot) for InnoDB transactions is a source of mutex contention on kernel_mutex. This code is run once per statement for read-committed and once per transaction for repeatable-read.

The function read_view_open_now is run to create a snapshot. It copies the list of uncommitted transactions into a per-transaction data structure. Memory is allocated from the per-transaction heap to store the copied data and that allocation might require a call to malloc. All of this work is done while holding kernel_mutex and other threads are unlikely to get much work done in InnoDB when kernel_mutex is locked.

Subscribe to feature request 49169 if you are interested in this. I am not sure if there is an easy fix. Work can be done to reduce the chance of allocating memory while copying the open transaction list. But splitting kernel_mutex into several locks might be hard.

When repeatable-read is used there are fewer calls to read_view_open_now and there is less contention on kernel_mutex. I ran sysbench to measure the difference in performance.

http://dev.mysql.com/doc/refman/5.5/en/innodb-transaction-isolation-levels.html#isolevel_read-committed
https://easyengine.io/tutorials/mysql/enable-innodb-file-per-table/
https://www.brightbox.com/blog/2013/10/31/on-mysql-locks/
http://stackoverflow.com/questions/20321407/mysql-table-lock-instead-of-row-locks
https://www.percona.com/blog/2015/01/14/mysql-performance-implications-of-innodb-isolation-modes/
https://www.percona.com/blog/2012/08/28/differences-between-read-committed-and-repeatable-read-transaction-isolation-levels/

https://www.simple-talk.com/sql/t-sql-programming/questions-about-t-sql-transaction-isolation-levels-you-were-too-shy-to-ask/

https://www.percona.com/blog/2012/07/31/innodb-table-locks/


http://stackoverflow.com/questions/20173670/clarifying-the-difference-between-row-level-lock-in-innodb-engine-and-table-leve


change isolation level:-
SELECT @@GLOBAL.tx_isolation, @@tx_isolation; 

SET global TRANSACTION ISOLATION LEVEL READ COMMITTED; 
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SET global TRANSACTION ISOLATION LEVEL REPEATABLE READ; 

SET GLOBAL tx_isolation='READ-COMMITTED';

SET SESSION tx_isolation='READ-COMMITTED';

]# mysql -e "show variables" | grep isolation

tx_isolation    READ-COMMITTED

## disable binlog  OR
SET GLOBAL binlog_format = 'ROW';  

error: rlm_sql_mysql: MySQL error 'Binary logging not possible. Message: Transaction level 'READ-COMMITTED' in InnoDB is not safe for binlog mode 'STATEMENT''

SET GLOBAL binlog_format = 'ROW';  


If you are not planning to use your MySQL server for the replication consider turning the binary logging off by removing the option --log-bin from the command options for the mysqld utility starting the MySQL server.



Innodb buffer pool insight

http://dev.mysql.com/doc/refman/5.6/en/optimizing-innodb-diskio.html

Buffer pool content

InnoDB data is stored in 16 KB pages (blocks), either on disk (ibdata files) or in memory (buffer pool). Each one of these pages may contain one or more row.
The buffer pool is basically a cache for these pages: once a page’s content is requested by a query, the page is cached in the buffer pool.
You may be wondering what kind of data is stored in these pages. Short answer: indexes (on a size point of view).
MySQL offers a very useful INFORMATION_SCHEMA database, which contains since version 5.5 a table named innodb_buffer_page. This table holds 1 record (row) per page in the buffer pool, including interesting data such as what the page contains.
https://dev.mysql.com/doc/refman/5.5/en/innodb-buffer-pool.html#innodb-buffer-pool-lru

innodb_buffer_pool_instances

If innodb_buffer_pool_size is set to more than 1GB, innodb_buffer_pool_instances divides the InnoDB buffer pool into a specific number of instances. The default was 1 in MariaDB 5.5, but for large systems with buffer pools of many gigabytes, many instances can help reduce contention concurrency. The default is 8 in mysql 5.7 and MariaDB 10.0, with the exception of 32-bit Windows, where it depends on the value of innodb_buffer_pool_size. Each instance manages its own data structures and takes an equal portion of the total buffer pool size, so for example if innodb_buffer_pool_size is 4GB and innodb_buffer_pool_instances is set to 4, each instance will be 1GB. Each instance should ideally be at least 1GB in size.
Writing modified pages back to disk
When you make a modification to an InnoDB page, InnoDB does not write it immediately to disk. Instead a delta is written to the transaction log (see below).
These modified-only-in-memory pages are typically reffered to as dirty pages. Writing down dirty pages happens as part of InnoDB's background process which continually performs work every 1 second, and it adjusts well to peaks and troughs in load with a feature introduced in MySQL 5.5 and further improved in MySQL 5.6 called adaptive flushing. However, if there are too many dirty pages and there is not enough free space, InnoDB may be forced to synchronously flush a dirty page to make free space.
This delaying allows InnoDB to perform fewer random writes, since there will usually be multiple changes to the same page, or by default pages in the same extent (1MB allocation unit on disk). MySQL also 5.6 allows you to disable this for SSDs.
(Note: Domas makes a comment about the doublewrite buffer below, and how I might be over-selling request merging :) It's outside of the scope covered here, but described in Facebook's blog and the MySQL manual).
Writing the transaction log
Any time you modify an InnoDB page a record of this modification is made to InnoDB's transaction log system (ib_logfile1 and ib_logfile0 on disk). This transaction log is designed to be sequentially written, and unless the server crashes the server will only ever write and not read from it.
The log files are cyclical by design. You can think of them as a concatentation of two (by default) that behave similar to tread on a tank. So the first one is filled, then the second, then InnoDB will start filling the first again. The writes to the transaction log will be 512B aligned and using the operating system's buffered IO. InnoDB actually relies on the operating system here to provide a cache of the log (which is not guaranteed). Since these writes are 512B - and a typical page is 4K what will happen without enough cache, is that the page will neeed to be read first, to make the partial-modification, then written back.
To reduce log file IO, InnoDB also has a log buffer (configured by innodb_log_buffer_size) that is filled with pending modifications which will be written and synced on any COMMIT by default.
Writing the slow log and general log
The general log is written out as each event is generated. It will be a sequential write, and is never synced or never read back (should be fairly low cost).
The slow query log is written out after query execution has finished. Similiar to the general log, it should also be very log cost.
Why I say "should" is that this also depends on filesystem choice. An fsync under ext3 does not flush one file, but all files. This has become known as the great fsync() bug. Also, the operating system will usually have a limit the amount of modifications queued up waiting to be written, so too much log activity could cause synchronous writing and impact other operations (see Domas' comment below).

IO on a Replication Master (aka binary log enabled)

The binary log is sequential IO written to as part of a COMMIT operation, but by default it is never flushed, so it is not crash-safe! It requires setting sync_binlog=1.
The binary log does not have its own in memory buffers, so it's possible if an out of date slave came online that the master server may need to read old binary log files in order to send previous server events. However in practice the master pushes changes to online slaves as they are committed so it should be write-only.
The server maps changes in the binary log to InnoDB's transaction log to ensure consistency by default.
IO on a Replication Slave
The relay logs are in the same format as the binary logs, but the IO semantics are a little different. The slave's IO_THREAD retrieves new events from the master and writes sequential IO relay log files on the slave. Then the SQL_THREAD then reads the changes from the relay logs and applies them. This read operation does not have any caches inside of MySQL to ensure no IO is performed, and instead relies on the operating system's buffered IO to assist. It's possible to decrease the amount of relay logs kept on the slave to assist in a better 'cache fit', but this also means that if the master fails there may be changes the slave was not aware of.

Writing the relay logs is not crash-safe by default, and requires setting sync_relay_log=1.
Also, the status files which maintain a mapping between the relay logs and master's binary logs (which are not a 1:1) are also not crash-safe. A new option in MySQL 5.6 allows you to use an internal table to maintain these status files for added safety, but it is not enabled by default. The new options are master-info-repository and relay-log-info-repository.

Summary
I am sure I made a couple of simplifications (for example not describing the doublewrite buffer), but hopefully it's a good start. There are a couple of key take away points I want to make:
Reads are foregrounded (except read-ahead) and don't provide the same opportunity reorder and merge - so that makes them typically random IO and very expensive. If you run a diagnostic command like iostat and you see a lot of reads on a warmed up server - this is something adding memory can usually solve.
Most writes are sequential or backgrounded. Both InnoDB and the operating system try to produce sequential IO and merge requests.
While InnoDB has always been crash safe by default, MySQL has not. There are new features in MySQL 5.6 which makes replication more reliable.

Innodb_buffer_pool_read_requests and Innodb_buffer_pool_reads are the values you need to monitor for buffer reads and disk read for the Buffer Pool.
What you are looking for is a cache miss rate of 1% or less based on this
Innodb_buffer_pool_reads X 100 / Innodb_buffer_pool_read_requests
I have written posts like this before
You should also be tracking how much data is being poured into the InnoDB transaction logs
Example
you could take the delta of Innodb_os_log_written (bytes written in a one second window) and divide it by the delta of Innodb_log_writes and track how many bytes are being flushed to the logs per second. If the result seems too high for you, you could tweek innodb_flush_method, innodb_flush_log_at_trx_commit, innodb_log_file_size and things of this nature.

find query per second (qps) with mytop

Centos6
1) using "mysqladmin status"

OR

 rpm -ivh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
yum install mytop -y

mytop -uroot  --prompt  -d  databasename






imapsync

This summary is not available. Please click here to view the post.

tar backup and restore

To Create the Backup Archive:

sudo tar -cvpzf yourbackupfilename.tar.gz --exclude=/path/to/backup/yourbackupfilename.tar.gz --one-file-system /

In the last part of the command a single forward slash will backup the entire root directory, or you can specify a certain directory to backup.

Restoring your backup:

sudo tar -xvpzf /path/to/yourbackupfilename.tar.gz -C /directory/to/restore/to --numeric-owner

If restoring a complete root directory backup the last section of this command would simply be a forward slash /

grep email address from file

grep -E -o "\b[_a-zA-Z0-9.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9.-]+\b"

E=extended regex
o=only print matching string

optimum mysql configuration

 [mysql]  
 # CLIENT #  
 port              = 3306  
 socket             = /var/lib/mysql/mysql.sock  
 [mysqld]  
 # GENERAL #  
 user              = mysql  
 default-storage-engine     = InnoDB  
 socket             = /var/lib/mysql/mysql.sock  
 pid-file            = /var/lib/mysql/mysql.pid  
 # MyISAM #  
 key-buffer-size        = 32M  
 myisam-recover         = FORCE,BACKUP  
 # SAFETY #  
 max-allowed-packet       = 16M  
 max-connect-errors       = 1000000  
 sort_buffer_size = 1073741824  
 myisam_sort_buffer_size = 1073741824  
 # DATA STORAGE #  
 datadir            = /var/lib/mysql/  
 # BINARY LOGGING #  
 #log-bin            = /var/lib/mysql/mysql-bin  
 #expire-logs-days        = 14  
 #sync-binlog          = 1  
 # CACHES AND LIMITS #  
 #tmp-table-size         = 32M  
 #max-heap-table-size      = 32M  
 tmp-table-size         = 1G  
 max-heap-table-size      = 1G  
 query-cache-type        = 0  
 query-cache-size        = 0  
 max-connections        = 500  
 thread-cache-size       = 50  
 open-files-limit        = 65535  
 table-definition-cache     = 4096  
 table-open-cache        = 4096  
 join_buffer_size = 1048576  
 # INNODB #  
 innodb-flush-method      = O_DIRECT  
 innodb-log-files-in-group   = 2  
 innodb-log-file-size      = 256M  
 innodb-flush-log-at-trx-commit = 1  
 innodb-file-per-table     = 1  
 innodb-buffer-pool-size    = 12G  
 # LOGGING #  
 log-error           = /var/lib/mysql/mysql-error.log  
 log-queries-not-using-indexes = 1  
 slow-query-log         = 1  
 slow-query-log-file      = /var/lib/mysql/mysql-slow.log