All pages
Powered by GitBook
Couldn't generate the PDF for 118 pages, generation stopped at 100.
Extend with 50 more pages.
1 of 100

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Administrative Statements

Explore administrative SQL statements for MariaDB Server. This section covers commands for server management, maintenance, and diagnostics, including BINLOG, KILL, SHUTDOWN, and SHOW.

ANALYZE and EXPLAIN Statements

Learn commands for query analysis. This section covers ANALYZE TABLE and EXPLAIN, used to view execution plans and optimize query performance.

BINLOG

Executes binary log events directly using base64-encoded data. Primarily used by the mariadb-binlog utility to re-apply events to the server.

Syntax

BINLOG 'str'

Description

BINLOG is an internal-use statement. It is generated by the program as the printable representation of certain events in files. The 'str' value is a base 64-encoded string that the server decodes to determine the data change indicated by the corresponding event.

This statement requires the privilege.

This statement requires the privilege.

See Also

This page is licensed: GPLv2, originally from

CACHE INDEX

Assigns specific table indices to a named key cache. Optimizes server performance by preloading or dedicating memory to frequently accessed keys.

Syntax

Description

The CACHE INDEX statement assigns table indexes to a specific key cache. It is used only for tables.

A default key cache exists and cannot be destroyed. To create more key caches, the server system variable.

The associations between tables indexes and key caches are lost on server restart. To recreate them automatically, it is necessary to configure caches in a and include some CACHE INDEX (and optionally ) statements in the init file.

Examples

The following statement assigns indexes from the tables t1, t2, and t3 to the key cache named hot_cache:

Implementation (for MyISAM)

Normally CACHE INDEX should not take a long time to execute. Internally it's implemented the following way:

  • Find the right key cache (under LOCK_global_system_variables)

  • Open the table with a TL_READ_NO_INSERT lock.

  • Flush the original key cache for the given file (under key cache lock)

  • Flush the new key cache for the given file (safety)

The only possible long operations are getting the locks for the table and flushing the original key cache, if there were many key blocks for the file in it.

We plan to also add CACHE INDEX for Aria tables if there is a need for this.

This page is licensed: GPLv2, originally from

RESET

Clears internal server buffers, caches, and status variables. Resets state information like the query cache or replication status without a restart.

Syntax

RESET reset_option [, reset_option] ...

Description

The RESET statement is used to clear the state of various server operations. You must have the to executeRESET.

RESET acts as a stronger version of the statement.

The different RESET options are:

Option
Description

This page is licensed: GPLv2, originally from

DESCRIBE

Provides information about a table's columns. Acts as a shortcut for SHOW COLUMNS, displaying field names, types, and other attributes.

Syntax

{DESCRIBE | DESC} tbl_name [col_name | wild]

Description

DESCRIBE provides information about the columns in a table.It is a shortcut for .These statements also display information for .

col_name can be a column name, or a string containing theSQL "%" and "_" wildcard characters toobtain output only for the columns with names matching the string. There is noneed to enclose the string within quotes unless it contains spaces or otherspecial characters.

The description for providesmore information about the output columns.

See Also

This page is licensed: GPLv2, originally from

PURGE BINARY LOGS

Deletes binary log files from the server. Removes logs based on a specific filename or date timestamp to reclaim disk space and manage storage.

Syntax

Description

The PURGE BINARY LOGS

USE [DATABASE]

Selects the default database for the current session. Subsequent queries execute against this database unless explicitly qualified by name.

Syntax

Description

The 'USE db_name'

HELP Command

Displays help information from the server's help tables. Useful for looking up SQL syntax and command descriptions directly from the client.

Syntax

Description

The HELP

CACHE INDEX                      
  tbl_index_list [, tbl_index_list] ...
  IN key_cache_name                    

tbl_index_list:
  tbl_name [[INDEX|KEY] (index_name[, index_name] ...)]

BACKUP Statements

Learn about backup statements for MariaDB Server. This section details SQL statements and utilities for creating consistent database backups, essential for disaster recovery and data protection.

FLUSH Statements

Explore commands to clear internal caches. Learn to use FLUSH to reload privileges, clear the query cache, or close open tables.

Plugin Statements

Manage server plugins. This section covers INSTALL PLUGIN, UNINSTALL PLUGIN, and SHOW PLUGINS for extending server functionality.

Legacy Replication Statements

Category for old replication statements

SET Statements

Assign values to system variables. Learn to use the SET statement to configure GLOBAL and SESSION variables for tuning server behavior.

SETSET CHARACTER SETSET GLOBAL SQL_SLAVE_SKIP_COUNTERSET NAMESSET PASSWORDSET ROLESET SQL_LOG_BINSET STATEMENTSET TRANSACTIONSET Variable

SHOW Statements

View server metadata and status. This section lists SHOW statements for inspecting databases, tables, variables, and performance metrics.

Move the file to the new key cache (under file share lock)

MyISAM
key_buffer_size
configuration file
LOAD INDEX
fill_help_tables.sql
statement deletes all the
files listed in the log index file prior to the specified log file name ordate. BINARY and MASTER are synonyms.Deleted log files also are removed from the list recorded in the index file, sothat the given log file becomes the first in the list.

The datetime expression is in the format 'YYYY-MM-DD hh:mm:ss'.

If a replica is active but has yet to read from a binary log file you attempt to delete, the statement will fail with an error. However, if the replica is not connected and has yet to read from a log file you delete, the file will be deleted, but the replica will be unable to continue replicating once it connects again.

This statement has no effect if the server was not started with the --log-bin option to enable binary logging.

To list the binary log files on the server, use SHOW BINARY LOGS. To see which files they are reading, use SHOW REPLICA STATUS. You can only delete the files that are older than the oldest file that is used by the slaves.

To list the binary log files on the server, use SHOW BINARY LOGS. To see which files they are reading, use SHOW SLAVE STATUS. You can only delete the files that are older than the oldest file that is used by the slaves.

To delete all binary log files, use RESET MASTER.To move to a new log file (for example if you want to remove the current log file), use FLUSH LOGS before you execute PURGE LOGS.

If the expire_logs_days server system variable is not set to 0, the server automatically deletes binary log files after the given number of days. From MariaDB 10.6, the binlog_expire_logs_seconds variable allows more precise control over binlog deletion, and takes precedence if both are non-zero.

Requires the BINLOG ADMIN privilege.

Requires the SUPER privilege.

Examples

See Also

  • Using and Maintaining the Binary Log

  • FLUSH LOGS.

This page is licensed: GPLv2, originally from fill_help_tables.sql

binary log
statement tells MariaDB to use the
db_name
database as the default (current) database for subsequent statements. The database remains the default until the end of the session, or until another
USE
statement is issued:

The DATABASE() function (SCHEMA() is a synonym) returns the default database.

Another way to set the default database is by specifying its name when starting the mariadb command line client:

One cannot use USE to a database one has no privileges to. The reason is thata user with no privileges to a database should not be able to know if a database exists or not.

See Also

  • Identifier Qualifiers

  • USE CATALOG

This page is licensed: GPLv2, originally from fill_help_tables.sql

command can be used in any MariaDB client, such as the
command-line client, to get basic syntax help and a short description for most commands and functions.

If you provide an argument to the HELP command, the mariadb client uses it as a search string to access server-side help. The proper operation of this command requires that the help tables in the mysql database be initialized with help topic information.

If there is no match for the search string, the search fails. Use HELP contents to see a list of the help categories:

If a search string matches multiple items, MariaDB shows a list of matching topics:

Then you can enter a topic as the search string to see the help entry for that topic.

The help is provided with the MariaDB server and makes use of four help tables found in the mysql database: help_relation, help_topic, help_category and help_keyword. These tables are populated by the mariadb-install-db or fill_help_table.sql scripts.

This page is licensed: GPLv2, originally from fill_help_tables.sql

mariadb

SLAVE ["connection_name"] [ALL]

Deletes all relay logs from the slave and reset the replication position in the master binary log.

MASTER

Deletes all old binary logs, makes the binary index file (--log-bin-index) empty and creates a new binary log file. This is useful when you want to reset the master to an initial state. If you want to just delete old, not used binary logs, you should use the PURGE BINARY LOGS command.

QUERY CACHE

Removes all queries from the query cache. See also FLUSH QUERY CACHE.

RELOAD privilege
FLUSH
fill_help_tables.sql
SHOW COLUMNS FROM
views
SHOW COLUMNS
SHOW COLUMNS
INFORMATION_SCHEMA.COLUMNS Table
mysqlshow
fill_help_tables.sql
mariadb-binlog
binary log
BINLOG REPLAY
SUPER
MariaDB replication
fill_help_tables.sql

EXPLAIN ANALYZE

Understand the historical context of EXPLAIN ANALYZE in MariaDB. Learn how this syntax maps to the modern ANALYZE statement for profiling query execution.

Outdated syntax

The syntax for the EXPLAIN ANALYZE feature was changed to ANALYZE statement, available since . See ANALYZE statement.

This page is licensed: CC BY-SA / Gnu FDL

FLUSH QUERY CACHE

Defragment the query cache to optimize memory usage. This command reorganizes the cache to eliminate fragmentation without removing existing cached queries.

Description

You can defragment the query cache to better utilize its memory with the FLUSH QUERY CACHE statement. The statement does not remove any queries from the cache.

The RESET QUERY CACHE statement removes all query results from the query cache. The FLUSH TABLES statement also does this.

This page is licensed: GPLv2, originally from fill_help_tables.sql

Replication Statements

Control replication topologies. Learn statements like CHANGE MASTER TO and START SLAVE to configure primaries and replicas.

The terms master and slave have historically been used in replication, and MariaDB has begun the process of adding primary and replica synonyms. The old terms will continue to be used to maintain backward compatibility - see MDEV-18777 to follow progress on this effort.

CHANGE MASTER TORESET MASTERRESET REPLICASET GLOBAL SQL_SLAVE_SKIP_COUNTERSTART REPLICASTOP REPLICALegacy Replication Statements

RESET MASTER

RESET MASTER [TO #]

Deletes all binary log files listed in the index file, resets the binary log index file to be empty, and creates a new binary log file with a suffix of .000001.

If TO # is given, then the first new binary log file will start from number #.

This statement is for use only when the master is started for the first time and should never be used if any slaves are actively replicating from the binary log.

See Also

  • The statement is intended for use in active replication.

This page is licensed: GPLv2, originally from

RESET SLAVE

Old name for RESET REPLICA

This page is licensed: CC BY-SA / Gnu FDL

SHOW SLAVE HOSTS

Old name for SHOW REPLICA HOSTS

This page is licensed: CC BY-SA / Gnu FDL

SHOW SLAVE STATUS

Old name for SHOW REPLICA STATUS

This page is licensed: CC BY-SA / Gnu FDL

START SLAVE

Old name for START REPLICA

This page is licensed: CC BY-SA / Gnu FDL

STOP SLAVE

Old name for STOP REPLICA

This page is licensed: CC BY-SA / Gnu FDL

About SHOW

Overview of the SHOW statement syntax. Learn how to use patterns and WHERE clauses to filter output from various SHOW statements.

SHOW provides information about various aspects of MariaDB Server. A list of the various SHOW statements is here.

The general syntax is:

SHOW LIKE 'pattern' | WHERE expr

The LIKE and WHERE clauses make sense only for particular SHOW statements, though. See Extended SHOW for what SHOW statements benefit from using those clauses.

If the syntax for a given SHOW statement includes LIKE 'pattern' , 'pattern' is a string that can contain the SQL % and _ wildcard characters. The pattern is useful for restricting statement output to matching values.

This page is licensed: GPLv2, originally from

SHUTDOWN

Stops the MariaDB server process. Allows a client with the SHUTDOWN privilege to cleanly power down the database instance.

Syntax

Description

The SHUTDOWN command shuts the server down.

KILL

Terminates a specific connection or query. Allows administrators to stop runaway threads or disconnect users to free up server resources.

Syntax

Description

Each connection to mariadbd runs in a separate thread. You can see which threads are running with the SHOW PROCESSLIST

ANALYZE FORMAT=JSON

Gain deep insight into query execution with JSON-formatted analysis. This command combines optimizer estimates with actual runtime statistics for precise performance tuning.

ANALYZE FORMAT=JSON is a mix of the and statement features. The ANALYZE FORMAT=JSON $statement will execute $statement, and then print the output of EXPLAIN FORMAT=JSON, amended with data from the query execution.

Basic Execution Data

EXPLAIN FORMAT=JSON

Get comprehensive query plans in JSON format. This output provides detailed optimizer data, including costs and attached conditions, not found in the tabular view.

Synopsis

EXPLAIN FORMAT=JSON is a variant of command that produces output in JSON form. The output always has one row which has only one column titled "JSON". The contents are a JSON representation of the query plan:

Using Buffer UPDATE Algorithm

Understand the 'Using buffer' strategy for UPDATE operations. Learn how MariaDB prevents infinite update loops when modifying indexed columns during a range scan.

This article explains the statement's Using Buffer algorithm.

Consider the following table and query:

Name
Salary

Storage Snapshots and BACKUP STAGE Statements

Combine database commands with storage-level snapshots. Learn the correct sequence of BACKUP STAGE commands to freeze writes safely while taking a disk snapshot.

The statements are a set of statements to make it possible to make an efficient external backup tool. These commands could even be used by tools that perform backups by taking a snapshot of a file system, SAN, or some other kind of storage device.

Generic Backup Process with Storage Snapshots

A tool that backs up MariaDB by taking a snapshot of a file system, SAN, or some other kind of storage device could use each BACKUP STAGE command in the following way:

SET GLOBAL SQL_SLAVE_SKIP_COUNTER

Syntax

Description

This statement skips the next N events from the primary. This is useful for recovering from stops caused by a statement.

SET SQL_LOG_BIN

Enable or disable binary logging for the current session. This statement allows administrators to perform operations without replicating them to replicas.

Syntax

Description

Sets the system variable, which disables or enables for the current connection, if the client has the

SHOW BINARY LOGS

List the binary log files on the server. View the file names and sizes to monitor replication logs and manage disk usage.

Syntax

Description

Lists the files on the server. This statement is used as part of the procedure described in , that shows how to determine which logs can be purged.

SHOW BINLOG EVENTS

Inspect the contents of a binary log file. This statement displays the events within a specific binlog, useful for debugging replication issues.

Syntax

Description

Shows the events in the . If you do not specify log_name

SHOW CHARACTER SET

List available character sets. View the default collation, maximum length, and description for each supported character set.

Syntax

Description

The SHOW CHARACTER SET

SHOW CLIENT_STATISTICS

View statistics on client connections. This statement displays metrics like bytes sent/received and busy time for connected clients.

Syntax

Description

The SHOW CLIENT_STATISTICS

SHOW CONTRIBUTORS

List financial contributors to the MariaDB Foundation. View the names and contributions of companies and individuals supporting the project.

Syntax

Description

The SHOW CONTRIBUTORS

SHOW CREATE DATABASE

View the CREATE DATABASE statement. This statement returns the SQL syntax required to recreate a specific database with its current options.

Syntax

Description

Shows the statement that creates the given database. SHOW CREATE SCHEMA

SHOW CREATE FUNCTION

Retrieve the CREATE FUNCTION statement. This statement shows the exact SQL used to define a stored function, including its body and characteristics.

Syntax

Description

This statement is similar to but for .

SHOW CREATE SERVER

Display the CREATE SERVER statement. This statement shows the configuration details for a defined federated server connection.

Syntax

Description

Shows the statement that created the given server definition.

Example

The SHOW CREATE SERVER statement is not available.

SHOW FUNCTION CODE

Display the internal instruction representation of a stored function. This debug statement shows the low-level opcodes of the routine.

Syntax

Description

SHOW FUNCTION CODE

CACHE INDEX t1, t2, t3 IN hot_cache;
+---------+--------------------+----------+----------+
| Table   | Op                 | Msg_type | Msg_text |
+---------+--------------------+----------+----------+
| test.t1 | assign_to_keycache | status   | OK       |
| test.t2 | assign_to_keycache | status   | OK       |
| test.t3 | assign_to_keycache | status   | OK       |
+---------+--------------------+----------+----------+
PURGE { BINARY | MASTER } LOGS
    { TO 'log_name' | BEFORE datetime_expr }
PURGE BINARY LOGS TO 'mariadb-bin.000063';
PURGE BINARY LOGS BEFORE '2013-04-21';
PURGE BINARY LOGS BEFORE '2013-04-22 09:55:22';
USE db_name
USE db1;
SELECT COUNT(*) FROM mytable;   # selects FROM db1.mytable
USE db2;
SELECT COUNT(*) FROM mytable;   # selects FROM db2.mytable
mariadb db1    # starts the mariadb command-line client with db1 as the current database
HELP search_string
HELP contents
You asked for help about help category: "Contents"
For more information, type 'help <item>', where <item> is one of the following
categories:
   Account Management
   Administration
   Compound Statements
   Data Definition
   Data Manipulation
   Data Types
   Functions
   Functions and Modifiers for Use with GROUP BY
   Geographic Features
   Help Metadata
   Language Structure
   Plugins
   Procedures
   Sequences
   Table Maintenance
   Transactions
   User-Defined Functions
   Utility
HELP drop
Many help items for your request exist.
To make a more specific request, please type 'help <item>',
where <item> is one of the following
topics:
   ALTER TABLE
   DROP DATABASE
   DROP EVENT
   DROP FUNCTION
   DROP FUNCTION UDF
   DROP INDEX
   DROP PACKAGE
   DROP PACKAGE BODY
   DROP PROCEDURE
   DROP ROLE
   DROP SEQUENCE
   DROP SERVER
   DROP TABLE
   DROP TRIGGER
   DROP USER
   DROP VIEW
DESCRIBE city;
+------------+----------+------+-----+---------+----------------+
| Field      | Type     | Null | Key | Default | Extra          |
+------------+----------+------+-----+---------+----------------+
| Id         | int(11)  | NO   | PRI | NULL    | auto_increment |
| Name       | char(35) | YES  |     | NULL    |                |
| Country    | char(3)  | NO   | UNI |         |                |
| District   | char(20) | YES  | MUL |         |                |
| Population | int(11)  | YES  |     | NULL    |                |
+------------+----------+------+-----+---------+----------------+

WAIT FOR ALL REPLICAS / SLAVES

The WAIT FOR ALL REPLICAS statement can be used throughout.

The WAIT FOR ALL SLAVES option was first added in MariaDB 10.4.4.

When a primary server is shutdown and it goes through the normal shutdown process, the primary kills client threads in random order. By default, the primary also considers its binary log dump threads to be regular client threads. As a consequence, the binary log dump threads can be killed while client threads still exist, and this means that data can be written on the primary during a normal shutdown that won't be replicated. This is true even if semi-synchronous replication is being used.

This problem can be solved by shutting down the server with the SHUTDOWN command and by providing the WAIT FOR ALL REPLICAS/WAIT FOR ALL SLAVES option to the command. For example:

When the WAIT FOR ALL REPLICAS option is provided, the server only kills its binary log dump threads after all client threads have been killed, and it only completes the shutdown after the last binary log has been sent to all connected replicas.

See Replication Threads: Binary Log Dump Threads and the Shutdown Process for more information.

Required Permissions

One must have a SHUTDOWN privilege (see GRANT) to use this command. It is the same privilege one needs to use the mariadb-admin shutdown command.

Shutdown for Upgrades

If you are doing a shutdown to migrate to another major version of MariaDB, please ensure that the innodb_fast_shutdown variable is not 2 (fast crash shutdown). The default of this variable is 1.

Example

The following example shows how to create an event which turns off the server at a certain time:

Other Ways to Stop mariadbd

You can use the mariadb-admin shutdown command to take down mariadbd cleanly.

You can also use the system kill command on Unix with signal SIGTERM (15)

You can find the process number of the server process in the file that ends with .pid in your data directory.

The above is identical to mariadb-admin shutdown.

On windows you should use:

See Also

  • mariadb-admin shutdown.

  • InnoDB fast shutdown option

This page is licensed: CC BY-SA / Gnu FDL

statement and kill a thread with the
KILL thread_id
statement.
KILL
allows the optional
CONNECTION
or
QUERY
modifier:
  • KILL CONNECTION is the same as KILL with no modifier: It terminates the connection associated with the given thread or query id.

  • KILL QUERY terminates the statement that the connection thread_id is currently executing, but leaves the connection itself intact.

  • KILL QUERY ID terminates the query by query_id, leaving the connection intact.

If a connection is terminated that has an active transaction, the transaction is rolled back. If only a query is killed, the current transaction stays active. See also idle_transaction_timeout.

If you have the PROCESS privilege, you can see all threads.

If you have the CONNECTION ADMIN privilege, you can kill all threads and statements. Otherwise, you can see and kill only your own threads and statements.

If you have the SUPER privilege, the CONNECTION ADMIN privilege, you can kill all threads and statements. Otherwise, you can see and kill only your own threads and statements.

Killing queries that repair or create indexes on MyISAM and Aria tables may result in corrupted tables. Use the SOFT option to avoid this.

The HARD option (default) kills a statement as soon as possible. If you useSOFT, critical operations that may leave a table in an inconsistent state are not interrupted. Such operations include REPAIR and INDEX creation for MyISAM and Aria tables (REPAIR TABLE, OPTIMIZE TABLE).

KILL ... USER username kills all connections and queries for a given user. USER can be specified in one of the following ways:

  • username (kill without regard to hostname)

  • username@hostname

  • CURRENT_USER or CURRENT_USER()

If you specify a thread id and that thread does not exist, you get the following error:

If you specify a query id that doesn't exist, you get the following error:

However, if you specify a user name, no error is issued for non-connected (or even non-existing) users. To check if the connection/query has been killed, you can use the ROW_COUNT() function.

A client whose connection is killed receives the following error:

To obtain a list of existing sessions, use the SHOW PROCESSLIST statement or query the Information Schema PROCESSLIST table.

You cannot use KILL with the Embedded MariaDB Server library because the embedded server merely runs inside the threads of the host application. It does not create any connection threads of its own.

Note: You can also use mariadb-admin kill thread_id [,thread_id...] to kill connections. To get a list of running queries,use mariadb-admin processlist. See mariadb-admin.

See Also

  • Query limits and timeouts

  • Aborting statements that exceed a certain time to execute

  • idle_transaction_timeout

This page is licensed: GPLv2, originally from fill_help_tables.sql

You can get the following also from tabular
ANALYZE
statement form:
  • r_rows is provided for any node that reads rows. It shows how many rows were read, on average.

  • r_filtered is provided whenever there is a condition that is checked. It shows the percentage of rows left after checking the condition.

Advanced Execution Data

The most important data not available in the regular tabular ANALYZE statement are:

  • r_loops field. This shows how many times the node was executed. Most query plan elements have this field.

  • r_total_time_ms field. It shows how much time in total, in milliseconds, was spent executing this node. If the node has subnodes, their execution time is included.

    • For UPDATE and DELETE statements, top-level query_block.r_total_time_ms does include the time to make row deletions/updates but does NOT include the time to commit the changes.

  • r_buffer_size field. Query plan nodes that make use of buffers report the size of buffer that was used.

InnoDB engine statistics

Starting from MariaDB 10.6.15, , , , MariaDB 10.11.5, , and (MDEV-31577), the following statistics are reported for InnoDB tables:

Only non-zero members are printed.

  • pages_accessed is the total number of buffer pool pages accessed when reading this table.

  • pages_updated is the total number of buffer pool pages that were modified during the execution of the statement.

  • pages_read_count is the number of pages that InnoDB had to read from disk for this table. If the query touches "hot" data in the InnoDB buffer pool, this value will be 0 and not present.

  • pages_prefetch_read_count Number of pages for which read-ahead was initiated. Not all such pages will necessarily be accessed.

  • pages_read_time_ms is the total time spent reading the table.

  • old_rows_read is the number of old row versions that InnoDB had to read. Old row version is the version of the row that is not visible to this transaction.

SHOW ANALYZE FORMAT=JSON

MariaDB starting with

SHOW ANALYZE FORMAT=JSON for <connection_id> extends ANALYZE [FORMAT=JSON] <select> to allow one to analyze a query currently running in another connection.

Data About Individual Query Plan Nodes

  • filesort node reports whether sorting was done with LIMIT n parameter, and how many rows were in the sort result.

  • block-nl-join node has r_loops field, which allows to tell whether Using join buffer was efficient.

  • range-checked-for-each-record reports counters that show the result of the check.

  • expression-cache is used for subqueries, and it reports how many times the cache was used, and what cache hit ratio was.

  • union_result node has r_rows so one can see how many rows were produced after UNION operation and so forth.

Use Cases

See Examples of ANALYZE FORMAT=JSON.

This page is licensed: CC BY-SA / Gnu FDL

EXPLAIN FORMAT=JSON
ANALYZE
Output is different from MySQL

The output of MariaDB's EXPLAIN FORMAT=JSON is different from EXPLAIN FORMAT=JSON in MySQL. The reasons for that are:

  • MySQL's output has deficiencies.

  • The output of MySQL's EXPLAIN FORMAT=JSON is not defined. Even MySQL Workbench has trouble parsing it (see this blog post).

  • MariaDB has query optimizations that MySQL does not have. This means that MariaDB generates query plans that MySQL does not generate.

Output Format

TODO: MariaDB's output format description.

See Also

  • ANALYZE FORMAT=JSON produces output like EXPLAIN FORMAT=JSON, but amended with the data from query execution.

This page is licensed: CC BY-SA / Gnu FDL

EXPLAIN
Suppose the employees table has an index on the salary column, and the optimizer decides to use a range scan on that index.

The optimizer starts a range scan on the salary index. We find the first record Babatunde, 1000. If we do an on-the-fly update, we immediately instruct the storage engine to change this record to be Babatunde, 1000+100=1100.

Then we proceed to search for the next record, and find Jolana, 1050. We instruct the storage engine to update it to be Jolana, 1050+100=1150.

Then we proceed to search for the next record ... and what happens next depends on the storage engine. In some storage engines, data changes are visible immediately, so we will find the Babatunde, 1100 record that we wrote at the first step, modifying it again, giving Babatunde an undeserved raise. Then we will see Babatunde again and again, looping continually.

In order to prevent such situations, the optimizer checks whether the UPDATE statement is going to change key values for the keys it is using. In that case, it will use a different algorithm:

  1. Scan everyone with "salary<2000", remembering the rowids of the rows in a buffer.

  2. Read the buffer and apply the updates.

This way, each row will be updated only once.

The Using buffer EXPLAIN output indicates that the buffer as described above will be used.

This page is licensed: CC BY-SA / Gnu FDL

Babatunde

1000

Jolana

1050

Pankaja

1300

UPDATE employees SET salary = salary+100 WHERE salary < 2000;
UPDATE

First, execute the following:

  • Then, take the snapshot.

  • Then, execute the following:

The above ensures that all non-transactional tables are properly flushed to disk before the snapshot is done. Using BACKUP STAGE commands is also more efficient than using the FLUSH TABLES WITH READ LOCK command as the above set of commands will not block or be blocked by write operations to transactional tables.

Note that when the backup is completed, one should delete all files with the "#sql" prefix, as these are files used by concurrent running ALTER TABLE. Note that InnoDB will on server restart automatically delete any tables with the "#sql" prefix.

This page is licensed: CC BY-SA / Gnu FDL

BACKUP STAGE
BACKUP STAGE START
BACKUP STAGE BLOCK_COMMIT
BACKUP STAGE END

If multi-source replication is used, this statement applies to the default connection. It could be necessary to change the value of the default_master_connection system variable.

Note that, if the event is a transaction, the whole transaction will be skipped. With non-transactional engines, an event is always a single statement.

This statement is valid only when the replica threads are not running. Otherwise, it produces an error.

The statement does not automatically restart the replica threads.

Example

Multi-source replication:

Multiple Replication Domains

sql_slave_skip_counter can't be used to skip transactions on a replica if GTID replication is in use and if gtid_slave_pos contains multiple gtid_domain_id values. In that case, you'll get an error like the following:

In order to skip transactions in cases like this, you will have to manually change gtid_slave_pos.

See Also

  • Selectively Skipping Replication of Binlog Events

This page is licensed: GPLv2, originally from fill_help_tables.sql

replication
SUPER
. The statement is refused with an error if the client does not have that privilege.

Note that setting sql_log_bin=1 has no effect if log_bin variable, which enables global binary logging, is not set.

You cannot set sql_log_bin as a global variable.

You can set sql_log_bin as a global variable. This is considered dangerous, though, as it can damage replication.

This page is licensed: GPLv2, originally from fill_help_tables.sql

sql_log_bin
binary logging
privilege

This statement requires the BINLOG MONITOR privilege.

This statement requires the SUPER privilege and the REPLICATION_CLIENT privilege.

Examples

This page is licensed: GPLv2, originally from fill_help_tables.sql

binary log
PURGE BINARY LOGS
, the first binary log is displayed.

This statement requires the BINLOG MONITOR privilege.

This statement requires the REPLICATION SLAVE privilege.

Example

This page is licensed: GPLv2, originally from fill_help_tables.sql

binary log
statement shows all available
. The LIKE clause, if present on its own, indicates which character set names to match. The WHERE and LIKE clauses can be given to select rows using more general conditions, as discussed in
.

The same information can be queried from the Information Schema CHARACTER_SETS table.

See Setting Character Sets and Collations for details on specifying the character set at the server, database, table and column levels.

Examples

See Also

  • Supported Character Sets and Collations

  • Setting Character Sets and Collations

  • Information Schema CHARACTER_SETS

This page is licensed: GPLv2, originally from fill_help_tables.sql

character sets
Extended SHOW
statement has effectively been replaced by the generic
statement. The
table holds statistics about client connections.

The SHOW CLIENT_STATISTICS statement is part of the User Statistics feature. The information_schema.CLIENT_STATISTICS table holds statistics about client connections.

The userstat system variable must be set to 1 to activate this feature. See the User Statistics and information_schema.CLIENT_STATISTICS articles for more information.

Example

This page is licensed: CC BY-SA / Gnu FDL

SHOW TABLE STATISTICS
information_schema.CLIENT_STATISTICS
statement displays information about the companies and people who financially contribute to MariaDB. For each contributor, it displays
Name
,
Location
, and
Comment
values. All columns are encoded as
latin1
.

It displays all members and sponsors of the MariaDB Foundation as well as other financial contributors.

Example

See Also

  • .

  • SHOW AUTHORS list the authors of MariaDB (including documentation, QA etc).

  • MariaDB Foundation page on contributing financially.

This page is licensed: GPLv2, originally from fill_help_tables.sql

is a synonym for
SHOW CREATE DATABASE
.
SHOW CREATE DATABASE
quotes database names according to the value of the
server system variable.

Examples

With sql_quote_show_create turned off, the output looks slightly differently:

See Also

  • CREATE DATABASE

  • ALTER DATABASE

  • Character Sets and Collations

This page is licensed: GPLv2, originally from fill_help_tables.sql

CREATE DATABASE
sql_quote_show_create

SHOW CREATE FUNCTION quotes identifiers, according to the value of the sql_quote_show_create system variable.

SHOW CREATE FUNCTION quotes identifiers, according to the value of the sql_quote_show_create system variable. However, the output of this statement is unreliably affected by the sql_quote_show_create system variable.

Example

See Also

  • Stored Functions

  • CREATE FUNCTION

This page is licensed: GPLv2, originally from fill_help_tables.sql

SHOW CREATE PROCEDURE
stored functions
See Also
  • CREATE SERVER

This page is licensed: CC BY-SA / Gnu FDL

CREATE SERVER
SHOW CREATE SERVER server_name
SHOW CREATE SERVER srv1\G
*************************** 1. row ***************************
       Server: srv1
Create Server: CREATE SERVER `srv1` FOREIGN DATA WRAPPER mysql 
  OPTIONS (HOST '172.30.0.58', DATABASE 'db1', USER 'maxscale', PASSWORD 'password');
shows a representation of the internal implementation of the stored function.

It is similar to SHOW PROCEDURE CODE but for stored functions.

This page is licensed: GPLv2, originally from fill_help_tables.sql

SHOW FUNCTION CODE func_name
PURGE BINARY LOGS
fill_help_tables.sql
fill_help_tables.sql

ANALYZE FORMAT=JSON Examples

Review practical examples of ANALYZE FORMAT=JSON output. Learn to identify performance bottlenecks by comparing estimated costs against actual execution metrics.

Example #1

Customers who have ordered more than 1M goods.

ANALYZE FORMAT=JSON
SELECT COUNT(*)
FROM customer
WHERE
  (SELECT SUM(o_totalprice) FROM orders WHERE o_custkey=c_custkey) > 1000*1000;

The query takes 40 seconds over cold cache.

ANALYZE shows that 39.208 seconds were spent in the subquery, which was executed 150K times (for every row of outer table).

This page is licensed: CC BY-SA / Gnu FDL

UNINSTALL PLUGIN

Remove a specific plugin from the server. This statement unloads the plugin code and deletes its entry from the mysql.plugin table to prevent reloading.

Syntax

Description

This statement removes a single installed plugin. To uninstall the whole library which contains the plugin, use UNINSTALL SONAME. You cannot uninstall a plugin if any table that uses it is open.

plugin_name must be the name of some plugin that is listedin the table. The server executes the plugin's deinitializationfunction and removes the row for the plugin from the mysql.plugintable, so that subsequent server restarts will not load and initializethe plugin. UNINSTALL PLUGIN does not remove the plugin'sshared library file.

To use UNINSTALL PLUGIN, you must have the privilege for the table.

IF EXISTS

If the IF EXISTS clause is used, MariaDB will return a note instead of an error if the plugin does not exist. See .

Examples

See Also

This page is licensed: GPLv2, originally from

SET CHARACTER SET

Map strings to a specific character set. This command updates the character set for the client, results, and connection to ensure correct data encoding.

Syntax

SET {CHARACTER SET | CHARSET}
    {charset_name | DEFAULT}

Description

Sets the character_set_client and character_set_results session system variables to the specified character set and collation_connection to the value of , which implicitly sets to the value of .

This maps all strings sent between the current client and the server with the given mapping.

Example

See Also

This page is licensed: CC BY-SA / Gnu FDL

SHOW CREATE EVENT

Get the SQL statement to recreate a scheduled event. This statement displays the complete syntax used to define a specific event.

Syntax

Description

This statement displays the CREATE EVENT statement that creates a given event, as well as the SQL_MODE that was used when the trigger was created, and the character set used by the connection. To find out which events are present, use .

SHOW CREATE EVENT quotes identifiers according to the value of the system variable.

SHOW CREATE EVENT quotes identifiers according to the value of the system variable. Note, however, that the output of this statement is unreliably affected by the system variable.

The table provides similar, but more complete, information.

Examples

See also

This page is licensed: GPLv2, originally from

SHOW MASTER STATUS

View the current status of the primary server's binary log. This statement returns the current log file name and position for replication synchronization.

Syntax

SHOW [MASTER | BINLOG] STATUS
SHOW MASTER STATUS

Description

Provides status information about the files of the primary.

This statement requires the privilege.

This statement requires the privilege and the privilege.

To see information about the current in the binary log, use the variable.

Example

See Also

This page is licensed: GPLv2, originally from

SHOW LOCALES

List available error message locales. View the language IDs, names, and descriptions for supported localization settings.

Syntax

SHOW LOCALES

Description

SHOW LOCALES was introduced as part of the .

SHOW LOCALES is used to return information as part of the plugin. It requires this plugin to be installed to work.

While the table has 8 columns, the SHOW LOCALES statement will only display 4 of them:

Example

This page is licensed: CC BY-SA / Gnu FDL

SET Variable

Assign values to user-defined variables. This guide explains how to store data in session-specific variables for reuse in subsequent SQL statements.

Syntax

SET var_name = expr [, var_name = expr] ...

Description

The SET statement in is an extended version of the general statement. Referenced variables may be ones declared inside a stored program, global system variables, or user-defined variables.

The SET statement in stored programs is implemented as part of the pre-existing syntax. This allows an extended syntax of SET a=x, b=y, ... where different variable types (locally declared variables, global and session server variables, user-defined variables) can be mixed. This also allows combinations of local variables and some options that make sense only for system variables; in that case, the options are recognized but ignored.

SET can be used with both and .

When setting several variables using the columns returned by a query, should be preferred.

To set many variables to the same value, the function can be used.

Below is an example of how a user-defined variable may be set:

See Also

This page is licensed: GPLv2, originally from

SHOW INNODB STATUS (removed)

Documentation for the deprecated SHOW INNODB STATUS statement. This statement was removed in favor of SHOW ENGINE INNODB STATUS.

Syntax

SHOW INNODB STATUS

Description

This is a deprecated synonym for SHOW ENGINE INNODB STATUS. It was removed in MariaDB and MySQL 5.5.

This page is licensed: GPLv2, originally from

SHOW PLUGINS SONAME

List plugins and their library files. View information about installed plugins and their associated shared object names.

Syntax

SHOW PLUGINS SONAME { library | LIKE 'pattern' | WHERE expr };

Description

SHOW PLUGINS SONAME displays information about compiled-in and all server plugins in the directory, including plugins that haven't been installed.

Examples

There is also a corresponding table, called , which contains more complete information.

This page is licensed: CC BY-SA / Gnu FDL

BACKUP LOCK

Protect table files during backups. This command blocks DDL operations like ALTER TABLE while allowing read/write activity, ensuring file consistency for backup tools.

BACKUP LOCK blocks a table from DDL statements. This is mainly intended to be used by tools like that need to ensure there are no DDL statements on a table while the table files are opened. For example, for an Aria table that stores data in 3 files with extensions .frm, .MAI and .MAD. Normal read/write operations can continue as normal.

INSTALL SONAME

Load all plugins contained within a shared library file. This statement automatically discovers and installs every valid plugin found in the specified library.

Syntax

Description

This statement is a variant of . It installs all

UNINSTALL SONAME

Uninstall all plugins loaded from a specific library. This statement removes every plugin associated with the library file and unloads the library itself.

Syntax

Description

This statement is a variant of statement, that removes all belonging to a specified

RESET REPLICA

The terms master and slave have historically been used in replication, and MariaDB has begun the process of adding primary and replica synonyms. The old terms will continue to be used to maintain backward compatibility - see to follow progress on this effort.

Syntax

SET STATEMENT

Set a system variable for the duration of a single query. This statement allows temporary configuration changes that apply only to the immediate statement.

Syntax

var is a system variable (list of allowed variables is provided below), and value is a constant literal.

SHOW CREATE USER

View the CREATE USER statement. This statement returns the SQL required to recreate a user account with its authentication details.

Syntax

Description

Shows the statement that creates the given user. The statement requires the privilege for the

SHOW CREATE TRIGGER

Retrieve the CREATE TRIGGER statement. This statement displays the SQL syntax defining a specific trigger and its timing events.

Syntax

Description

This statement shows a statement that creates the given trigger, as well as the that was used when the trigger has been created and the character set used by the connection.

SHOW ERRORS

Display errors from the last executed statement. View error codes, messages, and types for recent failures.

Syntax

Description

This statement is similar to , except that instead of displaying errors, warnings, and notes, it displays only errors.

SHOW CREATE VIEW

Display the CREATE VIEW statement. This statement shows the SQL query that defines a specific view structure.

Syntax

Description

This statement shows a statement that creates the given , as well as the character set used by the connection when the view was created. This statement also works with views.

SHOW DATABASES

List databases on the MariaDB server. View the names of all databases available to the current user.

Syntax

Description

SHOW DATABASES lists the databases on the MariaDB server host.

SHOW EVENTS

List scheduled events. View metadata such as the event name, schedule, status, and timing for events in a database.

Syntax

Description

Shows information about Event Manager (created with ). Requires the privilege. Without any arguments,

SHOW OPEN TABLES

List currently open tables. View the database, table name, and lock status for tables in the table cache.

Syntax

Description

SHOW OPEN TABLES lists the non-

SHOW FUNCTION STATUS

List stored functions and their characteristics. View metadata like the database, name, type, and creator of stored functions.

Syntax

Description

This statement is similar to but for .

SHOW PACKAGE STATUS

List stored packages. View metadata about the interface part of Oracle-compatible packages in the database.

Syntax

Description

The SHOW PACKAGE STATUS

SHOW CREATE PACKAGE

View the CREATE PACKAGE statement. This statement returns the interface definition of a stored package in MariaDB.

Syntax

Description

The SHOW CREATE PACKAGE

SHUTDOWN [WAIT FOR ALL { SLAVES | REPLICAS } ]
SHUTDOWN WAIT FOR ALL REPLICAS;
CREATE EVENT `test`.`shutd`
    ON SCHEDULE
        EVERY 1 DAY
        STARTS '2014-01-01 20:00:00'
    COMMENT 'Shutdown Maria when the office is closed'
DO BEGIN
    SHUTDOWN;
END;
kill -SIGTERM pid-of-mariadbd-process
NET STOP MariaDB
KILL [HARD | SOFT] { {CONNECTION|QUERY} thread_id | QUERY ID query_id | USER user_name }
ERROR 1094 (HY000): Unknown thread id: <thread_id>
ERROR 1957 (HY000): Unknown query id: <query_id>
ERROR 1317 (70100): Query execution was interrupted
"r_engine_stats": {
        "pages_accessed":  integer,
        "pages_updated": integer,
        "pages_read_count": integer,
        "pages_prefetch_read_count": integer,
        "pages_read_time_ms": double,
        "old_rows_read": integer
      }
EXPLAIN FORMAT=JSON SELECT * FROM t1 WHERE col1=1\G
*************************** 1. row ***************************
EXPLAIN: {
  "query_block": {
    "select_id": 1,
    "table": {
      "table_name": "t1",
      "access_type": "ALL",
      "rows": 1000,
      "filtered": 100,
      "attached_condition": "(t1.col1 = 1)"
    }
  }
}
SET GLOBAL sql_slave_skip_counter = N
SHOW SLAVE STATUS \G
...
SET GLOBAL sql_slave_skip_counter = 1;
START SLAVE;
SET @@default_master_connection = 'master_01';
SET GLOBAL SQL_SLAVE_SKIP_COUNTER = 1;
START SLAVE;
ERROR 1966 (HY000): When using parallel replication and GTID with multiple 
 replication domains, @@sql_slave_skip_counter can not be used. Instead, 
 setting @@gtid_slave_pos explicitly can be  used to skip to after a given GTID 
 position.
SET [SESSION] sql_log_bin = {0|1}
SHOW BINARY LOGS
SHOW MASTER LOGS
SHOW BINARY LOGS;
+--------------------+-----------+
| Log_name           | File_size |
+--------------------+-----------+
| mariadb-bin.000001 |     19039 |
| mariadb-bin.000002 |    717389 |
| mariadb-bin.000003 |       300 |
| mariadb-bin.000004 |       333 |
| mariadb-bin.000005 |       899 |
| mariadb-bin.000006 |       125 |
| mariadb-bin.000007 |     18907 |
| mariadb-bin.000008 |     19530 |
| mariadb-bin.000009 |       151 |
| mariadb-bin.000010 |       151 |
| mariadb-bin.000011 |       125 |
| mariadb-bin.000012 |       151 |
| mariadb-bin.000013 |       151 |
| mariadb-bin.000014 |       125 |
| mariadb-bin.000015 |       151 |
| mariadb-bin.000016 |       314 |
+--------------------+-----------+
SHOW BINLOG EVENTS
   [IN 'log_name'] [FROM pos] [LIMIT [offset,] row_count]
SHOW BINLOG EVENTS IN 'mysql_sandbox10019-bin.000002';
+-------------------------------+-----+-------------------+-----------+-------------+------------------------------------------------+
| Log_name                      | Pos | Event_type        | Server_id | End_log_pos | Info                                           |
+-------------------------------+-----+-------------------+-----------+-------------+------------------------------------------------+
| mysql_sandbox10019-bin.000002 |   4 | Format_desc       |         1 |         248 | Server ver: 10.0.19-MariaDB-log, Binlog ver: 4 |
| mysql_sandbox10019-bin.000002 | 248 | Gtid_list         |         1 |         273 | []                                             |
| mysql_sandbox10019-bin.000002 | 273 | Binlog_checkpoint |         1 |         325 | mysql_sandbox10019-bin.000002                  |
| mysql_sandbox10019-bin.000002 | 325 | Gtid              |         1 |         363 | GTID 0-1-1                                     |
| mysql_sandbox10019-bin.000002 | 363 | Query             |         1 |         446 | CREATE DATABASE blog                           |
| mysql_sandbox10019-bin.000002 | 446 | Gtid              |         1 |         484 | GTID 0-1-2                                     |
| mysql_sandbox10019-bin.000002 | 484 | Query             |         1 |         571 | use `blog`; CREATE TABLE bb (id INT)           |
+-------------------------------+-----+-------------------+-----------+-------------+------------------------------------------------+
SHOW CHARACTER SET
    [LIKE 'pattern' | WHERE expr]
SHOW CHARACTER SET LIKE 'latin%';
+---------+-----------------------------+-------------------+--------+
| Charset | Description                 | Default collation | Maxlen |
+---------+-----------------------------+-------------------+--------+
| latin1  | cp1252 West European        | latin1_swedish_ci |      1 |
| latin2  | ISO 8859-2 Central European | latin2_general_ci |      1 |
| latin5  | ISO 8859-9 Turkish          | latin5_turkish_ci |      1 |
| latin7  | ISO 8859-13 Baltic          | latin7_general_ci |      1 |
+---------+-----------------------------+-------------------+--------+
SHOW CHARACTER SET WHERE Maxlen LIKE '2';
+---------+---------------------------+-------------------+--------+
| Charset | Description               | Default collation | Maxlen |
+---------+---------------------------+-------------------+--------+
| big5    | Big5 Traditional Chinese  | big5_chinese_ci   |      2 |
| sjis    | Shift-JIS Japanese        | sjis_japanese_ci  |      2 |
| euckr   | EUC-KR Korean             | euckr_korean_ci   |      2 |
| gb2312  | GB2312 Simplified Chinese | gb2312_chinese_ci |      2 |
| gbk     | GBK Simplified Chinese    | gbk_chinese_ci    |      2 |
| ucs2    | UCS-2 Unicode             | ucs2_general_ci   |      2 |
| cp932   | SJIS for Windows Japanese | cp932_japanese_ci |      2 |
+---------+---------------------------+-------------------+--------+
SHOW CLIENT_STATISTICS
SHOW CLIENT_STATISTICS\G
*************************** 1. row ***************************
                Client: localhost
     Total_connections: 35
Concurrent_connections: 0
        Connected_time: 708
             Busy_time: 2.5557979999999985
              Cpu_time: 0.04123740000000002
        Bytes_received: 3883
            Bytes_sent: 21595
  Binlog_bytes_written: 0
             Rows_read: 18
             Rows_sent: 115
          Rows_deleted: 0
         Rows_inserted: 0
          Rows_updated: 0
       Select_commands: 70
       Update_commands: 0
        Other_commands: 0
   Commit_transactions: 1
 Rollback_transactions: 0
    Denied_connections: 0
      Lost_connections: 0
         Access_denied: 0
         Empty_queries: 35
SHOW CONTRIBUTORS
SHOW CONTRIBUTORS;
+---------------------+-------------------------------+-------------------------------------------------------------+
| Name                | Location                      | Comment                                                     |
+---------------------+-------------------------------+-------------------------------------------------------------+
| Alibaba Cloud       | https://www.alibabacloud.com/ | Platinum Sponsor of the MariaDB Foundation                  |
| Tencent Cloud       | https://cloud.tencent.com     | Platinum Sponsor of the MariaDB Foundation                  |
| Microsoft           | https://microsoft.com/        | Platinum Sponsor of the MariaDB Foundation                  |
| MariaDB Corporation | https://mariadb.com           | Founding member, Platinum Sponsor of the MariaDB Foundation |
| ServiceNow          | https://servicenow.com        | Platinum Sponsor of the MariaDB Foundation                  |
| Intel               | https://www.intel.com         | Platinum Sponsor of the MariaDB Foundation                  |
| SIT                 | https://sit.org               | Platinum Sponsor of the MariaDB Foundation                  |
| Visma               | https://visma.com             | Gold Sponsor of the MariaDB Foundation                      |
| DBS                 | https://dbs.com               | Gold Sponsor of the MariaDB Foundation                      |
| IBM                 | https://www.ibm.com           | Gold Sponsor of the MariaDB Foundation                      |
| Automattic          | https://automattic.com        | Silver Sponsor of the MariaDB Foundation                    |
| Percona             | https://www.percona.com/      | Sponsor of the MariaDB Foundation                           |
| Galera Cluster      | https://galeracluster.com     | Sponsor of the MariaDB Foundation                           |
| Google              | USA                           | Sponsoring encryption, parallel replication and GTID        |
| Facebook            | USA                           | Sponsoring non-blocking API, LIMIT ROWS EXAMINED etc        |
| Ronald Bradford     | Brisbane, Australia           | EFF contribution for UC2006 Auction                         |
| Sheeri Kritzer      | Boston, Mass. USA             | EFF contribution for UC2006 Auction                         |
| Mark Shuttleworth   | London, UK.                   | EFF contribution for UC2006 Auction                         |
+---------------------+-------------------------------+-------------------------------------------------------------+
SHOW CREATE {DATABASE | SCHEMA} db_name
SHOW CREATE DATABASE test;
+----------+-----------------------------------------------------------------+
| Database | Create Database                                                 |
+----------+-----------------------------------------------------------------+
| test     | CREATE DATABASE `test` /*!40100 DEFAULT CHARACTER SET latin1 */ |
+----------+-----------------------------------------------------------------+

SHOW CREATE SCHEMA test;
+----------+-----------------------------------------------------------------+
| Database | Create Database                                                 |
+----------+-----------------------------------------------------------------+
| test     | CREATE DATABASE `test` /*!40100 DEFAULT CHARACTER SET latin1 */ |
+----------+-----------------------------------------------------------------+
SHOW CREATE DATABASE test;
+----------+---------------------------------------------------------------+
| Database | Create Database                                               |
+----------+---------------------------------------------------------------+
| test     | CREATE DATABASE test /*!40100 DEFAULT CHARACTER SET latin1 */ |
+----------+---------------------------------------------------------------+
SHOW CREATE FUNCTION func_name
SHOW CREATE FUNCTION VatCents\G
*************************** 1. row ***************************
            Function: VatCents
            sql_mode: 
     Create Function: CREATE DEFINER=`root`@`localhost` FUNCTION `VatCents`(price DECIMAL(10,2)) RETURNS int(11)
    DETERMINISTIC
BEGIN
 DECLARE x INT;
 SET x = price * 114;
 RETURN x;
END
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: latin1_swedish_ci
EXPLAIN: {
  "query_block": {
    "select_id": 1,
    "r_loops": 1,
    "r_total_time_ms": 39872,
    "table": {
      "table_name": "customer",
      "access_type": "index",
      "key": "i_c_nationkey",
      "key_length": "5",
      "used_key_parts": ["c_nationkey"],
      "r_loops": 1,
      "rows": 150303,
      "r_rows": 150000,
      "r_total_time_ms": 270.3,
      "filtered": 100,
      "r_filtered": 60.691,
      "attached_condition": "((subquery#2) > <cache>((1000 * 1000)))",
      "using_index": true
    },
    "subqueries": [
      {
        "query_block": {
          "select_id": 2,
          "r_loops": 150000,
          "r_total_time_ms": 39531,
          "table": {
            "table_name": "orders",
            "access_type": "ref",
            "possible_keys": ["i_o_custkey"],
            "key": "i_o_custkey",
            "key_length": "5",
            "used_key_parts": ["o_custkey"],
            "ref": ["dbt3sf1.customer.c_custkey"],
            "r_loops": 150000,
            "rows": 7,
            "r_rows": 10,
            "r_total_time_ms": 39208,
            "filtered": 100,
            "r_filtered": 100
          }
        }
      }
    ]
  }
}
UNINSTALL PLUGIN [IF EXISTS] plugin_name
SHOW CREATE EVENT event_name
fill_help_tables.sql
mysql.plugin
DELETE
mysql.plugin
SHOW WARNINGS
Plugin Overview
mysql_plugin
INSTALL PLUGIN
List of Plugins
fill_help_tables.sql
collation_database
character_set_connection
character_set_database
Setting Character Sets and Collations
SET NAMES
SHOW EVENTS
sql_quote_show_create
sql_quote_show_create
sql_quote_show_create
information_schema.EVENTS
Events Overview
CREATE EVENT
ALTER EVENT
DROP EVENT
fill_help_tables.sql
binary log
BINLOG MONITOR
SUPER
REPLICATION_CLIENT
GTIDs
gtid_binlog_pos
MariaDB replication
Using and Maintaining the Binary Log
The gtid_binlog_pos variable
fill_help_tables.sql
SHOW LOCALES;
+-----+-------+-------------------------------------+------------------------+
| Id  | Name  | Description                         | Error_Message_Language |
+-----+-------+-------------------------------------+------------------------+
|   0 | en_US | English - United States             | english                |
|   1 | en_GB | English - United Kingdom            | english                |
|   2 | ja_JP | Japanese - Japan                    | japanese               |
|   3 | sv_SE | Swedish - Sweden                    | swedish                |
...
Information Schema plugin extension
locales
Locales
information_schema.LOCALES
stored programs
SET
SET
local variables
user-defined variables
SELECT INTO
LAST_VALUE( )
SET
SET STATEMENT
DECLARE Variable
fill_help_tables.sql
SHOW PLUGINS SONAME 'ha_example.so';
+----------+---------------+----------------+---------------+---------+
| Name     | Status        | Type           | Library       | License |
+----------+---------------+----------------+---------------+---------+
| EXAMPLE  | NOT INSTALLED | STORAGE ENGINE | ha_example.so | GPL     |
| UNUSABLE | NOT INSTALLED | DAEMON         | ha_example.so | GPL     |
+----------+---------------+----------------+---------------+---------+
plugin_dir
information_schema
ALL_PLUGINS
Syntax

To lock a table:

To unlock a table:

Usage in a Backup Tool

This ensures that all files are from the same generation, that is created at the same time by the MariaDB server. This works, because the open files will point to the original table files which will not be affected if there is any ALTER TABLE while copying the files.

Privileges

BACKUP LOCK requires the database LOCK TABLES privileges.

BACKUP LOCK requires the RELOAD privilege.

BACKUP LOCK requires the RELOAD privilege.

Notes

  • The idea is that the BACKUP LOCK should be held for as short a time as possible by the backup tool. The time to take an uncontested lock is very short! One can easily do 50,000 locks/unlocks per second on low end hardware.

  • One should use different connections for BACKUP STAGE commands and BACKUP LOCK.

Implementation

  • Internally, BACKUP LOCK is implemented by taking an MDLSHARED_HIGH_PRIO MDL lock on the table object, which protects the table from any DDL operations.

See Also

  • BACKUP STAGE

  • MDEV-17309 - BACKUP LOCK: DDL locking of tables during backup

This page is licensed: CC BY-SA / Gnu FDL

mariadb-backup
Description

SET STATEMENT var1=value1 FOR stmt

is roughly equivalent to

The server parses the whole statement before executing it, so any variables set in this fashion that affect the parser may not have the expected effect. Examples include the charset variables, sql_mode=ansi_quotes, etc.

Examples

One can limit statement execution time max_statement_time:

One can switch on/off individual optimizations:

It is possible to enable MRR/BKA for a query:

Note that it makes no sense to try to set a session variable inside a SET STATEMENT:

For the above, after setting sort_buffer_size to 200000 it will be reset to its original state (the state before the SET STATEMENT started) after the statement execution.

Limitations

There are a number of variables that cannot be set on per-query basis. These include:

  • autocommit

  • character_set_client

  • character_set_connection

  • character_set_filesystem

  • collation_connection

  • default_master_connection

  • debug_sync

  • interactive_timeout

  • gtid_domain_id

  • last_insert_id

  • log_slow_filter

  • log_slow_rate_limit

  • log_slow_verbosity

  • long_query_time

  • min_examined_row_limit

  • profiling

  • profiling_history_size

  • query_cache_type

  • rand_seed1

  • rand_seed2

  • skip_replication

  • slow_query_log

  • sql_log_off

  • tx_isolation

  • wait_timeout

Source

  • The feature was originally implemented as a Google Summer of Code 2009 project by Joseph Lukas.

  • Percona Server 5.6 included it as Per-query variable statement

  • MariaDB ported the patch and fixed many bugs. The task in MariaDB Jira is MDEV-5231.

This page is licensed: CC BY-SA / Gnu FDL

database, except for the current user. The
statement for the current user is shown where no user is specified.

SHOW CREATE USER quotes identifiers according to the value of the sql_quote_show_create system variable.

Examples

User Password Expiry:

See Also

  • CREATE USER

  • ALTER USER

  • SHOW GRANTS shows the GRANTS/PRIVILEGES for a user.

  • SHOW PRIVILEGES shows the privileges supported by MariaDB.

This page is licensed: CC BY-SA / Gnu FDL

CREATE USER
SELECT
mysql
CREATE USER
The LIMIT clause has the same syntax as for the SELECT statement.

The SHOW COUNT(*) ERRORS statement displays the number of errors. You can also retrieve this number from the error_count variable.

The value of error_count might be greater than the number of messages displayed by SHOW WARNINGS if the max_error_count system variable is set so low that not all messages are stored.

For a list of MariaDB error codes, see MariaDB Error Codes.

Examples

This page is licensed: GPLv2, originally from fill_help_tables.sql

SHOW WARNINGS

SHOW CREATE VIEW quotes table, column and stored function names according to the value of the sql_quote_show_create server system variable.

Examples

With sql_quote_show_create off:

Grants

To be able to see a view, you need to have the SHOW VIEW and the SELECT privilege on the view:

See Also

  • Grant privileges to tables, views etc

This page is licensed: GPLv2, originally from fill_help_tables.sql

CREATE VIEW
view
SHOW EVENTS
lists all of the events in the current schema:

To see the event action, use SHOW CREATE EVENT instead, or look at the information_schema.EVENTS table.

To see events for a specific schema, use the FROM clause. For example, to see events for the test schema, use the following statement:

The LIKE clause, if present, indicates which event names to match. The WHERE clause can be given to select rows using more general conditions, as discussed in Extended Show.

This page is licensed: GPLv2, originally from fill_help_tables.sql

SHOW EVENTS [{FROM | IN} schema_name]
    [LIKE 'pattern' | WHERE expr]
events
CREATE EVENT
EVENT
The LIKE clause, if present on its own, indicates which function names to match.

The WHERE and LIKE clauses can be given to select rows using more general conditions, as discussed in Extended SHOW.

The information_schema.ROUTINES table contains more detailed information.

Examples

Showing all stored functions:

Stored functions whose name starts with 'V':

Stored functions with a security type of 'DEFINER':

This page is licensed: GPLv2, originally from fill_help_tables.sql

SHOW FUNCTION STATUS
    [LIKE 'pattern' | WHERE expr]
SHOW PROCEDURE STATUS
stored functions
UNINSTALL PLUGIN example;
UNINSTALL PLUGIN IF EXISTS example;
Query OK, 0 rows affected (0.099 sec)

UNINSTALL PLUGIN IF EXISTS example;
Query OK, 0 rows affected, 1 warning (0.000 sec)

SHOW WARNINGS;
+-------+------+-------------------------------+
| Level | Code | Message                       |
+-------+------+-------------------------------+
| Note  | 1305 | PLUGIN example does not exist |
+-------+------+-------------------------------+
SHOW VARIABLES LIKE 'character_set\_%';
+--------------------------+--------+
| Variable_name            | Value  |
+--------------------------+--------+
| character_set_client     | utf8   |
| character_set_connection | utf8   |
| character_set_database   | latin1 |
| character_set_filesystem | binary |
| character_set_results    | utf8   |
| character_set_server     | latin1 |
| character_set_system     | utf8   |
+--------------------------+--------+

SHOW VARIABLES LIKE 'collation%';
+----------------------+-------------------+
| Variable_name        | Value             |
+----------------------+-------------------+
| collation_connection | utf8_general_ci   |
| collation_database   | latin1_swedish_ci |
| collation_server     | latin1_swedish_ci |
+----------------------+-------------------+

SET CHARACTER SET utf8mb4;

SHOW VARIABLES LIKE 'character_set\_%';
+--------------------------+---------+
| Variable_name            | Value   |
+--------------------------+---------+
| character_set_client     | utf8mb4 |
| character_set_connection | latin1  |
| character_set_database   | latin1  |
| character_set_filesystem | binary  |
| character_set_results    | utf8mb4 |
| character_set_server     | latin1  |
| character_set_system     | utf8    |
+--------------------------+---------+

SHOW VARIABLES LIKE 'collation%';
+----------------------+-------------------+
| Variable_name        | Value             |
+----------------------+-------------------+
| collation_connection | latin1_swedish_ci |
| collation_database   | latin1_swedish_ci |
| collation_server     | latin1_swedish_ci |
+----------------------+-------------------+
SHOW CREATE EVENT test.e_daily\G
*************************** 1. row ***************************
               Event: e_daily
            sql_mode: 
           time_zone: SYSTEM
        Create Event: CREATE EVENT `e_daily`
                        ON SCHEDULE EVERY 1 DAY
                        STARTS CURRENT_TIMESTAMP + INTERVAL 6 HOUR
                        ON COMPLETION NOT PRESERVE
                        ENABLE
                        COMMENT 'Saves total number of sessions then
                                clears the table each day'
                        DO BEGIN
                          INSERT INTO site_activity.totals (time, total)
                            SELECT CURRENT_TIMESTAMP, COUNT(*) 
                            FROM site_activity.sessions;
                          DELETE FROM site_activity.sessions;
                        END
character_set_client: latin1
collation_connection: latin1_swedish_ci
  Database Collation: latin1_swedish_ci
SHOW BINLOG STATUS;
+--------------------+----------+--------------+------------------+
| File               | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+--------------------+----------+--------------+------------------+
| mariadb-bin.000016 |      475 |              |                  |
+--------------------+----------+--------------+------------------+
SELECT @@global.gtid_binlog_pos;
+--------------------------+
| @@global.gtid_binlog_pos |
+--------------------------+
| 0-1-2                    |
+--------------------------+
SET @x = 1;
BACKUP LOCK table_name
BACKUP UNLOCK
BACKUP LOCK [database.]table_name;
 - Open all files related to a table (for example, t.frm, t.MAI and t.MYD)
BACKUP UNLOCK;
- Copy data
- Close files
SET STATEMENT var1=value1 [, var2=value2, ...] 
  FOR <statement>
SET @save_value=@@var1;
SET SESSION var1=value1;
stmt;
SET SESSION var1=@save_value;
SET STATEMENT max_statement_time=1000 FOR SELECT ... ;
SET STATEMENT optimizer_switch='materialization=off' FOR SELECT ....;
SET STATEMENT  join_cache_level=6, optimizer_switch='mrr=on'  FOR SELECT ...
#USELESS STATEMENT
SET STATEMENT sort_buffer_size = 100000 FOR SET SESSION sort_buffer_size = 200000;
SHOW CREATE USER [user-name]
CREATE USER foo4@test require cipher 'text' 
  issuer 'foo_issuer' subject 'foo_subject';

SHOW CREATE USER foo4@test\G
*************************** 1. row ***************************
CREATE USER 'foo4'@'test' 
  REQUIRE ISSUER 'foo_issuer' 
  SUBJECT 'foo_subject' 
  CIPHER 'text'
CREATE USER 'monty'@'localhost' PASSWORD EXPIRE INTERVAL 120 DAY;

SHOW CREATE USER 'monty'@'localhost';
+------------------------------------------------------------------+
| CREATE USER for monty@localhost                                  |
+------------------------------------------------------------------+
| CREATE USER 'monty'@'localhost' PASSWORD EXPIRE INTERVAL 120 DAY |
+------------------------------------------------------------------+
SHOW ERRORS [LIMIT [offset,] row_count]
SHOW ERRORS [LIMIT row_count OFFSET offset]
SHOW COUNT(*) ERRORS
SHOW COUNT(*) ERRORS;
SELECT @@error_count;
SELECT f();
ERROR 1305 (42000): FUNCTION f does not exist

SHOW COUNT(*) ERRORS;
+-----------------------+
| @@session.error_count |
+-----------------------+
|                     1 |
+-----------------------+

SHOW ERRORS;
+-------+------+---------------------------+
| Level | Code | Message                   |
+-------+------+---------------------------+
| Error | 1305 | FUNCTION f does not exist |
+-------+------+---------------------------+
SHOW CREATE VIEW [view-name]
SHOW CREATE VIEW example\G
*************************** 1. row ***************************
                View: example
         Create View: CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL
SECURITY DEFINER VIEW `example` AS (select `t`.`id` AS `id`,`t`.`s` AS `s` from
`t`)
character_set_client: cp850
collation_connection: cp850_general_ci
SHOW CREATE VIEW example\G
*************************** 1. row ***************************
                View: example
         Create View: CREATE ALGORITHM=UNDEFINED DEFINER=root@localhost SQL SECU
RITY DEFINER VIEW example AS (select t.id AS id,t.s AS s from t)
character_set_client: cp850
collation_connection: cp850_general_ci
GRANT SHOW VIEW,SELECT ON test_database.test_view TO 'test'@'localhost';
SELECT CURRENT_USER(), SCHEMA();
+----------------+----------+
| CURRENT_USER() | SCHEMA() |
+----------------+----------+
| jon@ghidora    | myschema |
+----------------+----------+

SHOW EVENTS\G
*************************** 1. row ***************************
                  Db: myschema
                Name: e_daily
             Definer: jon@ghidora
           Time zone: SYSTEM
                Type: RECURRING
          Execute at: NULL
      Interval value: 10
      Interval field: SECOND
              Starts: 2006-02-09 10:41:23
                Ends: NULL
              Status: ENABLED
          Originator: 0
character_set_client: latin1
collation_connection: latin1_swedish_ci
  Database Collation: latin1_swedish_ci
SHOW EVENTS FROM test;
SHOW FUNCTION STATUS\G
*************************** 1. row ***************************
                  Db: test
                Name: VatCents
                Type: FUNCTION
             Definer: root@localhost
            Modified: 2013-06-01 12:40:31
             Created: 2013-06-01 12:40:31
       Security_type: DEFINER
             Comment: 
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: latin1_swedish_ci
SHOW FUNCTION STATUS LIKE 'V%' \G
*************************** 1. row ***************************
                  Db: test
                Name: VatCents
                Type: FUNCTION
             Definer: root@localhost
            Modified: 2013-06-01 12:40:31
             Created: 2013-06-01 12:40:31
       Security_type: DEFINER
             Comment: 
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: latin1_swedish_ci
SHOW FUNCTION STATUS WHERE Security_type LIKE 'DEFINER' \G
*************************** 1. row ***************************
                  Db: test
                Name: VatCents
                Type: FUNCTION
             Definer: root@localhost
            Modified: 2013-06-01 12:40:31
             Created: 2013-06-01 12:40:31
       Security_type: DEFINER
             Comment: 
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: latin1_swedish_ci
from a given
plugin_library
. See
for details.

plugin_library is the name of the shared library thatcontains the plugin code. The file name extension (forexample, libmyplugin.so or libmyplugin.dll) can be omitted (which makes the statement look the same on all architectures).

The shared library must be located in the plugin directory (that is,the directory named by the plugin_dir system variable). The library must be in the plugin directory itself, not in a subdirectory. Bydefault, plugin_dir is plugin directory under the directory named bythe pkglibdir configuration variable, but it can be changed by settingthe value of plugin_dir at server startup. For example, setits value in a my.cnf file:

If the value of plugin_dir is a relative path name, it istaken to be relative to the MySQL base directory (the value of the basedirsystem variable).

INSTALL SONAME adds one or more lines to the mysql.plugin table thatdescribes the plugin. This table contains the plugin name and library filename.

INSTALL SONAME causes the server to readoption (my.cnf) files just as during server startup. This enables the plugin topick up any relevant options from those files. It is possible to add pluginoptions to an option file even before loading a plugin (if the loose prefix isused). It is also possible to uninstall a plugin, edit my.cnf, and install theplugin again. Restarting the plugin this way enables it to the new optionvalues without a server restart.

INSTALL SONAME also loads and initializes the plugin code tomake the plugin available for use. A plugin is initialized by executing itsinitialization function, which handles any setup that the plugin must performbefore it can be used.

To use INSTALL SONAME, you must have the INSERT privilege for the mysql.plugin table.

At server startup, the server loads and initializes any plugin that islisted in the mysql.plugin table. This means that a plugin is installedwith INSTALL SONAME only once, not every time the serverstarts. Plugin loading at startup does not occur if the server is started withthe --skip-grant-tables option.

When the server shuts down, it executes the de-initialization functionfor each plugin that is loaded so that the plugin has a chance toperform any final cleanup.

If you need to load plugins for a single server startup when the--skip-grant-tables option is given (which tells the servernot to read system tables), use the--plugin-load mariadbd option.

If you need to install only one plugin from a library, use the INSTALL PLUGIN statement.

Examples

To load the LOCALES plugin and all of its information_schema tables with one statement, use

This statement can be used instead of INSTALL PLUGIN even when the library contains only one plugin:

See Also

  • List of Plugins

  • Plugin Overview

  • SHOW PLUGINS

  • INSTALL PLUGIN

This page is licensed: CC BY-SA / Gnu FDL

INSTALL PLUGIN
plugins
INSTALL PLUGIN
plugin_library
. See
for details.

plugin_library is the name of the shared library thatcontains the plugin code. The file name extension (forexample, libmyplugin.so or libmyplugin.dll) can be omitted (which makes the statement look the same on all architectures).

To use UNINSTALL SONAME, you must have the DELETE privilege for the mysql.plugin table.

IF EXISTS

If the IF EXISTS clause is used, MariaDB will return a note instead of an error if the plugin library does not exist. See SHOW WARNINGS.

Examples

To uninstall the XtraDB plugin and all of its information_schema tables with one statement, use

See Also

  • INSTALL SONAME

  • SHOW PLUGINS

  • INSTALL PLUGIN

  • UNINSTALL PLUGIN

This page is licensed: CC BY-SA / Gnu FDL

UNINSTALL PLUGIN
plugins
UNINSTALL PLUGIN
Description

RESET REPLICA makes the replica forget its replication position in the master's binary log. This statement is meant to be used for a clean start. It deletes the master.info and relay-log.info files, all the relay log files, and starts a new relay log file. To use RESET REPLICA, the replica threads must be stopped (use STOP REPLICA if necessary).

Note: All relay log files are deleted, even if they have not been completely executed by the replica SQL thread. (This is a condition likely to exist on a replication replica if you have issued a STOP REPLICA statement or if the replica is highly loaded.)

Note: RESET REPLICA does not reset the globalgtid_slave_pos variable. This means that a replica server configured with CHANGE MASTER TO MASTER_USE_GTID=slave_pos will not receive events with GTIDs occurring before the state saved ingtid_slave_pos. If the intent is to reprocess these events,gtid_slave_pos must be manually reset, e.g., by executing set global gtid_slave_pos="".

Connection information stored in the master.info file is immediately reset using any values specified in the corresponding startup options. This information includes values such as master host, master port, master user, and master password. If the replica SQL thread was in the middle of replicating temporary tables when it was stopped, and RESET REPLICA is issued, these replicated temporary tables are deleted on the replica.

The ALL also resets the PORT, HOST, USER, and PASSWORD parameters for the replica. If you are using a connection name, it will be permanently deleted it and it will not show up anymore in SHOW ALL REPLICAS STATUS.

connection_name

The connection_name option is used for multi-source replication.

If there is only one nameless primary, or the default primary (as specified by the default_master_connection system variable) is intended, connection_name can be omitted. If provided, the RESET REPLICA statement will apply to the specified primary. connection_name is case-insensitive.

MariaDB starting with

The FOR CHANNEL keyword was added for MySQL compatibility. This is identical to using the channel_name directly after RESET REPLICA.

FOR CHANNEL is not available.

The FOR CHANNEL keyword was added for MySQL compatibility. This is identical as using the channel_name directly after RESET REPLICA.

MariaDB starting with

RESET REPLICA resets the Master/Slave_last_event_time and Connects_Tried values (see SHOW REPLICA STATUS).

RESET REPLICA resets the Master/Slave_last_event_time values (see SHOW REPLICA STATUS).

RESET REPLICA does not reset the Master/Slave_last_event_time values (see ).

See Also

  • STOP REPLICA stops the replica, but it can be restarted with START REPLICA or after next MariaDB server restart.

This page is licensed: GPLv2, originally from fill_help_tables.sql

MDEV-18777

The TRIGGER privilege is required on the table the trigger is defined for to execute this statement.

SHOW CREATE TRIGGER quotes identifiers, according to the value of the sql_quote_show_create system variable.

SHOW CREATE TRIGGER quotes identifiers, according to the value of the sql_quote_show_create system variable. However, the output of this statement is unreliably affected by the sql_quote_show_create system variable.

Examples

The Created column serves to better view multiple trigger events.

The Created column is unavailable.

See Also

  • Trigger Overview

  • CREATE TRIGGER

  • DROP TRIGGER

  • information_schema.TRIGGERS Table

This page is licensed: GPLv2, originally from fill_help_tables.sql

CREATE TRIGGER
SQL_MODE
SHOW SCHEMAS
is a synonym for
SHOW DATABASES
. The
LIKE
clause, if present on its own, indicates which database names to match. The
WHERE
and
LIKE
clauses can be given to select rows using more general conditions, as discussed in
.

You see only those databases for which you have some kind of privilege, unless you have the global SHOW DATABASES privilege. You can also get this list using the mariadb-show command.

If the server was started with the --skip-show-database option, you cannot use this statement at all unless you have the SHOW DATABASES privilege.

The list of results returned by SHOW DATABASES is based on directories in the data directory, which is how MariaDB implements databases. It's possible that output includes directories that do not correspond to actual databases.

The Information Schema SCHEMATA table also contains database information.

Examples

See Also

  • CREATE DATABASE

  • ALTER DATABASE

  • DROP DATABASE

  • SHOW CREATE DATABASE

This page is licensed: GPLv2, originally from fill_help_tables.sql

Extended SHOW
TEMPORARY
tables that are currently open in the table cache. See
.

The FROM and LIKE clauses may be used.

The FROM clause, if present, restricts the tables shown to those present in thedb_name database.

The LIKE clause, if present on its own, indicates which table names to match. The WHERE and LIKE clauses can be given to select rows using more general conditions, as discussed in Extended SHOW.

The following information is returned:

Column
Description

Database

Database name.

Name

Table name.

In_use

Number of table instances being used.

Name_locked

1 if the table is name-locked, e.g. if it is being dropped or renamed, otherwise 0.

LOCK TABLE... WRITE acquires a strong MDL lock, and concurrent connections will wait on this MDL lock, so any subsequent LOCK TABLE... WRITE will not increment In_use.

Before , each use of, for example, LOCK TABLE ... WRITE would increment In_use for that table. With the implementation of the metadata locking improvements in MariaDB 5.5, LOCK TABLE... WRITE acquires a strong MDL lock, and concurrent connections will wait on this MDL lock, so any subsequent LOCK TABLE... WRITE will not increment In_use.

Example

This page is licensed: GPLv2, originally from fill_help_tables.sql

table-cache.html
statement returns characteristics of stored package specifications, such as the database, name, type, creator, creation and modification dates, and character set information. A similar statement,
, displays information about stored package bodies (i.e. implementations).

The LIKE clause, if present, indicates which package names to match. The WHERE and LIKE clauses can be given to select rows using more general conditions, as discussed in Extended SHOW.

The ROUTINES table in the INFORMATION_SCHEMA database contains more detailed information.

Examples

See Also

  • SHOW PACKAGE BODY

  • SHOW CREATE PACKAGE

  • CREATE PACKAGE

  • DROP PACKAGE

This page is licensed: CC BY-SA / Gnu FDL

SHOW PACKAGE BODY STATUS
statement can be used when
is set. It shows the CREATE statement that creates the given package specification.

SHOW CREATE PACKAGE quotes identifiers according to the value of the sql_quote_show_create system variable.

Examples

See Also

  • CREATE PACKAGE

  • DROP PACKAGE

  • CREATE PACKAGE BODY

  • SHOW CREATE PACKAGE BODY

This page is licensed: CC BY-SA / Gnu FDL

Oracle SQL_MODE

ANALYZE: Interpreting rows and filtered members

Understand the r_rows and r_filtered fields in analysis output. Learn how these actual runtime counters compare to the optimizer's rows and filtered estimates.

This article describes how to interpret r_rows and r_filtered members in ANALYZE FORMAT=JSON when an index-based access method is used.

Index-based access method

Index-based access method may employ some or all of the following:

  • attached_condition checking

Consider a table access which does all three:

The access is performed as follows:

Access diagram

Statistics values in MariaDB before 11.5

In MariaDB versions before 11.5, the counters were counted as follows:

that is,

  • r_rows is counted after Index Condition Pushdown check and Rowid Filter check.

  • r_filtered only counts selectivity of the attached_condition.

  • selectivity of the Rowid Filter is in rowid_filter.r_selectivity_pct.

Statistics values in and later versions

Starting from (), the row counters are:

  • r_index_rows counts the number of enumerated index tuples, before any checks are made

  • r_rows is the same as before - number of rows after index checks.

The selectivity counters are:

  • r_icp_filtered is the percentage of records left after pushed index condition check.

  • rowid_filter.r_selectivity_pct shows selectivity of Rowid Filter, as before.

  • r_filtered is the selectivity of attached_condition check, as before.

ANALYZE output members

in ANALYZE FORMAT=JSON output these members are placed as follows:

Whenever applicable, r_index_rows is shown. It is comparable with rows - both are numbers of rows to enumerate before any filtering is done. If r_index_rows is not shown, r_rows shows the number of records enumerated.

Then, filtering members:

filtered is comparable with r_total_filtered: both show total amount of filtering.

ICP and its observed filtering. The optimizer doesn't compute an estimate for this currently.

attached_condition and its observed filtering.

This page is licensed: CC BY-SA / Gnu FDL

FLUSH TABLES FOR EXPORT

Prepare individual tables for binary backup. This command flushes changes to disk and locks tables, allowing safe copying of .ibd files while the server runs.

Syntax

Description

FLUSH TABLES ... FOR EXPORT flushes changes to the specified tables to disk so that binary copies can be made while the server is still running. This works for , , , , and tables.

The table is read locked until you issue .

If a storage engine does not support FLUSH TABLES FOR EXPORT, a 1031 error ( 'HY000') is produced.

If FLUSH TABLES ... FOR EXPORT is in effect in the session, the following statements will produce an error if attempted:

  • FLUSH TABLES WITH READ LOCK

  • FLUSH TABLES ... WITH READ LOCK

  • FLUSH TABLES ... FOR EXPORT

If any of the following statements is in effect in the session, attempting FLUSH TABLES ... FOR EXPORT will produce an error.

  • FLUSH TABLES ... WITH READ LOCK

  • FLUSH TABLES ... FOR EXPORT

  • LOCK TABLES ... READ

FLUSH FOR EXPORT is not written to the .

This statement requires the and the privileges.

If one of the specified tables cannot be locked, none of the tables will be locked.

If a table does not exist, an error like the following will be produced:

If a table is a view, an error like the following will be produced:

Example

For a full description, please see .

See Also

  • - Compressing the MyISAM data file for easier distribution.

This page is licensed: CC BY-SA / Gnu FDL

INSTALL PLUGIN

Install a specific plugin from a shared library. This statement adds the plugin to the mysql.plugin table and loads its code into the server memory.

Syntax

Description

This statement installs an individual plugin from the specified library. To install the whole library (which could be required), use INSTALL SONAME. See also .

plugin_name is the name of the plugin as defined in theplugin declaration structure contained in the library file. Plugin names arenot case sensitive. For maximal compatibility, plugin names should be limitedto ASCII letters, digits, and underscore, because they are used in C sourcefiles, shell command lines, M4 and Bourne shell scripts, and SQL environments.

plugin_library is the name of the shared library thatcontains the plugin code. The file name extension can be omitted (which makes the statement look the same on all architectures).

The shared library must be located in the plugin directory (that is,the directory named by the system variable). The library must be in the plugin directory itself, not in a subdirectory. Bydefault, plugin_dir is plugin directory under the directory named bythe pkglibdir configuration variable, but it can be changed by settingthe value of plugin_dir at server startup. For example, setits value in a my.cnf file:

If the value of is a relative path name, it istaken to be relative to the base directory (the value of the system variable).

INSTALL PLUGIN adds a line to the mysql.plugin table thatdescribes the plugin. This table contains the plugin name and library filename.

INSTALL PLUGIN causes the server to readoption (my.cnf) files just as during server startup. This enables the plugin topick up any relevant options from those files. It is possible to add pluginoptions to an option file even before loading a plugin (if the loose prefix isused). It is also possible to uninstall a plugin, edit my.cnf, and install theplugin again. Restarting the plugin this way enables it to the new optionvalues without a server restart.

INSTALL PLUGIN also loads and initializes the plugin code tomake the plugin available for use. A plugin is initialized by executing itsinitialization function, which handles any setup that the plugin must performbefore it can be used.

To use INSTALL PLUGIN, you must have the for the mysql.plugin table.

At server startup, the server loads and initializes any plugin that islisted in the mysql.plugin table. This means that a plugin is installedwith INSTALL PLUGIN only once, not every time the serverstarts. Plugin loading at startup does not occur if the server is started withthe --skip-grant-tables option.

When the server shuts down, it executes the de-initialization functionfor each plugin that is loaded so that the plugin has a chance toperform any final cleanup.

If you need to load plugins for a single server startup when the--skip-grant-tables option is given (which tells the servernot to read system tables), use the--plugin-load .

IF NOT EXISTS

When the IF NOT EXISTS clause is used, MariaDB will return a note instead of an error if the specified plugin already exists. See .

Examples

The extension can also be omitted:

See Also

This page is licensed: GPLv2, originally from

START REPLICA

The terms master and slave have historically been used in replication, and MariaDB has begun the process of adding primary and replica synonyms. The old terms will continue to be used to maintain backward compatibility - see MDEV-18777 to follow progress on this effort.

Syntax

Description

START REPLICA is a synonym for START SLAVE, which is considered deprecated.

Only START SLAVE can be used.

START SLAVE or START REPLICA with no thread_type options starts both of the replica threads (see ) needed to connect with a master setup with The I/O thread reads events from the primary server and stores them in the . The SQL thread reads events from the relay log and executes them.

START REPLICA requires the privilege.

START REPLICA requires the privilege.

If START REPLICA succeeds in starting the replica threads, it returns without any error. However, even in that case, it might be that the replica threads start and then later stop (for example, because they do not manage to connect to the primary or read its , or some other problem). START REPLICA does not warn you about this. You must check the replica's for error messages generated by the replica threads or check that they are running satisfactorily with ().

START REPLICA UNTIL

START REPLICA UNTIL refers to the SQL_THREAD replica position at which the SQL_THREAD replication will halt. If SQL_THREAD isn't specified, both threads are started.

START REPLICA UNTIL master_gtid_pos=xxx is also supported. See for more details.

MariaDB starting with

SQL_BEFORE_GTIDS|SQL_AFTER_GTIDS

The START REPLICA UNTIL statement contains the options SQL_BEFORE_GTIDS and SQL_AFTER_GTIDS to allow control of whether the replica stops before or after a provided GTID state. Its syntax is:

See for details.

SQL_BEFORE_GTIDS and SQL_AFTER_GTIDS are not available.

connection_name

If there is only one nameless primary, or the default primary (as specified by the system variable) is intended, connection_name can be omitted. If provided, the START REPLICA statement will apply to the specified primary. connection_name is case-insensitive.

The FOR CHANNEL keyword is available for MySQL compatibility. This is identical to using the channel_name directly after START REPLICA.

The FOR CHANNEL keyword is not available.

START ALL REPLICAS

START ALL REPLICAS starts all configured replicas (replicas with master_host not empty) that were not started before. It will give a note for all started connections. You can check the notes with .

See Also

  • .

  • is used to create and change connections.

  • is used to stop a running connection.

  • is used to reset parameters for a connection and also to permanently delete a primary connection.

This page is licensed: GPLv2, originally from

SHOW COLLATION

List available collations. View the character set associated with each collation and identifying properties like ID and default status.

Syntax

Description

The output from SHOW COLLATION includes all available . The LIKE clause, if present on its own, indicates which collation names to match. The WHERE and LIKE clauses can be given to select rows using more general conditions, as discussed in .

Similar information, including some extra information, can be queried from the table.

No similar information or extra information can be queried from the table.

See for details on specifying the collation at the server, database, table and column levels.

The pad_attribute column (not shown in the examples below) has a value of NO PAD or PAD SPACE. This attribute affects whether trailing spaces are significant in string comparisons. See the table description for more information.

The pad_attribute column is not available.

Examples

See Also

This page is licensed: GPLv2, originally from

SHOW CREATE PACKAGE BODY

Display the CREATE statement for a package body. This Oracle-compatible statement shows the implementation code of a stored package.

Syntax

Description

The SHOW CREATE PACKAGE BODY statement shows the CREATE PACKAGE BODY statement that creates the given package body (that is, the implementation of the package).

The SHOW CREATE PACKAGE BODY statement shows the CREATE PACKAGE BODY statement that creates the given package body (that is, the implementation of the package). CREATE PACKAGE BODY can be used when is set.

SHOW CREATE PACKAGE BODY quotes identifiers according to the value of the system variable.

Examples

See Also

This page is licensed: CC BY-SA / Gnu FDL

Extended SHOW

Understand the extensions to the SHOW statement. Learn how to use WHERE and LIKE clauses to perform complex filtering on metadata results.

The following SHOW statements can be extended using a WHERE clause and a LIKE clause to refine the results:

  • SHOW CHARACTER SET

  • SHOW COLLATION

  • ``

As with a regular , the WHERE clause can be used for the specific columns returned, and the clause with the regular wildcards.

Examples

This statement shows all tables:

This statement only shows tables starting with the letter 'a':

This statement shows variables whose names start with aria and have a value greater than 8192:

This page is licensed: CC BY-SA / Gnu FDL

SHOW CREATE SEQUENCE

View the SQL used to create a sequence. This statement displays the CREATE SEQUENCE statement with current parameter values.

Syntax

Description

Shows the CREATE SEQUENCE statement that creates the given sequence. The statement requires the SELECT privilege for the table.

SHOW CREATE SEQUENCE quotes identifiers according to the value of the system variable.

Example

Notes

If you want to see the underlying table structure used for the SEQUENCE you can use on the SEQUENCE. You can also use SELECT to read the current recorded state of the SEQUENCE:

The also provides information about available sequences:

See Also

This page is licensed: CC BY-SA / Gnu FDL

SHOW GRANTS

View privileges assigned to a user. This statement displays the GRANT statements required to replicate a user's permissions.

Syntax

Description

The SHOW GRANTS statement lists privileges granted to a particular user or role.

Users

The statement lists the statement or statements that must be issued to duplicate the privileges that are granted to a MariaDB user account. The account is named using the same format as for theGRANT statement; for example, 'jeffrey'@'localhost'. If you specify only the user name part of the account name, a host name part of '%' is used. For additional information about specifying account names, see .

To list the privileges granted to the account that you are using to connect to the server, you can use any of the following statements:

If SHOW GRANTS FOR CURRENT_USER (or any of the equivalent syntaxes) is used in DEFINER context (such as within a stored procedure that is defined withSQL SECURITY DEFINER), the grants displayed are those of the definer and not the invoker.

Roles

SHOW GRANTS can also be used to view the privileges granted to a .

Example

FOR PUBLIC

grants privileges to all users. SHOW GRANTS FOR PUBLIC shows all these grants.

FOR PUBLIC is not available.

See Also

  • shows how the user was created.

  • shows the privileges supported by MariaDB.

This page is licensed: GPLv2, originally from

SHOW PROCEDURE CODE

Display the internal instruction representation of a stored procedure. This debug statement shows the low-level opcodes of the routine.

Syntax

SHOW PROCEDURE CODE proc_name

Description

This statement is a MariaDB extension that is available only for servers that have been built with debugging support. It displays a representation of the internal implementation of the named . A similar statement, , displays information about .

Both statements require that you be the owner of the routine or have access to the table.

If the named routine is available, each statement produces a result set. Each row in the result set corresponds to one "instruction" in the routine. The first column is Pos, which is an ordinal number beginning with 0. The second column is Instruction, which contains an SQL statement (usually changed from the original source), or a directive which has meaning only to the stored-routine handler.

Examples

See Also

This page is licensed: GPLv2, originally from

SHOW PACKAGE BODY STATUS

List stored package bodies. View metadata about the implementation part of Oracle-compatible packages.

Syntax

Description

The SHOW PACKAGE BODY STATUS statement returns characteristics of stored package bodies (implementations), such as the database, name, type, creator, creation and modification dates, and character set information. A similar statement, , displays information about stored package specifications.

The LIKE clause, if present, indicates which package names to match. The WHERE and LIKE clauses can be given to select rows using more general conditions, as discussed in .

The in the INFORMATION_SCHEMA database contains more detailed information.

Examples

See Also

This page is licensed: CC BY-SA / Gnu FDL

SHOW PROCEDURE STATUS

List stored procedures and their characteristics. View metadata like the database, name, type, and creator of stored procedures.

Syntax

Description

This statement is a MariaDB extension. It returns characteristics of a stored procedure, such as the database, name, type, creator, creation and modification dates, and character set information. A similar statement, , displays information about stored functions.

The LIKE clause, if present, indicates which procedure or function names to match. The WHERE and LIKE clauses can be given to select rows using more general conditions, as discussed in .

The in the INFORMATION_SCHEMA database contains more detailed information.

Examples

See Also

This page is licensed: GPLv2, originally from

SHOW INDEX_STATISTICS

View usage statistics for table indexes. This statement displays how often specific indexes are used, helping optimize query performance.

Syntax

SHOW INDEX_STATISTICS

Description

The information_schema.INDEX_STATISTICS table shows statistics on index usage and makes it possible to do such things as locating unused indexes and generating the commands to remove them.

SHOW INDEX_STATISTICS is replaced by the generic statement.

The SHOW INDEX_STATISTICS statement was introduced in as part of the feature. It was removed as a separate statement in , but effectively replaced by the generic statement.

The system variable must be set to 1 to activate this feature. See the and table for more information.

Example

This page is licensed: CC BY-SA / Gnu FDL

ANALYZE Statement

Learn to use the ANALYZE statement to execute a query and produce a performance report. This command reveals how close the optimizer's plan was to the actual execution.

Description

The ANALYZE statement is similar to the EXPLAIN statement. ANALYZE statement will invoke the optimizer, execute the statement, and then produce EXPLAIN output instead of the result set. The EXPLAIN output will be annotated with statistics from statement execution.

STOP REPLICA

The terms master and slave have historically been used in replication, and MariaDB has begun the process of adding primary and replica synonyms. The old terms will continue to be used to maintain backward compatibility - see to follow progress on this effort.

Syntax

SHOW COLUMNS

Display information about columns in a table. View field names, types, default values, and other attributes for a specific table.

Syntax

Description

SHOW COLUMNS displays information about the columns in a given table. It also works for views. The

SHOW ENGINE

Display status information for a storage engine. This statement retrieves operational logs or status details for a specific engine.

Syntax

Description

SHOW ENGINE displays operational information about a storage engine. The following statements currently are supported:

SHOW ENGINES

List available storage engines. View the support status (default, active, or disabled) and description for each engine.

Syntax

Description

SHOW ENGINES displays status information about the server's storage engines. This is particularly useful for checking whether a storage engine is supported, or to see what the default engine is.

INSTALL SONAME 'plugin_library'
[mariadbd]
plugin_dir=/path/to/plugin/directory
INSTALL SONAME 'locales';
INSTALL SONAME 'ha_sequence';
UNINSTALL SONAME  [IF EXISTS] 'plugin_library'
UNINSTALL SONAME 'ha_xtradb';
UNINSTALL SONAME IF EXISTS 'ha_example';
Query OK, 0 rows affected (0.099 sec)

UNINSTALL SONAME IF EXISTS 'ha_example';
Query OK, 0 rows affected, 1 warning (0.000 sec)

SHOW WARNINGS;
+-------+------+-------------------------------------+
| Level | Code | Message                             |
+-------+------+-------------------------------------+
| Note  | 1305 | SONAME ha_example.so does not exist |
+-------+------+-------------------------------------+
RESET { SLAVE | REPLICA } ["connection_name"] [ALL]  [FOR CHANNEL "connection_name"].
SHOW CREATE TRIGGER trigger_name
SHOW CREATE TRIGGER example\G
*************************** 1. row ***************************
               Trigger: example
              sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,STRICT_ALL_TABLES
,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_
ENGINE_SUBSTITUTION
SQL Original Statement: CREATE DEFINER=`root`@`localhost` TRIGGER example BEFORE
 INSERT ON t FOR EACH ROW
BEGIN
        SET NEW.c = NEW.c * 2;
END
  character_set_client: cp850
  collation_connection: cp850_general_ci
  Database Collation: utf8_general_ci
  Created: 2016-09-29 13:53:34.35
SHOW {DATABASES | SCHEMAS}
    [LIKE 'pattern' | WHERE expr]
SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
SHOW DATABASES LIKE 'm%';
+---------------+
| Database (m%) |
+---------------+
| mysql         |
+---------------+
SHOW OPEN TABLES [FROM db_name]
    [LIKE 'pattern' | WHERE expr]
SHOW OPEN TABLES;
+----------+---------------------------+--------+-------------+
| Database | Table                     | In_use | Name_locked |
+----------+---------------------------+--------+-------------+
...
| test     | xjson                     |      0 |           0 |
| test     | jauthor                   |      0 |           0 |
| test     | locks                     |      1 |           0 |
...
+----------+---------------------------+--------+-------------+
SHOW PACKAGE STATUS
    [LIKE 'pattern' | WHERE expr]
SHOW PACKAGE STATUS LIKE 'pkg1'\G
*************************** 1. row ***************************
                  Db: test
                Name: pkg1
                Type: PACKAGE
             Definer: root@localhost
            Modified: 2018-02-27 14:38:15
             Created: 2018-02-27 14:38:15
       Security_type: DEFINER
             Comment: This is my first package
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: latin1_swedish_ci
SHOW CREATE PACKAGE  [ db_name . ] package_name
SHOW CREATE PACKAGE employee_tools\G
*************************** 1. row ***************************
             Package: employee_tools
            sql_mode: PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER
      Create Package: CREATE DEFINER="root"@"localhost" PACKAGE "employee_tools" AS
  FUNCTION getSalary(eid INT) RETURN DECIMAL(10,2);
  PROCEDURE raiseSalary(eid INT, amount DECIMAL(10,2));
  PROCEDURE raiseSalaryStd(eid INT);
  PROCEDURE hire(ename TEXT, esalary DECIMAL(10,2));
END
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: latin1_swedish_ci
FLUSH TABLE[S] table_name [, table_name] FOR EXPORT
INSTALL PLUGIN [IF NOT EXISTS] plugin_name SONAME 'plugin_library'
START { SLAVE | REPLICA } ["connection_name"] [thread_type [, thread_type] ... ]
START { SLAVE | REPLICA } ["connection_name"] [SQL_THREAD] UNTIL                
    MASTER_LOG_FILE = 'log_name', MASTER_LOG_POS = log_pos 
START { SLAVE | REPLICA } ["connection_name"] [SQL_THREAD] UNTIL
    RELAY_LOG_FILE = 'log_name', RELAY_LOG_POS = log_pos 
START { SLAVE | REPLICA } ["connection_name"] [SQL_THREAD] UNTIL
    MASTER_GTID_POS = <GTID position> 
START ALL { SLAVES | REPLICAS } [thread_type [, thread_type]] 

thread_type: IO_THREAD | SQL_THREAD
SHOW COLLATION
    [LIKE 'pattern' | WHERE expr]
SHOW CREATE PACKAGE BODY  [ db_name . ] package_name
SHOW CREATE SEQUENCE sequence_name;
SHOW GRANTS [FOR user|role]
SHOW PACKAGE BODY STATUS
    [LIKE 'pattern' | WHERE expr]
SHOW PROCEDURE STATUS
    [LIKE 'pattern' | WHERE expr]
UNINSTALL PLUGIN
UNINSTALL SONAME
SHOW PLUGINS
INFORMATION_SCHEMA.PLUGINS Table
mysql_plugin
SHOW PLUGINS
INFORMATION_SCHEMA.PLUGINS Table
mysql_plugin
List of Plugins
SHOW TRIGGERS
Trigger Limitations
Character Sets and Collations
Information Schema SCHEMATA Table
DROP PACKAGE BODY
Oracle SQL_MODE

This page is licensed: CC BY-SA / Gnu FDL

In the DEFAULT clause of a SHOW CREATE statement, numbers are quoted.

Any statement trying to update any table
LOCK TABLES ... WRITE

aria_pack - Compressing the Aria data file for easier distribution

Archive
Aria
CSV
InnoDB
MyISAM
MERGE
UNLOCK TABLES
SQLSTATE
binary log
RELOAD
LOCK TABLES
copying MariaDB tables
FLUSH TABLES
Copying Tables Between Different MariaDB Databases and MariaDB Servers
Copying Transportable InnoDB Tablespaces
myisampack
SHOW PLUGINS
  • INSTALL SONAME

  • UNINSTALL PLUGIN

  • UNINSTALL SONAME

  • Installing a Plugin
    plugin_dir
    plugin_dir
    basedir
    INSERT privilege
    mariadbd option
    SHOW WARNINGS
    List of Plugins
    Plugin Overview
    INFORMATION_SCHEMA.PLUGINS Table
    mariadb-plugin
    fill_help_tables.sql
    collations
    Extended SHOW
    Information Schema COLLATIONS
    Information Schema COLLATIONS
    Setting Character Sets and Collations
    INFORMATION_SCHEMA.COLLATIONS
    Supported Character Sets and Collations
    Setting Character Sets and Collations
    Information Schema COLLATIONS
    fill_help_tables.sql
    SHOW COLLATION LIKE 'utf8mb4_bin'; 
    +-------------+---------+------+---------+----------+---------+---------------+ 
    | Collation   | Charset | Id   | Default | Compiled | Sortlen | Pad_attribute | 
    +-------------+---------+------+---------+----------+---------+---------------+ 
    | utf8mb4_bin | utf8mb4 | 46   |         | Yes      | 1       | PAD SPACE     | 
    +-------------+---------+------+---------+----------+---------+---------------+
    DROP PACKAGE BODY
  • Oracle SQL_MODE

  • Oracle SQL_MODE
    sql_quote_show_create
    CREATE PACKAGE
    SHOW CREATE PACKAGE
    DROP PACKAGE
    CREATE PACKAGE BODY
    SHOW COLUMNS
    SHOW DATABASES
    SHOW FUNCTION STATUS
    SHOW INDEX
    SHOW OPEN TABLES
    SHOW PACKAGE STATUS
    SHOW PACKAGE BODY STATUS
    SHOW INDEX
    SHOW PROCEDURE STATUS
    SHOW STATUS
    SHOW TABLE STATUS
    SHOW TABLES
    SHOW TRIGGERS
    SHOW VARIABLES
    SELECT
    LIKE
    sql_quote_show_create
    SHOW CREATE TABLE
    Information Schema SEQUENCES Table
    CREATE SEQUENCE
    ALTER SEQUENCE
    Information Schema SEQUENCES Table
    GRANT
    GRANT
    role
    GRANT ... TO PUBLIC
    Authentication from MariaDB 10.4
    SHOW CREATE USER
    SHOW PRIVILEGES
    Roles
    fill_help_tables.sql
    SHOW CREATE PROCEDURE
  • SHOW PROCEDURE STATUS

  • Stored Routine Privileges

  • Information Schema ROUTINES Table

  • stored procedure
    SHOW FUNCTION CODE
    stored functions
    SELECT
    mysql.proc
    Stored Procedure Overview
    CREATE PROCEDURE
    ALTER PROCEDURE
    DROP PROCEDURE
    fill_help_tables.sql
    SHOW CREATE PROCEDURE
  • Stored Routine Privileges

  • Information Schema ROUTINES Table

  • SHOW FUNCTION STATUS
    Extended SHOW
    ROUTINES table
    Stored Procedure Overview
    CREATE PROCEDURE
    ALTER PROCEDURE
    DROP PROCEDURE
    fill_help_tables.sql
    ERROR 1146 (42S02): Table 'test.xxx' doesn't exist
    ERROR 1347 (HY000): 'test.v' is not BASE TABLE
    FLUSH TABLES test.t1 FOR EXPORT;
    #  Copy files related to the table (see below)
    UNLOCK TABLES;
    [mariadbd]
    plugin_dir=/path/to/plugin/directory
    INSTALL PLUGIN sphinx SONAME 'ha_sphinx.so';
    INSTALL PLUGIN innodb SONAME 'ha_xtradb';
    INSTALL PLUGIN IF NOT EXISTS example SONAME 'ha_example';
    Query OK, 0 rows affected (0.104 sec)
    
    INSTALL PLUGIN IF NOT EXISTS example SONAME 'ha_example';
    Query OK, 0 rows affected, 1 warning (0.000 sec)
    
    SHOW WARNINGS;
    +-------+------+------------------------------------+
    | Level | Code | Message                            |
    +-------+------+------------------------------------+
    | Note  | 1968 | Plugin 'example' already installed |
    +-------+------+------------------------------------+
    SHOW COLLATION LIKE 'latin1%';
    +-------------------------+---------+------+---------+----------+---------+
    | Collation               | Charset | Id   | Default | Compiled | Sortlen |
    +-------------------------+---------+------+---------+----------+---------+
    | latin1_german1_ci       | latin1  |    5 |         | Yes      |       1 |
    | latin1_swedish_ci       | latin1  |    8 | Yes     | Yes      |       1 |
    | latin1_danish_ci        | latin1  |   15 |         | Yes      |       1 |
    | latin1_german2_ci       | latin1  |   31 |         | Yes      |       2 |
    | latin1_bin              | latin1  |   47 |         | Yes      |       1 |
    | latin1_general_ci       | latin1  |   48 |         | Yes      |       1 |
    | latin1_general_cs       | latin1  |   49 |         | Yes      |       1 |
    | latin1_spanish_ci       | latin1  |   94 |         | Yes      |       1 |
    | latin1_swedish_nopad_ci | latin1  | 1032 |         | Yes      |       1 |
    | latin1_nopad_bin        | latin1  | 1071 |         | Yes      |       1 |
    +-------------------------+---------+------+---------+----------+---------+
    SHOW COLLATION WHERE Sortlen LIKE '8' AND Charset LIKE 'utf8mb4';
    +------------------------------+---------+------+---------+----------+---------+
    | Collation                    | Charset | Id   | Default | Compiled | Sortlen |
    +------------------------------+---------+------+---------+----------+---------+
    | utf8mb4_unicode_ci           | utf8mb4 |  224 |         | Yes      |       8 |
    | utf8mb4_icelandic_ci         | utf8mb4 |  225 |         | Yes      |       8 |
    | utf8mb4_latvian_ci           | utf8mb4 |  226 |         | Yes      |       8 |
    | utf8mb4_romanian_ci          | utf8mb4 |  227 |         | Yes      |       8 |
    | utf8mb4_slovenian_ci         | utf8mb4 |  228 |         | Yes      |       8 |
    | utf8mb4_polish_ci            | utf8mb4 |  229 |         | Yes      |       8 |
    | utf8mb4_estonian_ci          | utf8mb4 |  230 |         | Yes      |       8 |
    | utf8mb4_spanish_ci           | utf8mb4 |  231 |         | Yes      |       8 |
    | utf8mb4_swedish_ci           | utf8mb4 |  232 |         | Yes      |       8 |
    | utf8mb4_turkish_ci           | utf8mb4 |  233 |         | Yes      |       8 |
    | utf8mb4_czech_ci             | utf8mb4 |  234 |         | Yes      |       8 |
    | utf8mb4_danish_ci            | utf8mb4 |  235 |         | Yes      |       8 |
    | utf8mb4_lithuanian_ci        | utf8mb4 |  236 |         | Yes      |       8 |
    | utf8mb4_slovak_ci            | utf8mb4 |  237 |         | Yes      |       8 |
    | utf8mb4_spanish2_ci          | utf8mb4 |  238 |         | Yes      |       8 |
    | utf8mb4_roman_ci             | utf8mb4 |  239 |         | Yes      |       8 |
    | utf8mb4_persian_ci           | utf8mb4 |  240 |         | Yes      |       8 |
    | utf8mb4_esperanto_ci         | utf8mb4 |  241 |         | Yes      |       8 |
    | utf8mb4_hungarian_ci         | utf8mb4 |  242 |         | Yes      |       8 |
    | utf8mb4_sinhala_ci           | utf8mb4 |  243 |         | Yes      |       8 |
    | utf8mb4_german2_ci           | utf8mb4 |  244 |         | Yes      |       8 |
    | utf8mb4_croatian_mysql561_ci | utf8mb4 |  245 |         | Yes      |       8 |
    | utf8mb4_unicode_520_ci       | utf8mb4 |  246 |         | Yes      |       8 |
    | utf8mb4_vietnamese_ci        | utf8mb4 |  247 |         | Yes      |       8 |
    | utf8mb4_croatian_ci          | utf8mb4 |  608 |         | Yes      |       8 |
    | utf8mb4_myanmar_ci           | utf8mb4 |  609 |         | Yes      |       8 |
    | utf8mb4_unicode_nopad_ci     | utf8mb4 | 1248 |         | Yes      |       8 |
    | utf8mb4_unicode_520_nopad_ci | utf8mb4 | 1270 |         | Yes      |       8 |
    +------------------------------+---------+------+---------+----------+---------+
    SHOW CREATE PACKAGE BODY employee_tools\G
    *************************** 1. row ***************************
            Package body: employee_tools
                sql_mode: PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER
     Create Package Body: CREATE DEFINER="root"@"localhost" PACKAGE BODY "employee_tools" AS
      
      stdRaiseAmount DECIMAL(10,2):=500;
      
      PROCEDURE log (eid INT, ecmnt TEXT) AS
      BEGIN
        INSERT INTO employee_log (id, cmnt) VALUES (eid, ecmnt);
      END;
      
      PROCEDURE hire(ename TEXT, esalary DECIMAL(10,2)) AS
        eid INT;
      BEGIN
        INSERT INTO employee (name, salary) VALUES (ename, esalary);
        eid:= last_insert_id();
        log(eid, 'hire ' || ename);
      END;
    
      FUNCTION getSalary(eid INT) RETURN DECIMAL(10,2) AS
        nSalary DECIMAL(10,2);
      BEGIN
        SELECT salary INTO nSalary FROM employee WHERE id=eid;
        log(eid, 'getSalary id=' || eid || ' salary=' || nSalary);
        RETURN nSalary;
      END;
    
      PROCEDURE raiseSalary(eid INT, amount DECIMAL(10,2)) AS
      BEGIN
        UPDATE employee SET salary=salary+amount WHERE id=eid;
        log(eid, 'raiseSalary id=' || eid || ' amount=' || amount);
      END;
    
      PROCEDURE raiseSalaryStd(eid INT) AS
      BEGIN
        raiseSalary(eid, stdRaiseAmount);
        log(eid, 'raiseSalaryStd id=' || eid);
      END;
    
    BEGIN  
      log(0, 'Session ' || connection_id() || ' ' || current_user || ' started');
    END
    character_set_client: utf8
    collation_connection: utf8_general_ci
      Database Collation: latin1_swedish_ci
    SHOW TABLES;
    +----------------------+
    | Tables_in_test       |
    +----------------------+
    | animal_count         |
    | animals              |
    | are_the_mooses_loose |
    | aria_test2           |
    | t1                   |
    | view1                |
    +----------------------+
    SHOW TABLES WHERE Tables_in_test LIKE 'a%';
    +----------------------+
    | Tables_in_test       |
    +----------------------+
    | animal_count         |
    | animals              |
    | are_the_mooses_loose |
    | aria_test2           |
    +----------------------+
    SHOW VARIABLES WHERE Variable_name LIKE 'aria%' AND Value >8192;
    +------------------------------+---------------------+
    | Variable_name                | Value               |
    +------------------------------+---------------------+
    | aria_checkpoint_log_activity | 1048576             |
    | aria_log_file_size           | 1073741824          |
    | aria_max_sort_file_size      | 9223372036853727232 |
    | aria_pagecache_buffer_size   | 134217728           |
    | aria_sort_buffer_size        | 134217728           |
    +------------------------------+---------------------+
    CREATE SEQUENCE s1 START WITH 50;
    SHOW CREATE SEQUENCE s1\G;
    *************************** 1. row ***************************
           Table: s1
    Create Table: CREATE SEQUENCE `s1` start with 50 minvalue 1 maxvalue 9223372036854775806 
      increment by 1 cache 1000 nocycle ENGINE=InnoDB
    SHOW CREATE TABLE s1\G
    *************************** 1. row ***************************
           Table: s1
    Create Table: CREATE TABLE `s1` (
      `next_not_cached_value` bigint(21) NOT NULL,
      `minimum_value` bigint(21) NOT NULL,
      `maximum_value` bigint(21) NOT NULL,
      `start_value` bigint(21) NOT NULL COMMENT 'start value when sequences is created 
         or value if RESTART is used',
      `increment` bigint(21) NOT NULL COMMENT 'increment value',
      `cache_size` bigint(21) unsigned NOT NULL,
      `cycle_option` tinyint(1) unsigned NOT NULL COMMENT '0 if no cycles are allowed, 
         1 if the sequence should begin a new cycle when maximum_value is passed',
      `cycle_count` bigint(21) NOT NULL COMMENT 'How many cycles have been done'
    ) ENGINE=InnoDB SEQUENCE=1
    
    SELECT * FROM s1\G
    *************************** 1. row ***************************
    next_not_cached_value: 50
            minimum_value: 1
            maximum_value: 9223372036854775806
              start_value: 50
                increment: 1
               cache_size: 1000
             cycle_option: 0
              cycle_count: 0
    SELECT * FROM INFORMATION_SCHEMA.SEQUENCES\G
    *************************** 1. row ***************************
           SEQUENCE_CATALOG: def
            SEQUENCE_SCHEMA: test
              SEQUENCE_NAME: s1
                  DATA_TYPE: bigint
          NUMERIC_PRECISION: 64
    NUMERIC_PRECISION_RADIX: 2
              NUMERIC_SCALE: 0
                START_VALUE: 50
              MINIMUM_VALUE: 1
              MAXIMUM_VALUE: 9223372036854775806
                  INCREMENT: 1
               CYCLE_OPTION: 0
    SHOW GRANTS FOR 'root'@'localhost';
    +---------------------------------------------------------------------+
    | Grants for root@localhost                                           |
    +---------------------------------------------------------------------+
    | GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION |
    +---------------------------------------------------------------------+
    SHOW GRANTS;
    SHOW GRANTS FOR CURRENT_USER;
    SHOW GRANTS FOR CURRENT_USER();
    SHOW GRANTS FOR journalist;
    +------------------------------------------+
    | Grants for journalist                    |
    +------------------------------------------+
    | GRANT USAGE ON *.* TO 'journalist'       |
    | GRANT DELETE ON `test`.* TO 'journalist' |
    +------------------------------------------+
    SHOW GRANTS FOR public;
    +------------------------------------------------+
    | Grants for PUBLIC                              |
    +------------------------------------------------+
    | GRANT ALL PRIVILEGES ON `dev_db`.* TO `PUBLIC` |
    +------------------------------------------------+
    DELIMITER //
    
    CREATE PROCEDURE p1 ()
      BEGIN
        DECLARE fanta INT DEFAULT 55;
        DROP TABLE t2;
        LOOP
          INSERT INTO t3 VALUES (fanta);
          END LOOP;
      END//
    Query OK, 0 rows affected (0.00 sec)
    
    SHOW PROCEDURE CODE p1//
    +-----+----------------------------------------+
    | Pos | Instruction                            |
    +-----+----------------------------------------+
    |   0 | set fanta@0 55                         |
    |   1 | stmt 9 "DROP TABLE t2"                 |
    |   2 | stmt 5 "INSERT INTO t3 VALUES (fanta)" |
    |   3 | jump 2                                 |
    +-----+----------------------------------------+
    SHOW PROCEDURE STATUS LIKE 'p1'\G
    *************************** 1. row ***************************
                      Db: test
                    Name: p1
                    Type: PROCEDURE
                 Definer: root@localhost
                Modified: 2010-08-23 13:23:03
                 Created: 2010-08-23 13:23:03
           Security_type: DEFINER
                 Comment: 
    character_set_client: latin1
    collation_connection: latin1_swedish_ci
      Database Collation: latin1_swedish_ci

    r_total_filtered is the combined selectivity of all checks.

    Index Condition Pushdown
    Rowid Filtering
    MDEV-18478
    index-read-diagram-3
    index-read-stats-old
    index-read-stats-new
    This lets one check how close the optimizer's estimates about the query plan are to the reality. ANALYZE produces an overview, while the ANALYZE FORMAT=JSON command provides a more detailed view of the query plan and the query execution.

    The syntax is

    where the statement is any statement for which one can run EXPLAIN.

    Command Output

    Consider an example:

    Compared to EXPLAIN, ANALYZE produces two extra columns:

    • r_rows is an observation-based counterpart of the rows column. It shows how many rows were actually read from the table.

    • r_filtered is an observation-based counterpart of the filtered column. It shows which fraction of rows was left after applying the WHERE condition.

    Interpreting the Output

    Joins

    Let's consider a more complicated example.

    Here, one can see that

    • For table customer, customer.rows=149095, customer.r_rows=150000. The estimate for number of rows we will read was fairly precise

    • customer.filtered=18.08, customer.r_filtered=9.13. The optimizer somewhat overestimated the number of records that will match selectivity of condition attached to customer table (in general, when you have a full scan and r_filtered is less than 15%, it's time to consider adding an appropriate index).

    • For table orders, orders.rows=7, orders.r_rows=10. This means that on average, there are 7 orders for a given c_custkey, but in our case there were 10, which is close to the expectation (when this number is consistently far from the expectation, it may be time to run ANALYZE TABLE, or even edit the table statistics manually to get better query plans).

    • orders.filtered=100, orders.r_filtered=30.03. The optimizer didn't have any way to estimate which fraction of records will be left after it checks the condition that is attached to table orders (it's orders.o_totalprice > 200*1000). So, it used 100%. In reality, it is 30%. 30% is typically not selective enough to warrant adding new indexes. For joins with many tables, it might be worth to collect and use for columns in question, this may help the optimizer to pick a better query plan.

    Meaning of NULL in r_rows and r_filtered

    Let's modify the previous example slightly

    The output of orders.r_rows=NULL and orders.r_filtered=NULL shows that the table orders was never scanned. Indeed, we can also see customer.r_filtered=0.00. This shows that a part of WHERE attached to table customer was never satisfied (or, satisfied in less than 0.01% of cases).

    ANALYZE FORMAT=JSON

    ANALYZE FORMAT=JSON produces JSON output. It produces much more information than tabular ANALYZE.

    Notes

    • ANALYZE UPDATE or ANALYZE DELETE will actually make updates/deletes (ANALYZE SELECT will perform the select operation and then discard the resultset).

    • PostgreSQL has a similar command, EXPLAIN ANALYZE.

    • The EXPLAIN in the slow query log feature allows MariaDB to have ANALYZE output of slow queries printed into the (see ).

    See Also

    • ANALYZE FORMAT=JSON

    • SHOW ANALYZE

    • ANALYZE TABLE

    • JIRA task for ANALYZE statement, MDEV-406

    This page is licensed: CC BY-SA / Gnu FDL

    Description

    Stops the replica threads. STOP REPLICA requires the SUPER privilege, or, from , the REPLICATION SLAVE ADMIN privilege.

    Like START REPLICA, this statement may be used with the IO_THREAD andSQL_THREAD options to name the thread or threads to be stopped. In almost all cases, one never need to use the thread_type options.

    STOP REPLICA waits until any current replication event group affecting one or more non-transactional tables has finished executing (if there is any such replication group), or until the user issues a KILL QUERY or KILL CONNECTION statement.

    Note that STOP REPLICA doesn't delete the connection permanently. Next time you execute START REPLICA or the MariaDB server restarts, the replica connection is restored with it's original arguments. If you want to delete a connection, you should execute RESET REPLICA.

    STOP ALL REPLICAS

    STOP ALL REPLICAS stops all your running replicas. It will give you a note for every stopped connection. You can check the notes with SHOW WARNINGS.

    connection_name

    The connection_name option is used for multi-source replication.

    If there is only one nameless master, or the default master (as specified by the default_master_connection system variable) is intended, connection_name can be omitted. If provided, the STOP REPLICA statement will apply to the specified master. connection_name is case-insensitive.

    MariaDB starting with

    The FOR CHANNEL keyword is available for MySQL compatibility. This is identical as using the channel_name directly after STOP REPLICA.

    The FOR CHANNEL keyword is not available.

    See Also

    • CHANGE MASTER TO is used to create and change connections.

    • START REPLICA is used to start a predefined connection.

    • RESET REPLICA is used to reset parameters for a connection and also to permanently delete a master connection.

    This page is licensed: GPLv2, originally from fill_help_tables.sql

    MDEV-18777
    LIKE
    clause, if present on its own, indicates which column names to match. The
    WHERE
    and
    LIKE
    clauses can be given to select rows using more general conditions, as discussed in
    .

    If the data types differ from what you expect them to be based on aCREATE TABLE statement, note that MariaDB sometimes changes data types when you create or alter a table. The conditions under which this occurs are described in the Silent Column Changes article.

    The FULL keyword causes the output to include the column collation and comments, as well as the privileges you have for each column.

    You can use db_name.tbl_name as an alternative to thetbl_name FROM db_name syntax. In other words, these two statements are equivalent:

    SHOW COLUMNS displays the following values for each table column:

    Field indicates the column name.

    Type indicates the column data type.

    Collation indicates the collation for non-binary string columns, or NULL for other columns. This value is displayed only if you use the FULL keyword.

    The Null field contains YES if NULL values can be stored in the column, NO if not.

    The Key field indicates whether the column is indexed:

    • If Key is empty, the column either is not indexed or is indexed only as a secondary column in a multiple-column, non-unique index.

    • If Key is PRI, the column is a PRIMARY KEY or is one of the columns in a multiple-column PRIMARY KEY.

    • If Key is UNI, the column is the first column of a unique-valued index that cannot contain NULL values.

    • If Key is MUL, multiple occurrences of a given value are allowed within the column. The column is the first column of a non-unique index or a unique-valued index that can contain NULL values.

    If more than one of the Key values applies to a given column of a table, Key displays the one with the highest priority, in the order PRI, UNI, MUL.

    A UNIQUE index may be displayed as PRI if it cannot contain NULL values and there is noPRIMARY KEY in the table. A UNIQUE index may display as MUL if several columns form a compositeUNIQUE index; although the combination of the columns is unique, each column can still hold multiple occurrences of a given value.

    The Default field indicates the default value that is assigned to the column.

    The Extra field contains any additional information that is available about a given column.

    Value
    Description

    AUTO_INCREMENT

    The column was created with the AUTO_INCREMENT keyword.

    PERSISTENT

    The column was created with the PERSISTENT keyword.

    VIRTUAL

    The column was created with the VIRTUAL keyword.

    on update CURRENT_TIMESTAMP

    The column is a TIMESTAMP column that is automatically updated on INSERT and UPDATE.

    Privileges indicates the privileges you have for the column. This value is displayed only if you use the FULL keyword.

    Comment indicates any comment the column has. This value is displayed only if you use the FULL keyword.

    SHOW FIELDS is a synonym forSHOW COLUMNS. Also DESCRIBE and EXPLAIN can be used as shortcuts.

    You can also list a table's columns with:

    See the mariadb-show command for more details.

    The DESCRIBE statement provides information similar to SHOW COLUMNS. The information_schema.COLUMNS table provides similar, but more complete, information.

    The SHOW CREATE TABLE, SHOW TABLE STATUS, and SHOW INDEX statements also provide information about tables.

    Examples

    See Also

    • DESCRIBE

    • mariadb-show

    • SHOW CREATE TABLE

    • SHOW TABLE STATUS

    This page is licensed: GPLv2, originally from fill_help_tables.sql

    Extended SHOW

    If the Sphinx Storage Engine is installed, the following is also supported:

    SHOW ENGINE INNODB STATUS

    SHOW ENGINE INNODB STATUS displays extensive information from the standard InnoDB Monitor about the state of the InnoDB storage engine. See SHOW ENGINE INNODB STATUS for more.

    SHOW ENGINE INNODB MUTEX

    SHOW ENGINE INNODB MUTEX displays InnoDB mutex statistics.

    The statement displays the following output fields:

    • Type: Always InnoDB.

    • Name: The source file where the mutex is implemented, and the line number in the file where the mutex is created. The line number is dependent on the MariaDB version.

    • Status: This field displays the following values if UNIV_DEBUG was defined at compilation time (for example, in include/univ.h in the InnoDB part of the source tree). Only the os_waits value is displayed if UNIV_DEBUG was not defined. Without UNIV_DEBUG, the information on which the output is based is insufficient to distinguish regular mutexes and mutexes that protect rw-locks (which allow multiple readers or a single writer). Consequently, the output may appear to contain multiple rows for the same mutex.

      • count indicates how many times the mutex was requested.

      • spin_waits indicates how many times the spinlock had to run.

      • spin_rounds indicates the number of spinlock rounds. (spin_rounds divided by spin_waits provides the average round count.)

      • os_waits indicates the number of operating system waits. This occurs when the spinlock did not work (the mutex was not locked during the spinlock and it was necessary to yield to the operating system and wait).

    Information from this statement can be used to diagnose system problems. For example, large values of spin_waits and spin_rounds may indicate scalability problems.

    The information_schema.INNODB_MUTEXES table provides similar information.

    SHOW ENGINE PERFORMANCE_SCHEMA STATUS

    This statement shows how much memory is used for performance_schema tables and internal buffers.

    The output contains the following fields:

    • Type: Always performance_schema.

    • Name: The name of a table, the name of an internal buffer, or the performance_schema word, followed by a dot and an attribute. Internal buffers names are enclosed by parenthesis. performance_schema means that the attribute refers to the whole database (it is a total).

    • Status: The value for the attribute.

    The following attributes are shown, in this order, for all tables:

    • row_size: The memory used for an individual record. This value will never change.

    • row_count: The number of rows in the table or buffer. For some tables, this value depends on a server system variable.

    • memory: For tables and performance_schema, this is the result of row_size * row_count.

    For internal buffers, the attributes are:

    • count

    • size

    SHOW ENGINE ROCKSDB STATUS

    See also MyRocks Performance Troubleshooting

    This page is licensed: GPLv2, originally from fill_help_tables.sql

    SHOW TABLE TYPES
    is a deprecated synonym.

    The information_schema.ENGINES table provides the same information.

    Since storage engines are plugins, different information about them is also shown in the information_schema.PLUGINS table and by the SHOW PLUGINS statement.

    Note that both MySQL's InnoDB and Percona's XtraDB replacement are labeled as InnoDB. However, if XtraDB is in use, it will be specified in the COMMENT field. See XtraDB and InnoDB. The same applies to FederatedX.

    The output consists of the following columns:

    • Engine indicates the engine's name.

    • Support indicates whether the engine is installed, and whether it is the default engine for the current session.

    • Comment is a brief description.

    • Transactions, XA and Savepoints indicate whether , and are supported by the engine.

    Examples

    This page is licensed: GPLv2, originally from fill_help_tables.sql

    replication
    CHANGE MASTER TO.
    relay log
    REPLICATION SLAVE ADMIN
    SUPER
    binary log
    error log
    SHOW REPLICA STATUS
    SHOW REPLICA STATUS
    Global Transaction ID/START REPLICA UNTIL master_gtid_pos=xxx
    Global Transaction ID#SQL_BEFORE_GTIDS/SQL_AFTER_GTIDS
    default_master_connection
    SHOW WARNINGS
    Setting up replication
    CHANGE MASTER TO
    STOP REPLICA
    RESET REPLICA
    fill_help_tables.sql
    SHOW PACKAGE STATUS
    Extended SHOW
    ROUTINES table
    SHOW PACKAGE STATUS
    SHOW CREATE PACKAGE BODY
    CREATE PACKAGE BODY
    DROP PACKAGE BODY
    SHOW TABLE STATISTICS
    User Statistics
    SHOW TABLE STATISTICS
    userstat
    User Statistics
    information_schema.INDEX_STATISTICS
    SHOW REPLICA STATUS

    BACKUP STAGE

    Control backup phases for external tools. Learn how to cycle through stages like START, BLOCK_DDL, and BLOCK_COMMIT to perform consistent backups with minimal locking.

    The BACKUP STAGE commands are a set of commands to make it possible to make an efficient external backup tool.

    Syntax

    In the following text, a transactional table means InnoDB, or specifically an InnoDB-like engine with redo log that can lock redo purges and can be copied without locks by an outside process.

    Goals with BACKUP STAGE Commands

    • To be able to do a majority of the backup with the minimum possible server locks. Especially for transactional tables (InnoDB, MyRocks etc) there is only need for a very short block of new commits while copying statistics and log tables.

    • DDL are only needed to be blocked for a very short duration of the backup while is copying the tables affected by DDL during the initial part of the backup.

    • Most non transactional tables (those that are not in use) will be copied during BACKUP STAGE START. The exceptions are system statistic and log tables that are not blocked during the backup until BLOCK_COMMIT.

    BACKUP STAGE Commands

    BACKUP STAGE START

    The START stage is designed for the following tasks:

    • Blocks purge of redo files for storage engines that needs this (Aria)

    • Start logging of DDL commands into 'datadir'/ddl.log. This may take a short time as the command has to wait until there are no active DDL commands.

    BACKUP STAGE FLUSH

    The FLUSH stage is designed for the following tasks:

    • FLUSH all changes for inactive non-transactional tables, except for statistics and log tables.

    • Close all tables that are not in use, to ensure they are marked as closed for the backup.

    • BLOCK all new write locks for all non transactional tables (except statistics and log tables). The command will not wait for tables that are in use by read-only transactions.

    DDLs don't have to be blocked at this stage as they can't cause the table to be in an inconsistent state. This is true also for non-transactional tables.

    BACKUP STAGE BLOCK_DDL

    The BLOCK_DDL stage is designed for the following tasks:

    • Wait for all statements using write locked non-transactional tables to end.

    • Blocks , , , and .

    • Blocks also start off a new and the final rename phase of . Running ALTER TABLES are not blocked.

    BACKUP STAGE BLOCK_COMMIT

    The BLOCK_COMMIT stage is designed for the following tasks:

    • Lock the binary log and commit/rollback to ensure that no changes are committed to any tables. If there are active commits or data to be copied to the binary log this will be allowed to finish. Active transactions will not affect BLOCK_COMMIT.

    • This doesn't lock temporary tables that are not used by replication. However these will be blocked when it's time to write to the binary log.

    • Lock system log tables and statistics tables, flush them and mark them closed.

    When the BLOCK_COMMIT's stages return, this is the 'backup time'. Everything committed will be in the backup and everything not committed will roll back.

    Transactional engines will continue to do changes to the redo log during the BLOCK COMMIT stage, but this is not important as all of these will roll back later as the changes will not be committed.

    BACKUP STAGE END

    The END stage is designed for the following tasks:

    • End DDL logging

    • Free resources

    Using BACKUP STAGE Commands with Backup Tools

    Using BACKUP STAGE Commands with mariadb-backup

    The BACKUP STAGE commands are a set of commands to make it possible to make an efficient external backup tool.

    The BACKUP STAGE commands are a set of commands to make it possible to make an efficient external backup tool. How uses these commands depends on which version you are using. It depends on whether you are using the version that is bundled with MariaDB Community Server or the version that is bundled with .

    The BACKUP STAGE commands are a set of commands to make it possible to make an efficient external backup tool. How uses these commands depends on which version you are using. It depends on whether you are using the version that is bundled with MariaDB Community Server or the version that is bundled with .

    See for some examples on how uses these commands.

    Using BACKUP STAGE Commands with Storage Snapshots

    The BACKUP STAGE commands are a set of commands to make it possible to make an efficient external backup tool. These commands could even be used by tools that perform backups by taking a snapshot of a file system, SAN, or some other kind of storage device. See for some examples on how to use each BACKUP STAGE command in an efficient way.

    Privileges

    BACKUP STAGE requires the privilege.

    Notes

    • Only one connection can run BACKUP STAGE START. If a second connection tries, it will wait until the first one has executed BACKUP STAGE END.

    • If the user skips a BACKUP STAGE, then all intermediate backup stages will automatically be run. This will allow us to add new stages within the BACKUP STAGE hierarchy in the future with even more precise locks without causing problems for tools using an earlier version of the BACKUP STAGE implementation.

    See Also

    • Locking a table from DDL.

    • . Implement BACKUP STAGE for safe external backups.

    This page is licensed: CC BY-SA / Gnu FDL

    SHOW AUTHORS

    Display a list of major contributors to the MariaDB and MySQL projects. View names, locations, and specific contributions of developers.

    Syntax

    SHOW AUTHORS

    Description

    The SHOW AUTHORS statement displays information about the people who work on MariaDB. For each author, it displays Name, Location, and Comment values. All columns are encoded as latin1.

    These include:

    • First the active people in MariaDB are listed.

    • Then the active people in MySQL.

    • Last the people that have contributed to MariaDB/MySQL in the past.

    The order is somewhat related to importance of the contribution given to the MariaDB project, but this is not 100% accurate. There is still room for improvement and debate...

    Example

    See Also

    • . This list and other sponsors.

    This page is licensed: GPLv2, originally from

    SHOW CREATE PROCEDURE

    Get the CREATE PROCEDURE statement. This statement returns the SQL syntax used to define a specific stored procedure.

    Syntax

    Description

    This statement is a MariaDB extension. It returns the exact string that can be used to re-create the named stored procedure, as well as the SQL_MODE that was used when the trigger has been created and the character set used by the connection.. A similar statement, , displays information about .

    Both statements require that:

    • you are the owner of the routine;

    • you have the privilege (from ); or

    • you have the privilege on the table.

    When none of the above statements are true, the statements display NULL for the Create Procedure or Create Function field.

    Users with SELECT privileges on or USAGE privileges on *.* can view the text of routines, even when they do not have privileges for the function or procedure itself.

    SHOW CREATE PROCEDURE quotes identifiers, according to the value of the system variable.

    SHOW CREATE PROCEDURE quotes identifiers, according to the value of the system variable. The output of this statement is unreliably affected by the system variable.

    Examples

    Here's a comparison of the SHOW CREATE PROCEDURE and statements.

    When the user issuing the statement does not have privileges on the routine, attempting to the procedure raises Error 1370.

    If the user neither has privilege to the routine nor the privilege on table, it raises Error 1305, informing them that the procedure does not exist.

    See Also

    This page is licensed: GPLv2, originally from

    SHOW CREATE TABLE

    Get the SQL statement to recreate a table. This statement shows the complete CREATE TABLE syntax, including column definitions and indexes.

    Syntax

    Description

    Shows the CREATE TABLE statement that creates the given table. The statement requires the SELECT privilege for the table. This statement also works with and .

    SHOW CREATE TABLE quotes table and column names according to the value of the server system variable.

    Certain values can result in parts of the original CREATE statement not being included in the output. MariaDB-specific table options, column options, and index options are not included in the output of this statement if the , and flags are used. All MariaDB-specific table attributes are also not shown when a non-MariaDB/MySQL emulation mode is used, which includes , , , , or .

    Invalid table options, column options and index options are normally commented out (note, that it is possible to create a table with invalid options, by altering a table of a different engine, where these options were valid). To have them uncommented, enable the . Remember that replaying a statement with uncommented invalid options will fail with an error, unless the is in effect.

    Note that SHOW CREATE TABLE is not meant to provide metadata about a table. It provides information about how the table was declared, but the real table structure could differ a bit. For example, if an index has been declared as HASH, the CREATE TABLE statement returned by SHOW CREATE TABLE will declare that index as HASH; however, it is possible that the index is in fact a BTREE, because the storage engine does not support HASH.

    MariaDB permits and data types to be assigned a value. As a result, SHOW CREATE TABLE will append a DEFAULT NULL to nullable TEXT or BLOB fields if no specific default is provided.

    Numbers are quoted in the DEFAULT clause in SHOW CREATE statement.

    Numbers are not quoted in the DEFAULT clause in SHOW CREATE statement.

    Index Order

    Indexes are sorted and displayed in the following order, which may differ from the order of the CREATE TABLE statement.

    • PRIMARY KEY

    • UNIQUE keys where all column are NOT NULL

    • UNIQUE keys that don't contain partial segments

    • Other UNIQUE keys

    See sql/sql_table.cc for details.

    Examples

    With off:

    impacting the output:

    See Also

    This page is licensed: GPLv2, originally from

    SHOW PLUGINS

    List installed server plugins. View the name, status, type, and library file for each active plugin.

    Syntax

    Description

    SHOW PLUGINS displays information about installed . The Library column indicates the plugin library - if it is NULL, the plugin is built-in and cannot be uninstalled.

    The table in the information_schema database contains more detailed information.

    For specific information about storage engines (a particular type of plugin), see the table and the statement.

    Examples

    See Also

    This page is licensed: GPLv2, originally from

    SHOW PRIVILEGES

    List available system privileges. View the context and description for each privilege supported by the server.

    Syntax

    Description

    SHOW PRIVILEGES shows the list of that the MariaDB server supports. The exact list of privileges depends on the version of your server.

    SHOW PRIVILEGES shows the list of that the MariaDB server supports. The exact list of privileges depends on the version of your server.

    Note that before , and , the privilege displays as Delete versioning rows ().

    Example

    The output is for MariaDB version from 10.5.9. In previous versions, it might look differently.

    See Also

    • shows how the user was created.

    • shows the GRANTS/PRIVILEGES for a user.

    This page is licensed: GPLv2, originally from

    SET

    Assign values to different types of variables. Learn the syntax for setting user-defined variables, system variables, and stored program variables.

    Syntax

    One can also set a user variable in any expression with this syntax:

    Description

    SET NAMES

    Configure the character set and collation for the current connection. This ensures the server correctly interprets data sent by the client application.

    Syntax

    Description

    Sets the , , and, implicitly, the

    SET TRANSACTION

    Define isolation levels and access modes for transactions. Learn to configure the behavior of the next transaction or the entire session for data consistency.

    Syntax

    Description

    This statement sets the transaction isolation level or the transaction access mode globally, for the current session, or for the next transaction:

    SHOW ANALYZE

    Retrieve runtime statistics for a currently executing query. This statement provides insights into query plan execution without waiting for completion.

    SHOW ANALYZE was added in MariaDB 10.9.

    Syntax

    SHOW ENGINE INNODB STATUS

    View extensive status information for the InnoDB engine. This statement displays details on deadlocks, buffer pool usage, and I/O activity.

    Syntax

    SHOW ENGINE INNODB STATUS is a specific form of the statement that displays the output, which is extensive InnoDB information which can be useful in diagnosing problems.

    The following sections are displayed

    SHOW EXPLAIN

    Get the execution plan for a running query. This statement displays EXPLAIN output for a statement currently executing in another thread.

    Syntax

    Description

    The SHOW EXPLAIN

    "table": {
        "table_name": "t1",
        "access_type": "range",
        "possible_keys": ...,
        "key": "INDEX1",
        ...
        "rowid_filter": {
          ...
          "r_selectivity_pct": n.nnn,
        },
        ...
        "rows": 123,
        "r_rows": 125,
        ...
        "filtered": 8.476269722,
        "r_filtered": 100,
        "index_condition": "cond1",
        "attached_condition": "cond2"
      }
    "table": {
        "table_name": ...,
    
        "rows": 426,
        "r_index_rows": 349,
        "r_rows": 34,
    ...
        "filtered": 8.476269722,
        "r_total_filtered": 9.742120344,
    ...
        "index_condition": "lineitem.l_quantity > 47",
        "r_icp_filtered": 100,
    ...
        "attached_condition": "lineitem.l_shipDATE between '1997-01-01' and '1997-06-30'",
        "r_filtered": 100
    ANALYZE explainable_statement;
    ANALYZE SELECT * FROM tbl1 
    WHERE key1 
      BETWEEN 10 AND 200 AND 
      col1 LIKE 'foo%'\G
    *************************** 1. row ***************************
               id: 1
      select_type: SIMPLE
            table: tbl1
             type: range
    possible_keys: key1
              key: key1
          key_len: 5
              ref: NULL
             rows: 181
           r_rows: 181
         filtered: 100.00
       r_filtered: 10.50
            Extra: Using index condition; Using where
    ANALYZE SELECT *
    FROM orders, customer 
    WHERE
      customer.c_custkey=orders.o_custkey AND
      customer.c_acctbal < 0 AND
      orders.o_totalprice > 200*1000
    +----+-------------+----------+------+---------------+-------------+---------+--------------------+--------+--------+----------+------------+-------------+
    | id | select_type | table    | type | possible_keys | key         | key_len | ref                | rows   | r_rows | filtered | r_filtered | Extra       |
    +----+-------------+----------+------+---------------+-------------+---------+--------------------+--------+--------+----------+------------+-------------+
    |  1 | SIMPLE      | customer | ALL  | PRIMARY,...   | NULL        | NULL    | NULL               | 149095 | 150000 |    18.08 |       9.13 | Using where |
    |  1 | SIMPLE      | orders   | ref  | i_o_custkey   | i_o_custkey | 5       | customer.c_custkey |      7 |     10 |   100.00 |      30.03 | Using where |
    +----+-------------+----------+------+---------------+-------------+---------+--------------------+--------+--------+----------+------------+-------------+
    ANALYZE SELECT * 
    FROM orders, customer 
    WHERE
      customer.c_custkey=orders.o_custkey AND
      customer.c_acctbal < -0 AND 
      customer.c_comment LIKE '%foo%' AND
      orders.o_totalprice > 200*1000;
    +----+-------------+----------+------+---------------+-------------+---------+--------------------+--------+--------+----------+------------+-------------+
    | id | select_type | table    | type | possible_keys | key         | key_len | ref                | rows   | r_rows | filtered | r_filtered | Extra       |
    +----+-------------+----------+------+---------------+-------------+---------+--------------------+--------+--------+----------+------------+-------------+
    |  1 | SIMPLE      | customer | ALL  | PRIMARY,...   | NULL        | NULL    | NULL               | 149095 | 150000 |    18.08 |       0.00 | Using where |
    |  1 | SIMPLE      | orders   | ref  | i_o_custkey   | i_o_custkey | 5       | customer.c_custkey |      7 |   NULL |   100.00 |       NULL | Using where |
    +----+-------------+----------+------+---------------+-------------+---------+--------------------+--------+--------+----------+------------+-------------+
    STOP { SLAVE | REPLICA } ["connection_name"] [thread_type [, thread_type] ... ] 
    [FOR CHANNEL "connection_name"]
    
    STOP ALL { SLAVES | REPLICAS } [thread_type [, thread_type]]
    
    STOP { SLAVE | REPLICA } ["connection_name"] [thread_type [, thread_type] ... ]
    
    STOP ALL { SLAVES | REPLICAS } [thread_type [, thread_type]] 
    
    thread_type: IO_THREAD | SQL_THREAD
    SHOW [FULL] {COLUMNS | FIELDS} FROM tbl_name [FROM db_name]
        [LIKE 'pattern' | WHERE expr]
    SHOW COLUMNS FROM mytable FROM mydb;
    SHOW COLUMNS FROM mydb.mytable;
    mariadb-show db_name tbl_name
    SHOW COLUMNS FROM city;
    +------------+----------+------+-----+---------+----------------+
    | Field      | Type     | Null | Key | Default | Extra          |
    +------------+----------+------+-----+---------+----------------+
    | Id         | int(11)  | NO   | PRI | NULL    | auto_increment |
    | Name       | char(35) | NO   |     |         |                |
    | Country    | char(3)  | NO   | UNI |         |                |
    | District   | char(20) | YES  | MUL |         |                |
    | Population | int(11)  | NO   |     | 0       |                |
    +------------+----------+------+-----+---------+----------------+
    SHOW COLUMNS FROM employees WHERE Type LIKE 'Varchar%';
    +---------------+-------------+------+-----+---------+-------+
    | Field         | Type        | Null | Key | Default | Extra |
    +---------------+-------------+------+-----+---------+-------+
    | first_name    | varchar(30) | NO   | MUL | NULL    |       |
    | last_name     | varchar(40) | NO   |     | NULL    |       |
    | position      | varchar(25) | NO   |     | NULL    |       |
    | home_address  | varchar(50) | NO   |     | NULL    |       |
    | home_phone    | varchar(12) | NO   |     | NULL    |       |
    | employee_code | varchar(25) | NO   | UNI | NULL    |       |
    +---------------+-------------+------+-----+---------+-------+
    SHOW ENGINE [engine-name] {STATUS | MUTEX}
    SHOW ENGINE INNODB STATUS
    SHOW ENGINE INNODB MUTEX
    SHOW ENGINE PERFORMANCE_SCHEMA STATUS
    SHOW ENGINE ROCKSDB STATUS
    SHOW ENGINE SPHINX STATUS
    SHOW [STORAGE] ENGINES
    SHOW ENGINES\G
    *************************** 1. row ***************************
          Engine: InnoDB
         Support: DEFAULT
         Comment: Supports transactions, row-level locking, and foreign keys
    Transactions: YES
              XA: YES
      Savepoints: YES
    *************************** 2. row ***************************
          Engine: CSV
         Support: YES
         Comment: CSV storage engine
    Transactions: NO
              XA: NO
      Savepoints: NO
    *************************** 3. row ***************************
          Engine: MyISAM
         Support: YES
         Comment: MyISAM storage engine
    Transactions: NO
              XA: NO
      Savepoints: NO
    *************************** 4. row ***************************
          Engine: BLACKHOLE
         Support: YES
         Comment: /dev/null storage engine (anything you write to it disappears)
    Transactions: NO
              XA: NO
      Savepoints: NO
    *************************** 5. row ***************************
          Engine: FEDERATED
         Support: YES
         Comment: FederatedX pluggable storage engine
    Transactions: YES
              XA: NO
      Savepoints: YES
    *************************** 6. row ***************************
          Engine: MRG_MyISAM
         Support: YES
         Comment: Collection of identical MyISAM tables
    Transactions: NO
              XA: NO
      Savepoints: NO
    *************************** 7. row ***************************
          Engine: ARCHIVE
         Support: YES
         Comment: Archive storage engine
    Transactions: NO
              XA: NO
      Savepoints: NO
    *************************** 8. row ***************************
          Engine: MEMORY
         Support: YES
         Comment: Hash based, stored in memory, useful for temporary tables
    Transactions: NO
              XA: NO
      Savepoints: NO
    *************************** 9. row ***************************
          Engine: PERFORMANCE_SCHEMA
         Support: YES
         Comment: Performance Schema
    Transactions: NO
              XA: NO
      Savepoints: NO
    *************************** 10. row ***************************
          Engine: Aria
         Support: YES
         Comment: Crash-safe tables with MyISAM heritage
    Transactions: NO
              XA: NO
      Savepoints: NO
    10 rows in set (0.00 sec)
    START REPLICA UNTIL (SQL_BEFORE_GTIDS|SQL_AFTER_GTIDS)="<gtid_list>"
    SHOW PACKAGE BODY STATUS LIKE 'pkg1'\G
    *************************** 1. row ***************************
                      Db: test
                    Name: pkg1
                    Type: PACKAGE BODY
                 Definer: root@localhost
                Modified: 2018-02-27 14:44:14
                 Created: 2018-02-27 14:44:14
           Security_type: DEFINER
                 Comment: This is my first package body
    character_set_client: utf8
    collation_connection: utf8_general_ci
      Database Collation: latin1_swedish_ci
    SHOW INDEX_STATISTICS;
    +--------------+-------------------+------------+-----------+
    | Table_schema | Table_name        | Index_name | Rows_read |
    +--------------+-------------------+------------+-----------+
    | test         | employees_example | PRIMARY    |         1 |
    +--------------+-------------------+------------+-----------+
    BACKUP STAGE [START | FLUSH | BLOCK_DDL | BLOCK_COMMIT | END ]
    SHOW CREATE PROCEDURE proc_name
    SHOW CREATE TABLE tbl_name
    SHOW PLUGINS;
    SHOW PRIVILEGES

    os_yields indicates the number of times a the thread trying to lock a mutex gave up its timeslice and yielded to the operating system (on the presumption that allowing other threads to run will free the mutex so that it can be locked).

  • os_wait_times indicates the amount of time (in ms) spent in operating system waits, if the timed_mutexes system variable is 1 (ON). If timed_mutexes is 0 (OFF), timing is disabled, so os_wait_times is 0. timed_mutexes is off by default.

  • column statistics
    slow query log
    MDEV-6388
    SHOW INDEX
    Extended SHOW
    Silent Column Changes
    transactions
    XA transactions
    transaction savepoints
    SHOW CONTRIBUTORS
    all members and sponsors of the MariaDB Foundation
    fill_help_tables.sql
    LONG UNIQUE keys
  • Normal keys

  • Fulltext keys

  • views
    SEQUENCE
    sql_quote_show_create
    SQL_MODE
    NO_TABLE_OPTIONS
    NO_FIELD_OPTIONS
    NO_KEY_OPTIONS
    SQL_MODE
    ANSI
    DB2
    POSTGRESQL
    MSSQL
    MAXDB
    ORACLE
    IGNORE_BAD_TABLE_OPTIONS
    SQL_MODE
    CREATE TABLE
    IGNORE_BAD_TABLE_OPTIONS
    SQL_MODE
    TEXT
    BLOB
    DEFAULT
    sql_quote_show_create
    SQL_MODE
    SHOW CREATE SEQUENCE
    SHOW CREATE VIEW
    fill_help_tables.sql
    INFORMATION_SCHEMA.ALL_PLUGINS Table (all plugins, installed or not)
  • INSTALL SONAME

  • UNINSTALL PLUGIN

  • UNINSTALL SONAME

  • plugins
    PLUGINS
    information_schema.ENGINES
    SHOW ENGINES
    List of Plugins
    Plugin Overview
    INFORMATION_SCHEMA.PLUGINS Table
    INSTALL PLUGIN
    fill_help_tables.sql
    Description

    SHOW ANALYZE allows one to retrieve ANALYZE-like output from a currently running statement. The statement

    connects to the query running in connection connection_id, gets information about the query plan it is executing, also gets information about the runtime statistics of the execution so far and returns it in a format similar to ANALYZE [FORMAT=JSON] output.

    This is similar to the SHOW EXPLAIN command, the difference being that SHOW ANALYZE also produces runtime statistics information.

    Use Case

    You're trying to troubleshoot a query that never finishes. Since it doesn't finish, it is not possible to get ANALYZE output for it. With SHOW ANALYZE, you can get the runtime statistics without waiting for the query to finish.

    Examples

    Example 1: Row Counts

    Consider the tables orders and customer and a join query finding the total amount of orders from customers with Gold status:

    The output of this query looks like this:

    We run the SELECT, and it has been running for 30 seconds. Let's try SHOW ANALYZE:

    The statement shows how long the query has been running.

    rows shows the number of rows expected. r_rows in shows how many rows were processed so far (110K out of expected 200K). r_loops shows we're doing the first table scan (which is obvious for this query plan).

    rows: 1 shows the optimizer was expecting 1 order per customer. But r_rows: 99.9 shows that it has found on average 100 orders per customer. This may be the reason the query is slower than expected.

    The final chunk of the output doesn't have anything interesting but here it is:

    Example 2: Timing Information

    Regular SELECT queries collect row count information, so SHOW ANALYZE can display it. However, detailed timing information is not collected, as collecting it may have CPU overhead. But if the target query is collecting timing information, SHOW ANALYZE will display it. How does one get the target query to collect timing information? Currently there is one way: if the target is running ANALYZE, it IS collecting timing information. Re-running the previous example:

    ANALYZE prints timing information in members named r_..._time_ms. You can see that, so far, out of 30 seconds, only 232 millisecond were spent in reading the customer table. The bottleneck is elsewhere...

    29.4 seconds were spent reading the orders table (and 0.986 seconds in processing the obtained rows). Now we can see where the query is spending time.

    See Also

    • SHOW EXPLAIN command

    • ANALYZE command

    • MDEV-27021: Extend SHOW EXPLAIN to support SHOW ANALYZE [FORMAT=JSON]

    This page is licensed: CC BY-SA / Gnu FDL

    Status: Shows the timestamp, monitor name and the number of seconds, or the elapsed time between the current time and the time the InnoDB Monitor output was last displayed. The per-second averages are based upon this time.
  • BACKGROUND THREAD: srv_master_thread lines show work performed by the main background thread.

  • SEMAPHORES: Threads waiting for a semaphore and stats on how the number of times threads have needed a spin or a wait on a mutex or rw-lock semaphore. If this number of threads is large, there may be I/O or contention issues. Reducing the size of the innodb_thread_concurrency system variable may help if contention is related to thread scheduling. Spin rounds per wait shows the number of spinlock rounds per OS wait for a mutex.

  • LATEST FOREIGN KEY ERROR: Only shown if there has been a foreign key constraint error, it displays the failed statement and information about the constraint and the related tables.

  • LATEST DETECTED DEADLOCK: Only shown if there has been a deadlock, it displays the transactions involved in the deadlock and the statements being executed, held and required locked and the transaction rolled back to.

  • TRANSACTIONS: The output of this section can help identify lock contention, as well as reasons for the deadlocks.

  • FILE I/O: InnoDB thread information as well as pending I/O operations and I/O performance statistics.

  • INSERT BUFFER AND ADAPTIVE HASH INDEX: InnoDB insert buffer (old name for the change buffer) and adaptive hash index status information, including the number of each type of operation performed, and adaptive hash index performance.

  • LOG: InnoDB log information, including current log sequence number, how far the log has been flushed to disk, the position at which InnoDB last took a checkpoint, pending writes and write performance statistics.

  • BUFFER POOL AND MEMORY: Information on buffer pool pages read and written, which allows you to see the number of data file I/O operations performed by your queries. See InnoDB Buffer Pool for more. Similar information is also available from the INFORMATION_SCHEMA.INNODB_BUFFER_POOL_STATS table.

  • ROW OPERATIONS:Information about the main thread, including the number and performance rate for each type of row operation.

  • If the innodb_status_output_locks system variable is set to 1, extended lock information will be displayed.

    Example output:

    This page is licensed: CC BY-SA / Gnu FDL

    SHOW ENGINE
    InnoDB Monitor
    command allows one to get an
    (that is, a description of a query plan) of a query running in a certain connection.

    will produce an EXPLAIN output for the query that connection number connection_id is running. The connection id can be obtained with SHOW PROCESSLIST.

    The output is always accompanied with a warning which shows the query the target connection is running (this shows what the EXPLAIN is for):

    EXPLAIN FOR CONNECTION

    The EXPLAIN FOR CONNECTION syntax was added for MySQL compatibility.

    FORMAT=JSON

    SHOW EXPLAIN [FORMAT=JSON] FOR <connection_id> extends SHOW EXPLAIN to return more detailed JSON output.

    EXPLAIN FOR CONNECTION and FORMAT=JSON are not available.

    Possible Errors

    The output can be only produced if the target connection is currently running a query, which has a ready query plan. If this is not the case, the output will be:

    You will get this error when:

    • The target connection is not running a command for which one can run EXPLAIN;

    • The target connection is running a command for which one can run EXPLAIN, but there is no query plan yet (for example, tables are open and locks are acquired before the query plan is produced).

    Differences Between SHOW EXPLAIN and EXPLAIN Outputs

    Background

    In MySQL, EXPLAIN execution takes a slightly different route from the way the real query (typically the SELECT) is optimized. This is unfortunate, and has caused a number of bugs in EXPLAIN. (For example, see MDEV-326, MDEV-410, and lp:1013343.lp:992942 is not directly about EXPLAIN, but it also would not have existed if MySQL didn't try to delete parts of a query plan in the middle of the query)

    SHOW EXPLAIN examines a running SELECT, and hence its output may be slightly different from what EXPLAIN SELECT would produce. We did our best to make sure that either the difference is negligible, or SHOW EXPLAIN's output is closer to reality than EXPLAIN's output.

    List of Recorded Differences

    • SHOW EXPLAIN may have Extra='no matching row in const table', where EXPLAIN would produce Extra='Impossible WHERE ...'

    • For queries with subqueries, SHOW EXPLAIN may print select_type==PRIMARY where regular EXPLAIN used to print select_type==SIMPLE, or vice versa.

    Required Permissions

    Running SHOW EXPLAIN requires the same permissions as running SHOW PROCESSLIST would.

    See Also

    • EXPLAIN

    • EXPLAIN ANALYZE, which will perform a query and outputs enhanced EXPLAIN results.

    • SHOW ANALYZE

    • It is also possible to save EXPLAIN into the slow query log.

    This page is licensed: CC BY-SA / Gnu FDL

    EXPLAIN
    SHOW AUTHORS\G
    *************************** 1. row ***************************
        Name: Michael (Monty) Widenius
    Location: Tusby, Finland
     Comment: Lead developer and main author
    *************************** 2. row ***************************
        Name: Sergei Golubchik
    Location: Kerpen, Germany
     Comment: Architect, Full-text search, precision math, plugin framework, merges etc
    *************************** 3. row ***************************
        Name: Igor Babaev
    Location: Bellevue, USA
     Comment: Optimizer, keycache, core work
    *************************** 4. row ***************************
        Name: Sergey Petrunia
    Location: St. Petersburg, Russia
     Comment: Optimizer
    *************************** 5. row ***************************
        Name: Oleksandr Byelkin
    Location: Lugansk, Ukraine
     Comment: Query Cache (4.0), Subqueries (4.1), Views (5.0)
    *************************** 6. row ***************************
        Name: Timour Katchaounov
    Location: Sofia , Bulgaria
     Comment: Optimizer
    *************************** 7. row ***************************
        Name: Kristian Nielsen
    Location: Copenhagen, Denmark
     Comment: Replication, Async client prototocol, General buildbot stuff
    *************************** 8. row ***************************
        Name: Alexander (Bar) Barkov
    Location: Izhevsk, Russia
     Comment: Unicode and character sets
    *************************** 9. row ***************************
        Name: Alexey Botchkov (Holyfoot)
    Location: Izhevsk, Russia
     Comment: GIS extensions, embedded server, precision math
    *************************** 10. row ***************************
        Name: Daniel Bartholomew
    Location: Raleigh, USA
     Comment: MariaDB documentation, Buildbot, releases
    *************************** 11. row ***************************
        Name: Colin Charles
    Location: Selangor, Malesia
     Comment: MariaDB documentation, talks at a LOT of conferences
    *************************** 12. row ***************************
        Name: Sergey Vojtovich
    Location: Izhevsk, Russia
     Comment: initial implementation of plugin architecture, maintained native storage engines (MyISAM, MEMORY, ARCHIVE, etc), rewrite of table cache
    *************************** 13. row ***************************
        Name: Vladislav Vaintroub
    Location: Mannheim, Germany
     Comment: MariaDB Java connector, new thread pool, Windows optimizations
    *************************** 14. row ***************************
        Name: Elena Stepanova
    Location: Sankt Petersburg, Russia
     Comment: QA, test cases
    *************************** 15. row ***************************
        Name: Georg Richter
    Location: Heidelberg, Germany
     Comment: New LGPL C connector, PHP connector
    *************************** 16. row ***************************
        Name: Jan Lindström
    Location: Ylämylly, Finland
     Comment: Working on InnoDB
    *************************** 17. row ***************************
        Name: Lixun Peng
    Location: Hangzhou, China
     Comment: Multi Source replication
    *************************** 18. row ***************************
        Name: Olivier Bertrand
    Location: Paris, France
     Comment: CONNECT storage engine
    *************************** 19. row ***************************
        Name: Kentoku Shiba
    Location: Tokyo, Japan
     Comment: Spider storage engine, metadata_lock_info Information schema
    *************************** 20. row ***************************
        Name: Percona
    Location: CA, USA
     Comment: XtraDB, microslow patches, extensions to slow log
    *************************** 21. row ***************************
        Name: Vicentiu Ciorbaru
    Location: Bucharest, Romania
     Comment: Roles
    *************************** 22. row ***************************
        Name: Sudheera Palihakkara
    Location: 
     Comment: PCRE Regular Expressions
    *************************** 23. row ***************************
        Name: Pavel Ivanov
    Location: USA
     Comment: Some patches and bug fixes
    *************************** 24. row ***************************
        Name: Konstantin Osipov
    Location: Moscow, Russia
     Comment: Prepared statements (4.1), Cursors (5.0), GET_LOCK (10.0)
    *************************** 25. row ***************************
        Name: Ian Gilfillan
    Location: South Africa
     Comment: MariaDB documentation
    *************************** 26. row ***************************
        Name: Federico Razolli
    Location: Italy
     Comment: MariaDB documentation Italian translation
    *************************** 27. row ***************************
        Name: Guilhem Bichot
    Location: Bordeaux, France
     Comment: Replication (since 4.0)
    *************************** 28. row ***************************
        Name: Andrei Elkin
    Location: Espoo, Finland
     Comment: Replication
    *************************** 29. row ***************************
        Name: Dmitri Lenev
    Location: Moscow, Russia
     Comment: Time zones support (4.1), Triggers (5.0)
    *************************** 30. row ***************************
        Name: Marc Alff
    Location: Denver, CO, USA
     Comment: Signal, Resignal, Performance schema
    *************************** 31. row ***************************
        Name: Mikael Ronström
    Location: Stockholm, Sweden
     Comment: NDB Cluster, Partitioning, online alter table
    *************************** 32. row ***************************
        Name: Ingo Strüwing
    Location: Berlin, Germany
     Comment: Bug fixing in MyISAM, Merge tables etc
    *************************** 33. row ***************************
        Name: Marko Mäkelä
    Location: Helsinki, Finland
     Comment: InnoDB core developer
    ...
    SHOW CREATE TABLE t\G
    *************************** 1. row ***************************
           Table: t
    Create Table: CREATE TABLE `t` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `s` char(60) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1
    SHOW CREATE TABLE t\G
    *************************** 1. row ***************************
           Table: t
    Create Table: CREATE TABLE t (
      id int(11) NOT NULL AUTO_INCREMENT,
      s char(60) DEFAULT NULL,
      PRIMARY KEY (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1
    SELECT @@sql_mode;
    +-------------------------------------------------------------------------------------------+
    | @@sql_mode                                                                                |
    +-------------------------------------------------------------------------------------------+
    | STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION |
    +-------------------------------------------------------------------------------------------+
    
    CREATE TABLE `t1` (
           `id` int(11) NOT NULL AUTO_INCREMENT,
           `msg` varchar(100) DEFAULT NULL,
           PRIMARY KEY (`id`)
         ) ENGINE=InnoDB DEFAULT CHARSET=latin1
    ;
    
    SHOW CREATE TABLE t1\G
    *************************** 1. row ***************************
           Table: t1
    Create Table: CREATE TABLE `t1` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `msg` varchar(100) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1
    
    SET SQL_MODE=ORACLE;
    
    SHOW CREATE TABLE t1\G
    *************************** 1. row ***************************
           Table: t1
    Create Table: CREATE TABLE "t1" (
      "id" int(11) NOT NULL,
      "msg" varchar(100) DEFAULT NULL,
      PRIMARY KEY ("id")
    SHOW PLUGINS;
    +----------------------------+----------+--------------------+-------------+---------+
    | Name                       | Status   | Type               | Library     | License |
    +----------------------------+----------+--------------------+-------------+---------+
    | binlog                     | ACTIVE   | STORAGE ENGINE     | NULL        | GPL     |
    | mysql_native_password      | ACTIVE   | AUTHENTICATION     | NULL        | GPL     |
    | mysql_old_password         | ACTIVE   | AUTHENTICATION     | NULL        | GPL     |
    | MRG_MyISAM                 | ACTIVE   | STORAGE ENGINE     | NULL        | GPL     |
    | MyISAM                     | ACTIVE   | STORAGE ENGINE     | NULL        | GPL     |
    | CSV                        | ACTIVE   | STORAGE ENGINE     | NULL        | GPL     |
    | MEMORY                     | ACTIVE   | STORAGE ENGINE     | NULL        | GPL     |
    | FEDERATED                  | ACTIVE   | STORAGE ENGINE     | NULL        | GPL     |
    | PERFORMANCE_SCHEMA         | ACTIVE   | STORAGE ENGINE     | NULL        | GPL     |
    | Aria                       | ACTIVE   | STORAGE ENGINE     | NULL        | GPL     |
    | InnoDB                     | ACTIVE   | STORAGE ENGINE     | NULL        | GPL     |
    | INNODB_TRX                 | ACTIVE   | INFORMATION SCHEMA | NULL        | GPL     |
    ...
    | INNODB_SYS_FOREIGN         | ACTIVE   | INFORMATION SCHEMA | NULL        | GPL     |
    | INNODB_SYS_FOREIGN_COLS    | ACTIVE   | INFORMATION SCHEMA | NULL        | GPL     |
    | SPHINX                     | ACTIVE   | STORAGE ENGINE     | NULL        | GPL     |
    | ARCHIVE                    | ACTIVE   | STORAGE ENGINE     | NULL        | GPL     |
    | BLACKHOLE                  | ACTIVE   | STORAGE ENGINE     | NULL        | GPL     |
    | FEEDBACK                   | DISABLED | INFORMATION SCHEMA | NULL        | GPL     |
    | partition                  | ACTIVE   | STORAGE ENGINE     | NULL        | GPL     |
    | pam                        | ACTIVE   | AUTHENTICATION     | auth_pam.so | GPL     |
    +----------------------------+----------+--------------------+-------------+---------+
    SHOW ANALYZE [FORMAT=JSON] FOR <connection_id>;
    SHOW ANALYZE [FORMAT=JSON] FOR <connection_id>;
    EXPLAIN format=json
    SELECT sum(orders.amount)
    FROM
      customer JOIN orders ON customer.cust_id=orders.cust_id
    WHERE
      customer.status='GOLD';
    +------+-------------+----------+------+---------------+---------+---------+------------------+--------+-------------+
    | id   | select_type | table    | type | possible_keys | key     | key_len | ref              | rows   | Extra       |
    +------+-------------+----------+------+---------------+---------+---------+------------------+--------+-------------+
    |    1 | SIMPLE      | customer | ALL  | PRIMARY       | NULL    | NULL    | NULL             | 199786 | Using where |
    |    1 | SIMPLE      | orders   | ref  | cust_id       | cust_id | 5       | customer.cust_id | 1      |             |
    +------+-------------+----------+------+---------------+---------+---------+------------------+--------+-------------+
    SHOW ANALYZE format=json FOR 3;
    | {
      "r_query_time_in_progress_ms": 32138,
    "query_block": {
        "select_id": 1,
        "r_loops": 1,
        "nested_loop": [
          {
            "table": {
              "table_name": "customer",
              "access_type": "ALL",
              "possible_keys": ["PRIMARY"],
              "r_loops": 1,
              "rows": 199786,
              "r_rows": 110544,
    "filtered": 100,
              "r_filtered": 9.538283398,
              "attached_condition": "customer.`status` = 'GOLD'"
            }
          },
          {
            "table": {
              "table_name": "orders",
              "access_type": "ref",
              "possible_keys": ["cust_id"],
              "key": "cust_id",
              "key_length": "5",
              "used_key_parts": ["cust_id"],
              "ref": ["test.customer.cust_id"],
              "r_loops": 10544,
              "rows": 1,
              "r_rows": 99.99222307,
    "filtered": 100,
              "r_filtered": 100
            }
          }
        ]
      }
    }
    Connection 1> ANALYZE SELECT ... ;
    Connection 2> SHOW ANALYZE FORMAT=JSON FOR <connection_id>;
    ANALYZE
    {
      "r_query_time_in_progress_ms": 30727,
      "query_block": {
        "select_id": 1,
        "r_loops": 1,
        "nested_loop": [
          {
            "table": {
              "table_name": "customer",
              "access_type": "ALL",
              "possible_keys": ["PRIMARY"],
              "r_loops": 1,
              "rows": 199786,
              "r_rows": 109994,
              "r_table_time_ms": 232.699,
              "r_other_time_ms": 46.355,
    "filtered": 100,
              "r_filtered": 9.085950143,
              "attached_condition": "customer.`status` = 'GOLD'"
            }
          },
          {
            "table": {
              "table_name": "orders",
              "access_type": "ref",
              "possible_keys": ["cust_id"],
              "key": "cust_id",
              "key_length": "5",
              "used_key_parts": ["cust_id"],
              "ref": ["test.customer.cust_id"],
              "r_loops": 9994,
              "rows": 1,
              "r_rows": 99.99779868,
              "r_table_time_ms": 29460.609,
              "r_other_time_ms": 986.842,
    "filtered": 100,
              "r_filtered": 100
            }
          }
        ]
      }
    }
    SHOW ENGINE INNODB STATUS
    =====================================
    2019-09-06 12:44:13 0x7f93cc236700 INNODB MONITOR OUTPUT
    =====================================
    Per second averages calculated from the last 4 seconds
    -----------------
    BACKGROUND THREAD
    -----------------
    srv_master_thread loops: 2 srv_active, 0 srv_shutdown, 83698 srv_idle
    srv_master_thread log flush and writes: 83682
    ----------
    SEMAPHORES
    ----------
    OS WAIT ARRAY INFO: reservation count 15
    OS WAIT ARRAY INFO: signal count 8
    RW-shared spins 0, rounds 20, OS waits 7
    RW-excl spins 0, rounds 0, OS waits 0
    RW-sx spins 0, rounds 0, OS waits 0
    Spin rounds per wait: 20.00 RW-shared, 0.00 RW-excl, 0.00 RW-sx
    ------------
    TRANSACTIONS
    ------------
    Trx id counter 236
    Purge done for trx's n:o < 236 undo n:o < 0 state: running
    History list length 22
    LIST OF TRANSACTIONS FOR EACH SESSION:
    ---TRANSACTION 421747401994584, not started
    0 lock struct(s), heap size 1136, 0 row lock(s)
    ---TRANSACTION 421747401990328, not started
    0 lock struct(s), heap size 1136, 0 row lock(s)
    --------
    FILE I/O
    --------
    I/O thread 0 state: waiting for completed aio requests (insert buffer thread)
    I/O thread 1 state: waiting for completed aio requests (log thread)
    I/O thread 2 state: waiting for completed aio requests (read thread)
    I/O thread 3 state: waiting for completed aio requests (read thread)
    I/O thread 4 state: waiting for completed aio requests (read thread)
    I/O thread 5 state: waiting for completed aio requests (read thread)
    I/O thread 6 state: waiting for completed aio requests (write thread)
    I/O thread 7 state: waiting for completed aio requests (write thread)
    I/O thread 8 state: waiting for completed aio requests (write thread)
    I/O thread 9 state: waiting for completed aio requests (write thread)
    Pending normal aio reads: [0, 0, 0, 0] , aio writes: [0, 0, 0, 0] ,
     ibuf aio reads:, log i/o's:, sync i/o's:
    Pending flushes (fsync) log: 0; buffer pool: 0
    286 OS file reads, 171 OS file writes, 22 OS fsyncs
    0.00 reads/s, 0 avg bytes/read, 0.00 writes/s, 0.00 fsyncs/s
    -------------------------------------
    INSERT BUFFER AND ADAPTIVE HASH INDEX
    -------------------------------------
    Ibuf: size 1, free list len 0, seg size 2, 0 merges
    merged operations:
     insert 0, delete mark 0, delete 0
    discarded operations:
     insert 0, delete mark 0, delete 0
    Hash table size 34679, node heap has 0 buffer(s)
    Hash table size 34679, node heap has 0 buffer(s)
    Hash table size 34679, node heap has 0 buffer(s)
    Hash table size 34679, node heap has 0 buffer(s)
    Hash table size 34679, node heap has 0 buffer(s)
    Hash table size 34679, node heap has 0 buffer(s)
    Hash table size 34679, node heap has 0 buffer(s)
    Hash table size 34679, node heap has 0 buffer(s)
    0.00 hash searches/s, 0.00 non-hash searches/s
    ---
    LOG
    ---
    Log sequence number 445926
    Log flushed up to   445926
    Pages flushed up to 445926
    Last checkpoint at  445917
    0 pending log flushes, 0 pending chkp writes
    18 log i/o's done, 0.00 log i/o's/second
    ----------------------
    BUFFER POOL AND MEMORY
    ----------------------
    Total large memory allocated 167772160
    Dictionary memory allocated 50768
    Buffer pool size   8012
    Free buffers       7611
    Database pages     401
    Old database pages 0
    Modified db pages  0
    Percent of dirty pages(LRU & free pages): 0.000
    Max dirty pages percent: 75.000
    Pending reads 0
    Pending writes: LRU 0, flush list 0, single page 0
    Pages made young 0, not young 0
    0.00 youngs/s, 0.00 non-youngs/s
    Pages read 264, created 137, written 156
    0.00 reads/s, 0.00 creates/s, 0.00 writes/s
    No buffer pool page gets since the last printout
    Pages read ahead 0.00/s, evicted without access 0.00/s, Random read ahead 0.00/s
    LRU len: 401, unzip_LRU len: 0
    I/O sum[0]:cur[0], unzip sum[0]:cur[0]
    --------------
    ROW OPERATIONS
    --------------
    0 queries inside InnoDB, 0 queries in queue
    0 read views open inside InnoDB
    Process ID=4267, Main thread ID=140272021272320, state: sleeping
    Number of rows inserted 1, updated 0, deleted 0, read 1
    0.00 inserts/s, 0.00 updates/s, 0.00 deletes/s, 0.00 reads/s
    Number of system rows inserted 0, updated 0, deleted 0, read 0
    0.00 inserts/s, 0.00 updates/s, 0.00 deletes/s, 0.00 reads/s
    ----------------------------
    END OF INNODB MONITOR OUTPUT
    ============================
    SHOW EXPLAIN [FORMAT=JSON] FOR <connection_id>;
    EXPLAIN [FORMAT=JSON] FOR CONNECTION <connection_id>;
    SHOW EXPLAIN FOR <connection_id>;
    SHOW EXPLAIN FOR 1;
    +------+-------------+-------+-------+---------------+------+---------+------+---------+-------------+
    | id   | select_type | table | type  | possible_keys | key  | key_len | ref  | rows    | Extra       |
    +------+-------------+-------+-------+---------------+------+---------+------+---------+-------------+
    |    1 | SIMPLE      | tbl   | index | NULL          | a    | 5       | NULL | 1000107 | Using index |
    +------+-------------+-------+-------+---------------+------+---------+------+---------+-------------+
    1 row in set, 1 warning (0.00 sec)
    SHOW WARNINGS;
    +-------+------+------------------------+
    | Level | Code | Message                |
    +-------+------+------------------------+
    | Note  | 1003 | select sum(a) from tbl |
    +-------+------+------------------------+
    1 row in set (0.00 sec)
    SHOW EXPLAIN FOR 2;
    ERROR 1932 (HY000): Target is not running an EXPLAINable command

    Should work efficiently with backup tools that use disk snapshots.

  • Should work as efficiently as possible for all table types that store data on the local disks.

  • As little copying as possible under higher level stages/locks. For example, .frm (dictionary) and .trn (trigger) files should be copying while copying the table data.

  • One can use the max_statement_time or lock_wait_timeout system variables to ensure that a BACKUP STAGE command doesn't block the server too long.

  • DDL logging is only be available from MariaDB 10.11.8, , and , or in MariaDB Enterprise Server.

  • A disconnect will automatically release backup stages.

  • There is no easy way to see which is the current stage.

  • mariadb-backup
    CREATE TABLE
    DROP TABLE
    TRUNCATE TABLE
    RENAME TABLE
    ALTER TABLE
    ALTER TABLE
    mariadb-backup
    MariaDB Enterprise Server
    mariadb-backup
    MariaDB Enterprise Server
    mariadb-backup and BACKUP STAGE Commands
    mariadb-backup
    Storage Snapshots and BACKUP STAGE Commands
    RELOAD
    BACKUP LOCK
    MDEV-5336
    SHOW PROCEDURE STATUS
  • Stored Routine Privileges

  • Information Schema ROUTINES Table

  • SHOW CREATE FUNCTION
    stored functions
    SHOW CREATE ROUTINE
    SELECT
    mysql.proc
    mysql.proc
    sql_quote_show_create
    sql_quote_show_create
    sql_quote_show_create
    SHOW CREATE FUNCTION
    CALL
    SELECT
    mysql.proc
    Stored Procedure Overview
    CREATE PROCEDURE
    ALTER PROCEDURE
    DROP PROCEDURE
    fill_help_tables.sql

    The SET statement assigns values to different types of variables that affect the operation of the server or your client.

    The SET statement assigns values to different types of variables that affect the operation of the server or your client. Older versions of MySQL employed SET OPTION, but this syntax was deprecated in favor of SET without OPTION.

    Changing a system variable by using the SET statement does not make the change permanently. To do so, the change must be made in a configuration file.

    For setting variables on a per-query basis, see SET STATEMENT.

    See SHOW VARIABLES for documentation on viewing server system variables.

    See Server System Variables for a list of all the system variables.

    GLOBAL / SESSION

    When setting a system variable, the scope can be specified as either GLOBAL or SESSION.

    A global variable change affects all new sessions. It does not affect any currently open sessions, including the one that made the change.

    A session variable change affects the current session only.

    If the variable has a session value, not specifying either GLOBAL or SESSION will be the same as specifying SESSION. If the variable only has a global value, not specifying GLOBAL or SESSION will apply to the change to the global value.

    DEFAULT

    Setting a global variable to DEFAULT will restore it to the server default, and setting a session variable to DEFAULT will restore it to the current global value.

    Examples

    • innodb_sync_spin_loops is a global variable.

    • skip_parallel_replication is a session variable.

    • max_error_count is both global and session.

    Setting the session values:

    Setting the global values:

    SHOW VARIABLES will by default return the session value unless the variable is global only.

    Using the inplace syntax:

    See Also

    • Using last_value() to return data of used rows

    • SET STATEMENT

    • SET Variable

    • SET Data Type

    This page is licensed: GPLv2, originally from fill_help_tables.sql

    session system variables to the specified character set and collation.

    This determines which character set the client will use to send statements to the server, and the server will use for sending results back to the client.

    ucs2, utf16, utf16le and utf32 are not valid character sets for SET NAMES, as they cannot be used as client character sets.

    The collation clause is optional. If not defined (or if DEFAULT is specified), the default collation for the character set will be used.

    Quotes are optional for the character set or collation clauses.

    Examples

    utf8mb4 is the default for the affected variables:

    SET NAMES DEFAULT;                
    
    SELECT VARIABLE_NAME, SESSION_VALUE 
        FROM INFORMATION_SCHEMA.SYSTEM_VARIABLES WHERE 
        VARIABLE_NAME LIKE 'character_set_con%' OR 
        VARIABLE_NAME LIKE 'character_set_cl%' OR 
        VARIABLE_NAME LIKE
    

    The utf8 character set (and related collations) is an alias for utf8mb3 , rather than the other way around. MariaDB 11.4 added the character_set_collations variable, so the SELECT query is more specific in this example:

    SELECT VARIABLE_NAME, SESSION_VALUE 
        FROM INFORMATION_SCHEMA.SYSTEM_VARIABLES WHERE 
        VARIABLE_NAME LIKE 'character_set_con%' OR 
        VARIABLE_NAME LIKE 'character_set_cl%' OR 
        VARIABLE_NAME LIKE 'character_set_re%' OR 
        VARIABLE_NAME 
    

    The utf8 character set (and related collation) is the default for the given variables:

    See Also

    • SET CHARACTER SET

    • Setting Character Sets and Collations

    • Character Sets and Collations

    This page is licensed: CC BY-SA / Gnu FDL

    character_set_client
    character_set_connection
    character_set_results
    collation_connection
  • With the GLOBAL keyword, the statement sets the default transaction level globally for all subsequent sessions. Existing sessions are unaffected.

  • With the SESSION keyword, the statement sets the default transaction level for all subsequent transactions performed within the current session.

  • Without any SESSION or GLOBAL keyword, the statement sets the isolation level for only the next (not started) transaction performed within the current session. After that it reverts to using the session value.

  • A change to the global default isolation level requires the SUPER privilege. Any session is free to change its session isolation level (even in the middle of a transaction), or the isolation level for its next transaction.

    Isolation Level

    To set the global default isolation level at server startup, use the --transaction-isolation=level option on the command line or in an option file. Values of level for this option use dashes rather than spaces, so the allowable values are READ_UNCOMMITTED,READ-COMMITTED, REPEATABLE-READ, or SERIALIZABLE. For example, to set the default isolation level to REPEATABLE READ, use these lines in the [mariadb] section of an option file:

    To determine the global and session transaction isolation levels at runtime, check the value of the transaction_isolation variable.

    To determine the global and session transaction isolation levels at runtime, check the value of the tx_isolation system variable.

    InnoDB supports each of the translation isolation levels described here using different locking strategies. The default level isREPEATABLE READ. For additional information about InnoDB record-level locks and how it uses them to execute various types of statements, see InnoDB Lock Modes, and innodb-locks-set.html.

    Isolation Levels

    The following sections describe how MariaDB supports the different transaction levels.

    READ UNCOMMITTED

    SELECT statements are performed in a non-locking fashion, but a possible earlier version of a row might be used. Thus, using this isolation level, such reads are not consistent. This is also called a "dirty read". Otherwise, this isolation level works likeREAD COMMITTED.

    READ COMMITTED

    A somewhat Oracle-like isolation level with respect to consistent (non-locking) reads: Each consistent read, even within the same transaction, sets and reads its own fresh snapshot. See innodb-consistent-read.html.

    For locking reads (SELECT with FOR UPDATE or LOCK IN SHARE MODE), InnoDB locks only index records, not the gaps before them, and thus allows the free insertion of new records next to locked records. For UPDATE and DELETE statements, locking depends on whether the statement uses a unique index with a unique search condition (such as WHERE id = 100), or a range-type search condition (such as WHERE id > 100). For a unique index with a unique search condition, InnoDB locks only the index record found, not the gap before it. For range-type searches, InnoDB locks the index range scanned, using gap locks or next-key (gap plus index-record) locks to block insertions by other sessions into the gaps covered by the range. This is necessary because "phantom rows" must be blocked for MariaDB replication and recovery to work.

    If the READ COMMITTED isolation level is used or the innodb_locks_unsafe_for_binlog system variable is enabled, there is no InnoDB gap locking except for foreign-key constraint checking and duplicate-key checking. Also, record locks for non-matching rows are released after MariaDB has evaluated the WHERE condition. If you use READ COMMITTED or enable innodb_locks_unsafe_for_binlog, you must use row-based binary logging.

    Rows that don't match are not being locked in a so called semiconsistent read. This means you might see only a partially consistent read when the transaction isolation level is READ COMMITTED or READ UNCOMMITTED.

    (A semiconsistent read applies to UPDATE and DELETE statements. Those statements skip locked rows, provided the version in the current read does not match the WHERE condition. Also, if the latest version of a record was successfully locked, but found not to match the condition, the lock is released.)

    REPEATABLE READ

    This is the default isolation level for InnoDB. For consistent reads, there is an important difference from the READ COMMITTED isolation level: All consistent reads within the same transaction read the snapshot established by the first read. This convention means that if you issue several plain (non-locking) SELECT statements within the same transaction, these SELECT statements are consistent also with respect to each other. See innodb-consistent-read.html.

    For locking reads (SELECT with FOR UPDATE or LOCK IN SHARE MODE), UPDATE, and DELETE statements, locking depends on whether the statement uses a unique index with a unique search condition, or a range-type search condition. MariaDB does not relax the gap locking for unique indexes.

    For locking reads (SELECT with FOR UPDATE or LOCK IN SHARE MODE), UPDATE, and DELETE statements, locking depends on whether the statement uses a unique index with a unique search condition, or a range-type search condition. For a unique index with a unique search condition, InnoDB locks only the index record found, not the gap before it.

    For other search conditions, InnoDB locks the index range scanned, using gap locks or next-key (gap plus index-record) locks to block insertions by other sessions into the gaps covered by the range.

    This is the minimum isolation level for non-distributed XA transactions.

    SERIALIZABLE

    This level is like REPEATABLE READ, but InnoDB implicitly converts all plain SELECT statements to SELECT ... LOCK IN SHARE MODE if autocommit is disabled. If autocommit is enabled, the SELECT is its own transaction. It therefore is known to be read only and can be serialized if performed as a consistent (non-locking) read and need not block for other transactions. (This means that to force a plain SELECT to block if other transactions have modified the selected rows, you should disable autocommit.)

    Distributed XA transactions should always use this isolation level.

    innodb_snapshop_isolation

    If the innodb_snapshot_isolation system variable is not set to ON, strictly-speaking anything other than READ UNCOMMITTED is not clearly defined. innodb_snapshot_isolation defaults to OFF for backwards compatibility. Setting to ON will result in attempts to acquire a lock on a record that does not exist in the current read view raising an error, and the transaction being rolled back.

    If the innodb_snapshot_isolation system variable is not set to ON, strictly-speaking anything other than READ UNCOMMITTED is not clearly defined.

    Access Mode

    The access mode specifies whether the transaction is allowed to write data or not. By default, transactions are in READ WRITE mode (see the tx_read_only system variable). READ ONLY mode allows the storage engine to apply optimizations that cannot be used for transactions which write data. Note that, unlike the global read_only mode, the READ_ONLY ADMIN privilege doesn't allow writes, and DDL statements on temporary tables are not allowed either.

    The access mode specifies whether the transaction is allowed to write data or not. By default, transactions are in READ WRITE mode (see the tx_read_only system variable). READ ONLY mode allows the storage engine to apply optimizations that cannot be used for transactions which write data. Note that, unlike the global read_only mode, the SUPER privilege doesn't allow writes, and DDL statements on temporary tables are not allowed either.

    It is not permitted to specify both READ WRITE and READ ONLY in the same statement.

    READ WRITE and READ ONLY can also be specified in the START TRANSACTION statement, in which case the specified mode is only valid for one transaction.

    Examples

    Attempting to set the isolation level within an existing transaction without specifying GLOBAL or SESSION.

    This page is licensed: GPLv2, originally from fill_help_tables.sql

    system privileges
    system privileges
    Delete history
    MDEV-20382
    SHOW CREATE USER
    SHOW GRANTS
    fill_help_tables.sql

    SHOW INDEX

    List index information for a table. View key names, column sequences, cardinality, and other index attributes.

    Syntax

    Description

    SHOW INDEX returns table index information. The format resembles that of the SQLStatistics call in ODBC.

    SHOW CREATE PROCEDURE test.simpleproc\G
    *************************** 1. row ***************************
               Procedure: simpleproc
                sql_mode: 
        Create Procedure: CREATE PROCEDURE `simpleproc`(OUT param1 INT)
                          BEGIN
                          SELECT COUNT(*) INTO param1 FROM t;
                          END
    character_set_client: latin1
    collation_connection: latin1_swedish_ci
      Database Collation: latin1_swedish_ci
    
    SHOW CREATE FUNCTION test.hello\G
    *************************** 1. row ***************************
                Function: hello
                sql_mode:
         Create Function: CREATE FUNCTION `hello`(s CHAR(20))
                          RETURNS CHAR(50)
                          RETURN CONCAT('Hello, ',s,'!')
    character_set_client: latin1
    collation_connection: latin1_swedish_ci
      Database Collation: latin1_swedish_ci
    CALL test.prc1();
    Error 1370 (42000): execute command denied to 
      user 'test_user'@'localhost' for routine 'test'.'prc1'
    SHOW CREATE TABLES test.prc1\G
    Error 1305 (42000): PROCEDURE prc1 does not exist
    SET variable_assignment [, variable_assignment] ...
    
    variable_assignment:
          user_var_name = expr
        | [GLOBAL | SESSION] system_var_name = expr
        | [@@global. | @@session. | @@]system_var_name = expr
    user_var_name:= expr
    SELECT VARIABLE_NAME, SESSION_VALUE, GLOBAL_VALUE FROM
     INFORMATION_SCHEMA.SYSTEM_VARIABLES WHERE 
      VARIABLE_NAME IN ('max_error_count', 'skip_parallel_replication', 'innodb_sync_spin_loops');
    +---------------------------+---------------+--------------+
    | VARIABLE_NAME             | SESSION_VALUE | GLOBAL_VALUE |
    +---------------------------+---------------+--------------+
    | MAX_ERROR_COUNT           | 64            | 64           |
    | SKIP_PARALLEL_REPLICATION | OFF           | NULL         |
    | INNODB_SYNC_SPIN_LOOPS    | NULL          | 30           |
    +---------------------------+---------------+--------------+
    SET max_error_count=128;Query OK, 0 rows affected (0.000 sec)
    
    SET skip_parallel_replication=ON;Query OK, 0 rows affected (0.000 sec)
    
    SET innodb_sync_spin_loops=60;
    ERROR 1229 (HY000): Variable 'innodb_sync_spin_loops' is a GLOBAL variable 
      and should be set with SET GLOBAL
    
    SELECT VARIABLE_NAME, SESSION_VALUE, GLOBAL_VALUE FROM
     INFORMATION_SCHEMA.SYSTEM_VARIABLES WHERE 
      VARIABLE_NAME IN ('max_error_count', 'skip_parallel_replication', 'innodb_sync_spin_loops');
    +---------------------------+---------------+--------------+
    | VARIABLE_NAME             | SESSION_VALUE | GLOBAL_VALUE |
    +---------------------------+---------------+--------------+
    | MAX_ERROR_COUNT           | 128           | 64           |
    | SKIP_PARALLEL_REPLICATION | ON            | NULL         |
    | INNODB_SYNC_SPIN_LOOPS    | NULL          | 30           |
    +---------------------------+---------------+--------------+
    SET GLOBAL max_error_count=256;
    
    SET GLOBAL skip_parallel_replication=ON;
    ERROR 1228 (HY000): Variable 'skip_parallel_replication' is a SESSION variable 
      and can't be used with SET GLOBAL
    
    SET GLOBAL innodb_sync_spin_loops=120;
    
    SELECT VARIABLE_NAME, SESSION_VALUE, GLOBAL_VALUE FROM
     INFORMATION_SCHEMA.SYSTEM_VARIABLES WHERE 
      VARIABLE_NAME IN ('max_error_count', 'skip_parallel_replication', 'innodb_sync_spin_loops');
    +---------------------------+---------------+--------------+
    | VARIABLE_NAME             | SESSION_VALUE | GLOBAL_VALUE |
    +---------------------------+---------------+--------------+
    | MAX_ERROR_COUNT           | 128           | 256          |
    | SKIP_PARALLEL_REPLICATION | ON            | NULL         |
    | INNODB_SYNC_SPIN_LOOPS    | NULL          | 120          |
    +---------------------------+---------------+--------------+
    SHOW VARIABLES LIKE 'max_error_count';
    +-----------------+-------+
    | Variable_name   | Value |
    +-----------------+-------+
    | max_error_count | 128   |
    +-----------------+-------+
    
    SHOW VARIABLES LIKE 'skip_parallel_replication';
    +---------------------------+-------+
    | Variable_name             | Value |
    +---------------------------+-------+
    | skip_parallel_replication | ON    |
    +---------------------------+-------+
    
    SHOW VARIABLES LIKE 'innodb_sync_spin_loops';
    +------------------------+-------+
    | Variable_name          | Value |
    +------------------------+-------+
    | innodb_sync_spin_loops | 120   |
    +------------------------+-------+
    SELECT (@a:=1);
    +---------+
    | (@a:=1) |
    +---------+
    |       1 |
    +---------+
    
    SELECT @a;
    +------+
    | @a   |
    +------+
    |    1 |
    +------+
    SELECT VARIABLE_NAME, SESSION_VALUE 
      FROM INFORMATION_SCHEMA.SYSTEM_VARIABLES WHERE 
      VARIABLE_NAME LIKE 'character_set_c%' OR 
      VARIABLE_NAME LIKE 'character_set_re%' OR 
      VARIABLE_NAME LIKE 'collation_c%';
    +--------------------------+-----------------+
    | VARIABLE_NAME            | SESSION_VALUE   |
    +--------------------------+-----------------+
    | CHARACTER_SET_RESULTS    | utf8            |
    | CHARACTER_SET_CONNECTION | utf8            |
    | CHARACTER_SET_CLIENT     | utf8            |
    | COLLATION_CONNECTION     | utf8_general_ci |
    +--------------------------+-----------------+
    
    SET NAMES big5;
    
    SELECT VARIABLE_NAME, SESSION_VALUE 
      FROM INFORMATION_SCHEMA.SYSTEM_VARIABLES WHERE 
      VARIABLE_NAME LIKE 'character_set_c%' OR 
      VARIABLE_NAME LIKE 'character_set_re%' OR 
      VARIABLE_NAME LIKE 'collation_c%';
    +--------------------------+-----------------+
    | VARIABLE_NAME            | SESSION_VALUE   |
    +--------------------------+-----------------+
    | CHARACTER_SET_RESULTS    | big5            |
    | CHARACTER_SET_CONNECTION | big5            |
    | CHARACTER_SET_CLIENT     | big5            |
    | COLLATION_CONNECTION     | big5_chinese_ci |
    +--------------------------+-----------------+
    
    SET NAMES 'latin1' COLLATE 'latin1_bin';
    
    SELECT VARIABLE_NAME, SESSION_VALUE 
      FROM INFORMATION_SCHEMA.SYSTEM_VARIABLES WHERE 
      VARIABLE_NAME LIKE 'character_set_c%' OR 
      VARIABLE_NAME LIKE 'character_set_re%' OR 
      VARIABLE_NAME LIKE 'collation_c%';
    +--------------------------+---------------+
    | VARIABLE_NAME            | SESSION_VALUE |
    +--------------------------+---------------+
    | CHARACTER_SET_RESULTS    | latin1        |
    | CHARACTER_SET_CONNECTION | latin1        |
    | CHARACTER_SET_CLIENT     | latin1        |
    | COLLATION_CONNECTION     | latin1_bin    |
    +--------------------------+---------------+
    
    SET NAMES DEFAULT;
    
    SELECT VARIABLE_NAME, SESSION_VALUE 
      FROM INFORMATION_SCHEMA.SYSTEM_VARIABLES WHERE 
      VARIABLE_NAME LIKE 'character_set_c%' OR 
      VARIABLE_NAME LIKE 'character_set_re%' OR 
      VARIABLE_NAME LIKE 'collation_c%';
    +--------------------------+-------------------+
    | VARIABLE_NAME            | SESSION_VALUE     |
    +--------------------------+-------------------+
    | CHARACTER_SET_RESULTS    | latin1            |
    | CHARACTER_SET_CONNECTION | latin1            |
    | CHARACTER_SET_CLIENT     | latin1            |
    | COLLATION_CONNECTION     | latin1_swedish_ci |
    +--------------------------+-------------------+
    SET NAMES {'charset_name'
        [COLLATE 'collation_name'] | DEFAULT}
    SET [GLOBAL | SESSION] TRANSACTION
        transaction_property [, transaction_property] ...
    
    transaction_property:
        ISOLATION LEVEL level
      | READ WRITE
      | READ ONLY
    
    level:
         REPEATABLE READ
       | READ COMMITTED
       | READ UNCOMMITTED
       | SERIALIZABLE
    [mariadb]
    transaction-isolation = REPEATABLE-READ
    SELECT @@GLOBAL.transaction_isolation, @@tx_isolation;
    SET GLOBAL TRANSACTION ISOLATION LEVEL SERIALIZABLE;
    START TRANSACTION;
    
    SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
    ERROR 1568 (25001): Transaction characteristics can't be changed while a transaction is in progress
    SHOW PRIVILEGES;
    +--------------------------+---------------------------------------+--------------------------------------------------------------------+
    | Privilege                | Context                               | Comment                                                            |
    +--------------------------+---------------------------------------+--------------------------------------------------------------------+
    | Alter                    | Tables                                | To alter the table                                                 |
    | Alter routine            | Functions,Procedures                  | To alter or drop stored functions/procedures                       |
    | Create                   | Databases,Tables,Indexes              | To create new databases and tables                                 |
    | Create routine           | Databases                             | To use CREATE FUNCTION/PROCEDURE                                   |
    | Create temporary tables  | Databases                             | To use CREATE TEMPORARY TABLE                                      |
    | Create view              | Tables                                | To create new views                                                |
    | Create user              | Server Admin                          | To create new users                                                |
    | Delete                   | Tables                                | To delete existing rows                                            |
    | Delete history           | Tables                                | To delete versioning table historical rows                         |
    | Drop                     | Databases,Tables                      | To drop databases, tables, and views                               |
    | Event                    | Server Admin                          | To create, alter, drop and execute events                          |
    | Execute                  | Functions,Procedures                  | To execute stored routines                                         |
    | File                     | File access on server                 | To read and write files on the server                              |
    | Grant option             | Databases,Tables,Functions,Procedures | To give to other users those privileges you possess                |
    | Index                    | Tables                                | To create or drop indexes                                          |
    | Insert                   | Tables                                | To insert data into tables                                         |
    | Lock tables              | Databases                             | To use LOCK TABLES (together with SELECT privilege)                |
    | Process                  | Server Admin                          | To view the plain text of currently executing queries              |
    | Proxy                    | Server Admin                          | To make proxy user possible                                        |
    | References               | Databases,Tables                      | To have references on tables                                       |
    | Reload                   | Server Admin                          | To reload or refresh tables, logs and privileges                   |
    | Binlog admin             | Server                                | To purge binary logs                                               |
    | Binlog monitor           | Server                                | To use SHOW BINLOG STATUS and SHOW BINARY LOG                      |
    | Binlog replay            | Server                                | To use BINLOG (generated by mariadb-binlog)                        |
    | Replication master admin | Server                                | To monitor connected slaves                                        |
    | Replication slave admin  | Server                                | To start/stop slave and apply binlog events                        |
    | Slave monitor            | Server                                | To use SHOW SLAVE STATUS and SHOW RELAYLOG EVENTS                  |
    | Replication slave        | Server Admin                          | To read binary log events from the master                          |
    | Select                   | Tables                                | To retrieve rows from table                                        |
    | Show databases           | Server Admin                          | To see all databases with SHOW DATABASES                           |
    | Show view                | Tables                                | To see views with SHOW CREATE VIEW                                 |
    | Shutdown                 | Server Admin                          | To shut down the server                                            |
    | Super                    | Server Admin                          | To use KILL thread, SET GLOBAL, CHANGE MASTER, etc.                |
    | Trigger                  | Tables                                | To use triggers                                                    |
    | Create tablespace        | Server Admin                          | To create/alter/drop tablespaces                                   |
    | Update                   | Tables                                | To update existing rows                                            |
    | Set user                 | Server                                | To create views and stored routines with a different definer       |
    | Federated admin          | Server                                | To execute the CREATE SERVER, ALTER SERVER, DROP SERVER statements |
    | Connection admin         | Server                                | To bypass connection limits and kill other users' connections      |
    | Read_only admin          | Server                                | To perform write operations even if @@read_only=ON                 |
    | Usage                    | Server Admin                          | No privileges - allow connect only                                 |
    +--------------------------+---------------------------------------+--------------------------------------------------------------------+
    41 rows in set (0.000 sec)
    'character_set_re%'
    OR
    VARIABLE_NAME LIKE 'collation_c%';
    +--------------------------+-----------------------+
    | VARIABLE_NAME | SESSION_VALUE |
    +--------------------------+-----------------------+
    | CHARACTER_SET_RESULTS | utf8mb4 |
    | CHARACTER_SET_CONNECTION | utf8mb4 |
    | CHARACTER_SET_CLIENT | utf8mb4 |
    | COLLATION_CONNECTION | utf8mb4_uca1400_ai_ci |
    +--------------------------+-----------------------+
    LIKE
    'collation_c%'
    ;
    +--------------------------+--------------------+
    | VARIABLE_NAME | SESSION_VALUE |
    +--------------------------+--------------------+
    | CHARACTER_SET_RESULTS | utf8mb3 |
    | CHARACTER_SET_CONNECTION | utf8mb3 |
    | CHARACTER_SET_CLIENT | utf8mb3 |
    | COLLATION_CONNECTION | utf8mb3_general_ci |
    +--------------------------+--------------------+
    SET NAMES utf8mb4;
    SELECT VARIABLE_NAME, SESSION_VALUE
    FROM INFORMATION_SCHEMA.SYSTEM_VARIABLES WHERE
    VARIABLE_NAME LIKE 'character_set_con%' OR
    VARIABLE_NAME LIKE 'character_set_cl%' OR
    VARIABLE_NAME LIKE 'character_set_re%' OR
    VARIABLE_NAME LIKE 'collation_c%';
    +--------------------------+--------------------+
    | VARIABLE_NAME | SESSION_VALUE |
    +--------------------------+--------------------+
    | CHARACTER_SET_RESULTS | utf8mb4 |
    | CHARACTER_SET_CONNECTION | utf8mb4 |
    | CHARACTER_SET_CLIENT | utf8mb4 |
    | COLLATION_CONNECTION | utf8mb4_general_ci |
    +--------------------------+--------------------+
    DECLARE Variable

    You can use db_name.tbl_name as an alternative to thetbl_name FROM db_name syntax. These two statements are equivalent:

    SHOW KEYS and SHOW INDEXES are synonyms for SHOW INDEX.

    You can also list a table's indexes with the mariadb-show command:

    The information_schema.STATISTICS table stores similar information.

    The following fields are returned by SHOW INDEX.

    Field
    Description

    Table

    Table name

    Non_unique

    1 if the index permits duplicate values, 0 if values must be unique.

    Key_name

    Index name. The primary key is always named PRIMARY.

    Seq_in_index

    The column's sequence in the index, beginning with 1.

    Column_name

    Column name.

    Collation

    Either A, if the column is sorted in ascending order in the index, or NULL if it's not sorted.

    The WHERE and LIKE clauses can be given to select rows using more general conditions, as discussed in Extended SHOW.

    Examples

    See Also

    • Ignored Indexes

    • SHOW INDEX_STATISTICS

    This page is licensed: GPLv2, originally from fill_help_tables.sql

    SHOW {INDEX | INDEXES | KEYS} 
     FROM tbl_name [FROM db_name]
     [WHERE expr]
    SHOW INDEX FROM mytable FROM mydb;
    SHOW INDEX FROM mydb.mytable;
    mariadb-show -k db_name tbl_name
    CREATE TABLE IF NOT EXISTS `employees_example` (
      `id` INT(11) NOT NULL AUTO_INCREMENT,
      `first_name` VARCHAR(30) NOT NULL,
      `last_name` VARCHAR(40) NOT NULL,
      `position` VARCHAR(25) NOT NULL,
      `home_address` VARCHAR(50) NOT NULL,
      `home_phone` VARCHAR(12) NOT NULL,
      `employee_code` VARCHAR(25) NOT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY `employee_code` (`employee_code`),
      KEY `first_name` (`first_name`,`last_name`)
    ) ENGINE=Aria;
    
    INSERT INTO `employees_example` (`first_name`, `last_name`, `position`, `home_address`, `home_phone`, `employee_code`)
      VALUES
      ('Mustapha', 'Mond', 'Chief Executive Officer', '692 Promiscuous Plaza', '326-555-3492', 'MM1'),
      ('Henry', 'Foster', 'Store Manager', '314 Savage Circle', '326-555-3847', 'HF1'),
      ('Bernard', 'Marx', 'Cashier', '1240 Ambient Avenue', '326-555-8456', 'BM1'),
      ('Lenina', 'Crowne', 'Cashier', '281 Bumblepuppy Boulevard', '328-555-2349', 'LC1'),
      ('Fanny', 'Crowne', 'Restocker', '1023 Bokanovsky Lane', '326-555-6329', 'FC1'),
      ('Helmholtz', 'Watson', 'Janitor', '944 Soma Court', '329-555-2478', 'HW1');
    SHOW INDEXES FROM employees_example\G
    *************************** 1. row ***************************
            Table: employees_example
       Non_unique: 0
         Key_name: PRIMARY
     Seq_in_index: 1
      Column_name: id
        Collation: A
      Cardinality: 6
         Sub_part: NULL
           Packed: NULL
             Null: 
       Index_type: BTREE
          Comment: 
    Index_comment: 
          Ignored: NO
    *************************** 2. row ***************************
            Table: employees_example
       Non_unique: 0
         Key_name: employee_code
     Seq_in_index: 1
      Column_name: employee_code
        Collation: A
      Cardinality: 6
         Sub_part: NULL
           Packed: NULL
             Null: 
       Index_type: BTREE
          Comment: 
    Index_comment: 
          Ignored: NO
    *************************** 3. row ***************************
            Table: employees_example
       Non_unique: 1
         Key_name: first_name
     Seq_in_index: 1
      Column_name: first_name
        Collation: A
      Cardinality: NULL
         Sub_part: NULL
           Packed: NULL
             Null: 
       Index_type: BTREE
          Comment: 
    Index_comment: 
          Ignored: NO
    *************************** 4. row ***************************
            Table: employees_example
       Non_unique: 1
         Key_name: first_name
     Seq_in_index: 2
      Column_name: last_name
        Collation: A
      Cardinality: NULL
         Sub_part: NULL
           Packed: NULL
             Null: 
       Index_type: BTREE
          Comment: 
    Index_comment: 
          Ignored: NO

    Cardinality

    Estimated number of unique values in the index. The cardinality statistics are calculated at various times, and can help the optimizer make improved decisions.

    Sub_part

    NULL if the entire column is included in the index, or the number of included characters if not.

    Packed

    NULL if the index is not packed, otherwise how the index is packed.

    Null

    NULL if NULL values are permitted in the column, an empty string if NULLs are not permitted.

    Index_type

    The index type, which can be BTREE, FULLTEXT, HASH or RTREE. See Storage Engine Index Types.

    Comment

    Other information, such as whether the index is disabled.

    Index_comment

    Contents of the COMMENT attribute when the index was created.

    Ignored

    Whether or not an index will be ignored by the optimizer. See Ignored Indexes. From MariaDB 10.6.0.

    With both READ UNCOMMITTED and READ COMMITTED isolation levels, you can’t expect results to be deterministic between successive statements of the same transaction.

    With both READ UNCOMMITTED and READ COMMITTED isolation levels, you can’t expect results to be deterministic between successive statements of the same transaction.

    EXPLAIN

    Syntax

    or

    or

    Description

    The EXPLAIN statement can be used either as a synonym for or as a way to obtain information about how MariaDB executes a SELECT, UPDATE or DELETE statement:

    • 'EXPLAIN tbl_name' is synonymous with'[DESCRIBE](../describe.md) tbl_name' or'[SHOW COLUMNS](../show/show-columns.md) FROM tbl_name'.

    • When you precede a SELECT, UPDATE or a DELETE statement with the keywordEXPLAIN, MariaDB displays information from the optimizer about the query execution plan. That is, MariaDB explains how it would process the SELECT

    shows the output of a running statement. In some cases, its output can be closer to reality than EXPLAIN.

    The runs a statement and returns information about its execution plan. It also shows additional columns, to check how much the optimizer's estimation about filtering and found rows are close to reality.

    There is an online that you can use to share EXPLAIN and EXPLAIN EXTENDED output with others.

    EXPLAIN can acquire metadata locks in the same way that SELECT does, as it needs to know table metadata and, sometimes, data as well.

    Columns in EXPLAIN ... SELECT

    Column name
    Description

    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:

    Value
    Description
    Comment

    "Type" Column

    This column contains information on how the table is accessed.

    Value
    Description

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

    Value
    Description

    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 statement. This includes what the SELECT query would look like after optimizing and rewriting rules are applied and how the optimizer qualifies columns and tables.

    Examples

    As synonym for DESCRIBE or SHOW COLUMNS FROM:

    A simple set of examples to see how EXPLAIN can identify poor index usage:

    SELECT on a primary key:

    The type is const, which means that only one possible result could be returned. Now, returning the same record but searching by their phone number:

    Here, the type is All, which means no index could be used. Looking at the rows count, a full table scan (all six rows) had to be performed in order to retrieve the record. If it's a requirement to search by phone number, an index will have to be created.

    example:

    Example of ref_or_null Optimization

    ref_or_null is something that often happens when you use subqueries with NOT IN as then one has to do an extra check for NULL values if the first value didn't have a matching row.

    See Also

    This page is licensed: GPLv2, originally from

    FLUSH

    Reload internal caches and clear buffers. Learn how to use the FLUSH statement to reset logs, privileges, hosts, and other server states without restarting.

    Syntax

    or when flushing tables:

    where table_list is a list of tables separated by , (comma).

    EXPLAIN tbl_name [col_name | wild]
    EXPLAIN [EXTENDED | PARTITIONS | FORMAT=JSON] 
      {SELECT select_options | UPDATE update_options | DELETE delete_options}
    EXPLAIN [FORMAT=JSON] FOR CONNECTION <connection_id>
    ,
    UPDATE
    or
    DELETE
    , including information about how tables are joined and in which order.
    EXPLAIN EXTENDED
    can be used to provide additional information.
  • EXPLAIN PARTITIONS is useful only when examining queries involving partitioned tables. For details, see Partition pruning and selection.

  • ANALYZE statement performs the query as well as producing EXPLAIN output, and provides actual as well as estimated statistics.

  • EXPLAIN output can be printed in the slow query log. See EXPLAIN in the Slow Query Log for details.

  • EXPLAIN FOR CONNECTION is an alias for SHOW EXPLAIN FOR.

  • key_len

    How many bytes of the key that was used (shows if we are using only parts of the multi-column key).

    ref

    The reference that is used as the key value.

    rows

    An estimate of how many rows we will find in the table for each key lookup.

    Extra

    Extra information about this join.

    PRIMARY

    The SELECT is in the outermost query, but there is also a SUBQUERY within it.

    SIMPLE

    It is a simple SELECT query without any SUBQUERY or UNION.

    SUBQUERY

    The SELECT is a SUBQUERY of the PRIMARY.

    UNCACHEABLE SUBQUERY

    The SUBQUERY is UNCACHEABLE.

    UNCACHEABLE UNION

    The UNION is UNCACHEABLE.

    UNION

    The SELECT is a UNION of the PRIMARY.

    UNION RESULT

    The result of the UNION.

    LATERAL DERIVED

    The SELECT uses a

    index_subquery

    This is similar as ref, but used for sub queries that are transformed to key lookups.

    index

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

    range

    The table will be accessed with a key over one or more value ranges.

    ref_or_null

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

    ref

    A non unique index or prefix of an unique index is used to find the rows. Good if the prefix doesn't match many rows.

    system

    The table has 0 or 1 rows.

    unique_subquery

    This is similar as eq_ref, but used for sub queries that are transformed to key lookups

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

  • No matching min/max row

    During 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 const table

    The table was a const table (a table with only one possible matching row), but no row was found.

    No tables used

    The 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 exists

    Stop 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_only

    For information_schema tables. Only the frm (table definition file was opened) was opened for each matching row.

    Open_full_table

    For information_schema tables. A full table open for each matching row is done to retrieve the requested information. (Slow)

    Open_trigger_only

    For information_schema tables. Only the trigger file definition was opened for each matching row.

    Range checked for each record (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 databases

    For information_schema tables. Shows how many times we had to do a directory scan.

    Select tables optimized away

    All 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_table

    For information_schema tables. The queried table didn't need to be opened.

    unique row not found

    The 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 filesort

    Filesort 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 index

    Only 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 condition

    Like '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-by

    The 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 buffer

    We 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 temporary

    A temporary table is created to hold the result. This typically happens if you are using GROUP BY, DISTINCT or ORDER BY.

    Using where

    A 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 pushed condition

    Like 'Using where' but the where condition is pushed down to the table engine for internal optimization at the row level.

    Using buffer

    The UPDATE statement will first buffer the rows, and then run the updates, rather than do updates on the fly. See for a detailed explanation.

    id

    Sequence number that shows in which order tables are joined.

    select_type

    What kind of SELECT the table comes from.

    table

    Alias name of table. Materialized temporary tables for sub queries are named <subquery#>

    type

    How rows are found from the table (join type).

    possible_keys

    keys in table that could be used to find rows in the table

    key

    The name of the key that is used to retrieve rows. NULL is no key was used.

    DEPENDENT SUBQUERY

    The SUBQUERY is DEPENDENT.

    DEPENDENT UNION

    The UNION is DEPENDENT.

    DERIVED

    The SELECT is DERIVED from the PRIMARY.

    MATERIALIZED

    The SUBQUERY is MATERIALIZED.

    Materialized tables will be populated at first access and will be accessed by the primary key (= one key lookup). Number of rows in EXPLAIN shows the cost of populating the table

    ALL

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

    const

    There 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_ref

    A unique index is used to find the rows. This is the best possible plan to find the row.

    filter

    A second index is being used with the Rowid Filtering Optimization.

    fulltext

    A fulltext index is used to access the rows.

    index_merge

    A 'range' access is done for several index and the found rows are merged. The key column shows which keys are used.

    const row not found

    The table was a system table (a table with should exactly one row), but no row was found.

    Distinct

    If distinct optimization (remove duplicates) was used. This is marked only for the last table in the SELECT.

    Full scan on NULL key

    The 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 HAVING

    The used HAVING clause is always false so the SELECT will return no rows.

    Impossible WHERE noticed after reading const tables.

    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 WHERE

    The used WHERE clause is always false so the SELECT will return no rows. For example: WHERE 1=2

    DESCRIBE
    SHOW EXPLAIN
    ANALYZE statement
    EXPLAIN Analyzer
    SHOW WARNINGS
    SHOW EXPLAIN
    SHOW EXPLAIN
    Ignored Indexes
    fill_help_tables.sql
    Description

    The FLUSH statement clears or reloads various internal caches used by MariaDB. To execute FLUSH, you must have the RELOAD privilege. See GRANT.

    The RESET statement is similar to FLUSH. See RESET.

    You cannot issue a FLUSH statement from within a stored function or a trigger. Doing so within a stored procedure is permitted, as long as it is not called by a stored function or trigger. See Stored Routine Limitations, Stored Function Limitations and Trigger Limitations.

    If a listed table is a view, an error like the following will be produced:

    By default, FLUSH statements are written to the binary log and will be replicated. The NO_WRITE_TO_BINLOG keyword (LOCAL is an alias) will ensure the statement is not written to the binary log.

    The different flush options are:

    Option
    Description

    CHANGED_PAGE_BITMAPS

    only. Internal command used for backup purposes. See the .

    CLIENT_STATISTICS

    Reset client statistics (see ).

    DES_KEY_FILE

    Reloads the DES key file (Specified with the ).

    HOSTS

    Flush the hostname cache (used for converting ip to host names and for unblocking blocked hosts. See and

    INDEX_STATISTICS

    Reset index statistics (see ).

    ERROR

    Closes and reopens the error log file to which the server is writing.

    You can also use the mariadb-admin client to flush things. Use mariadb-admin --help to examine what flush commands it supports.

    FLUSH RELAY LOGS

    Compatibility with MySQL

    The FOR CHANNEL keyword was added for MySQL compatibility. This is identical to using the channel_name directly after the FLUSH command. For example, one can now use:

    FOR CHANNEL isn't available.

    FLUSH STATUS

    Server status variables can be reset by executing the following:

    This statement requires the RELOAD privilege.

    Specify FLUSH GLOBAL or FLUSH SESSION. Flushing of global status variables has been moved to FLUSH GLOBAL STATUS which is a synonym for FLUSH STATUS. You can use old-mode=OLD_FLUSH_STATUS to restore the old behavior of the FLUSH STATUS statement.

    The variables flushed are mainly session, but some are global. Not all session (or global) variables are flushed - the decision was made per variable.

    Global Status Variables that Support FLUSH STATUS

    Not all global status variables support being reset by FLUSH STATUS. Currently, the following is an incomplete list of status variables are reset by FLUSH GLOBAL STATUS in 11.5 or FLUSH STATUS in earlier versions:

    • Aborted_clients

    • Aborted_connects

    • Binlog_cache_disk_use

    • Binlog_cache_use

    FLUSH TABLES

    MariaDB starting with

    FLUSH TABLES doesn't cause InnoDB statistics to be reloaded or recalculated. RENAME TABLE, however, triggers a reload of the statistics.

    FLUSH TABLES causes InnoDB statistics to be reloaded or recalculated.

    FLUSH TABLES causes InnoDB statistics to be reloaded or recalculated.

    Purpose of FLUSH TABLES

    The purpose of FLUSH TABLES is to clean up the open table cache and table definition cache of tables that are not in use. This frees up memory and file descriptors. Normally this is not needed as the caches works on a first-in, first-out basis, but can be useful if the server seems to use too much memory for some reason.

    Purpose of FLUSH TABLES WITH READ LOCK

    FLUSH TABLES WITH READ LOCK is useful if you want to take a backup of some tables. When FLUSH TABLES WITH READ LOCK returns, all write access to tables is blocked and all tables are marked as 'properly closed' on disk. The tables can still be used for read operations.

    Purpose of FLUSH TABLES table_list

    FLUSH TABLES table_list is useful if you want to copy a table object or files to or from the server. This command puts a lock that stops new users of the table and will wait until everyone has stopped using the table. The table is then removed from the table definition and table cache.

    Note that it's up to the user to ensure that no one is accessing the table between FLUSH TABLES and the table is copied to or from the server. This can be secured by using LOCK TABLES.

    If there are any tables locked by the connection that is using FLUSH TABLES all the locked tables will be closed as part of the flush and reopened and relocked before FLUSH TABLES returns. This allows one to copy the table after FLUSH TABLES returns without having any writes on the table. For now this works with most tables, except InnoDB as InnoDB may do background purges on the table even while it's write locked.

    Purpose of FLUSH TABLES table_list WITH READ LOCK

    FLUSH TABLES table_list WITH READ LOCK should work as FLUSH TABLES WITH READ LOCK, but only those tables that are listed will be properly closed. However in practice this works exactly like FLUSH TABLES WITH READ LOCK as the FLUSH command has anyway to wait for all WRITE operations to end because we are depending on a global read lock for this code. In the future we should consider fixing this to instead use meta data locks.

    Implementation of FLUSH TABLES

    • Free memory and file descriptors not in use

    Implementation of FLUSH TABLES WITH READ LOCK

    • Lock all tables read only for simple old style backup.

    • All background writes are suspended and tables are marked as closed.

    • No statement requiring table changes are allowed for any user until UNLOCK TABLES.

    Instead of using FLUSH TABLE WITH READ LOCK one should in most cases instead use BACKUP STAGE BLOCK_COMMIT.

    Implementation of FLUSH TABLES table_list

    • Free memory and file descriptors for tables not in use from table list.

    • Lock given tables as read only.

    • Wait until all translations has ended that uses any of the given tables.

    • Wait until all background writes are suspended and tables are marked as closed.

    Implementation of FLUSH TABLES table_list FOR EXPORT

    • Free memory and file descriptors for tables not in use from table list.

    • Lock given tables as read.

    • Wait until all background writes are suspended and tables are marked as closed.

    • Check that all tables supports FOR EXPORT.

    • No changes to these tables allowed until UNLOCK TABLES.

    This is basically the same behavior as in older MariaDB versions if you first lock the tables, then do FLUSH TABLES. The tables will be copyable until you issue UNLOCK TABLES.

    FLUSH SSL

    The FLUSH SSL command can be used to dynamically reinitialize the server's TLS context. This is most useful if you need to replace a certificate that is about to expire without restarting the server.

    This operation is performed by reloading the files defined by the following TLS system variables:

    • ssl_cert

    • ssl_key

    • ssl_ca

    • ssl_capath

    These TLS system variables are not dynamic, so their values can not be changed without restarting the server.

    If you want to dynamically reinitialize the server's TLS context, then you need to change the certificate and key files at the relevant paths defined by these TLS system variables, without actually changing the values of the variables. See MDEV-19341 for more information.

    Reducing Memory Usage

    To flush some of the global caches that take up memory, you could execute the following command:

    This page is licensed: GPLv2, originally from fill_help_tables.sql

    DESCRIBE city;
    +------------+----------+------+-----+---------+----------------+
    | Field      | Type     | Null | Key | Default | Extra          |
    +------------+----------+------+-----+---------+----------------+
    | Id         | int(11)  | NO   | PRI | NULL    | auto_increment |
    | Name       | char(35) | YES  |     | NULL    |                |
    | Country    | char(3)  | NO   | UNI |         |                |
    | District   | char(20) | YES  | MUL |         |                |
    | Population | int(11)  | YES  |     | NULL    |                |
    +------------+----------+------+-----+---------+----------------+
    CREATE TABLE IF NOT EXISTS `employees_example` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `first_name` varchar(30) NOT NULL,
      `last_name` varchar(40) NOT NULL,
      `position` varchar(25) NOT NULL,
      `home_address` varchar(50) NOT NULL,
      `home_phone` varchar(12) NOT NULL,
      `employee_code` varchar(25) NOT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY `employee_code` (`employee_code`),
      KEY `first_name` (`first_name`,`last_name`)
    ) ENGINE=Aria;
    
    INSERT INTO `employees_example` (`first_name`, `last_name`, `position`, `home_address`, `home_phone`, `employee_code`)
      VALUES
      ('Mustapha', 'Mond', 'Chief Executive Officer', '692 Promiscuous Plaza', '326-555-3492', 'MM1'),
      ('Henry', 'Foster', 'Store Manager', '314 Savage Circle', '326-555-3847', 'HF1'),
      ('Bernard', 'Marx', 'Cashier', '1240 Ambient Avenue', '326-555-8456', 'BM1'),
      ('Lenina', 'Crowne', 'Cashier', '281 Bumblepuppy Boulevard', '328-555-2349', 'LC1'),
      ('Fanny', 'Crowne', 'Restocker', '1023 Bokanovsky Lane', '326-555-6329', 'FC1'),
      ('Helmholtz', 'Watson', 'Janitor', '944 Soma Court', '329-555-2478', 'HW1');
    
    SHOW INDEXES FROM employees_example;
    +-------------------+------------+---------------+--------------+---------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
    | Table             | Non_unique | Key_name      | Seq_in_index | Column_name   | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
    +-------------------+------------+---------------+--------------+---------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
    | employees_example |          0 | PRIMARY       |            1 | id            | A         |           7 |     NULL | NULL   |      | BTREE      |         |               |
    | employees_example |          0 | employee_code |            1 | employee_code | A         |           7 |     NULL | NULL   |      | BTREE      |         |               |
    | employees_example |          1 | first_name    |            1 | first_name    | A         |        NULL |     NULL | NULL   |      | BTREE      |         |               |
    | employees_example |          1 | first_name    |            2 | last_name     | A         |        NULL |     NULL | NULL   |      | BTREE      |         |               |
    +-------------------+------------+---------------+--------------+---------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
    EXPLAIN SELECT * FROM employees_example WHERE id=1;
    +------+-------------+-------------------+-------+---------------+---------+---------+-------+------+-------+
    | id   | select_type | table             | type  | possible_keys | key     | key_len | ref   | rows | Extra |
    +------+-------------+-------------------+-------+---------------+---------+---------+-------+------+-------+
    |    1 | SIMPLE      | employees_example | const | PRIMARY       | PRIMARY | 4       | const |    1 |       |
    +------+-------------+-------------------+-------+---------------+---------+---------+-------+------+-------+
    EXPLAIN SELECT * FROM employees_example WHERE home_phone='326-555-3492';
    +------+-------------+-------------------+------+---------------+------+---------+------+------+-------------+
    | id   | select_type | table             | type | possible_keys | key  | key_len | ref  | rows | Extra       |
    +------+-------------+-------------------+------+---------------+------+---------+------+------+-------------+
    |    1 | SIMPLE      | employees_example | ALL  | NULL          | NULL | NULL    | NULL |    6 | Using where |
    +------+-------------+-------------------+------+---------------+------+---------+------+------+-------------+
    SHOW EXPLAIN FOR 1;
    +------+-------------+-------+-------+---------------+------+---------+------+---------+-------------+
    | id   | select_type | table | type  | possible_keys | key  | key_len | ref  | rows    | Extra       |
    +------+-------------+-------+-------+---------------+------+---------+------+---------+-------------+
    |    1 | SIMPLE      | tbl   | index | NULL          | a    | 5       | NULL | 1000107 | Using index |
    +------+-------------+-------+-------+---------------+------+---------+------+---------+-------------+
    1 row in set, 1 warning (0.00 sec)
    SELECT * FROM table_name
      WHERE key_column=expr OR key_column IS NULL;
    FLUSH RELAY LOGS FOR CHANNEL 'connection_name';
    FLUSH [NO_WRITE_TO_BINLOG | LOCAL]
        flush_option [, flush_option] ...
    FLUSH [NO_WRITE_TO_BINLOG | LOCAL] TABLES [table_list]  [table_flush_option]
    ERROR 1347 (HY000): 'test.v' is not BASE TABLE
    FLUSH RELAY LOGS 'connection_name'
    FLUSH STATUS
    FLUSH LOCAL HOSTS,
       QUERY CACHE, 
       TABLE_STATISTICS, 
       INDEX_STATISTICS, 
       USER_STATISTICS;
    Lateral Derived optimization
    Using Buffer UPDATE Algorithm

    BINARY LOGS

    FLUSH BINARY LOGS rotates the current binary log.

    BINARY LOGS DELETE_DOMAIN_ID=(list-of-domains)

    FLUSH BINARY LOGS DELETE_DOMAIN_ID can be used to discard obsolete GTID domains from the server's binary log state. In order for this to be successful, no event group from the listed GTID domains can be present in existing binary log files. If some still exist, then they must be purged prior to executing this command. If the command completes successfully, then it also rotates the binary log.

    MASTER

    Deprecated option, use RESET MASTER instead.

    PRIVILEGES

    Reload all privileges from the privilege tables in the mysql database. If the server is started with --skip-grant-table option, this will activate the privilege tables again.

    QUERY CACHE

    Defragment the query cache to better utilize its memory. If you want to reset the query cache, you can do it with RESET QUERY CACHE.

    QUERY_RESPONSE_TIME

    See the QUERY_RESPONSE_TIME plugin.

    QUERY_RESPONSE_TIME_READ

    See the QUERY_RESPONSE_TIME plugin. From .

    QUERY_RESPONSE_TIME_READ_WRITE

    See the QUERY_RESPONSE_TIME plugin. From .

    QUERY_RESPONSE_TIME_WRITE

    See the QUERY_RESPONSE_TIME plugin. From .

    SLAVE

    Deprecated option, use RESET REPLICA or RESET SLAVE instead.

    SSL

    Used to dynamically reinitialize the server's TLS context by reloading the files defined by several TLS system variables. See FLUSH SSL for more information.

    [ GLOBAL

    SESSION ] STATUS

    TABLE[S]

    Close tables given as options or all open tables if no table list was used. Using without any table list will only close tables not in use, and tables not locked by the FLUSH TABLES connection. If there are no locked tables, FLUSH TABLES will be instant and will not cause any waits, as it no longer waits for tables in use. When a table list is provided, the server will wait for the end of any transactions that are using the tables. Previously, FLUSH TABLES only waited for the statements to complete.

    TABLE[S] ... FOR EXPORT

    For InnoDB tables, flushes table changes to disk to permit binary table copies while the server is running. See FLUSH TABLES ... FOR EXPORT for more.

    TABLE[S] WITH READ LOCK

    Closes all open tables. New tables are only allowed to be opened with read locks until an UNLOCK TABLES is given.

    TABLE[S] WITH READ LOCK AND DISABLE CHECKPOINT

    As TABLES WITH READ LOCK but also disable all checkpoint writes by transactional table engines. This is useful when doing a disk snapshot of all tables.

    TABLE_STATISTICS

    Reset table statistics (see SHOW TABLE_STATISTICS).

    USER_RESOURCES

    Resets all per hour user resources. This enables clients that have exhausted their resources to connect again.

    USER_STATISTICS

    Reset user statistics (see SHOW USER_STATISTICS).

    USER_VARIABLES

    Reset user variables (see User-defined variables).

    Binlog_stmt_cache_disk_use
    Binlog_stmt_cache_use
    Connection_errors_accept
    Connection_errors_internal
    Connection_errors_max_connections
    Connection_errors_peer_address
    Connection_errors_select
    Connection_errors_tcpwrap
    Created_tmp_files
    Delayed_errors
    Delayed_writes
    Feature_check_constraint
    Feature_delay_key_write
    Max_used_connection_time
    Max_used_connections
    Opened_plugin_libraries
    Performance_schema_accounts_lost
    Performance_schema_cond_instances_lost
    Performance_schema_digest_lost
    Performance_schema_file_handles_lost
    Performance_schema_file_instances_lost
    Performance_schema_hosts_lost
    Performance_schema_locker_lost
    Performance_schema_mutex_instances_lost
    Performance_schema_rwlock_instances_lost
    Performance_schema_session_connect_attrs_lost
    Performance_schema_socket_instances_lost
    Performance_schema_stage_classes_lost
    Performance_schema_statement_classes_lost
    Performance_schema_table_handles_lost
    Performance_schema_table_instances_lost
    Performance_schema_thread_instances_lost
    Performance_schema_users_lost
    Qcache_hits
    Qcache_inserts
    Qcache_lowmem_prunes
    Qcache_not_cached
    Rpl_semi_sync_master_no_times
    Rpl_semi_sync_master_no_tx
    Rpl_semi_sync_master_timefunc_failures
    Rpl_semi_sync_master_wait_pos_backtraverse
    Rpl_semi_sync_master_yes_tx
    Rpl_transactions_multi_engine
    Server_audit_writes_failed
    Slave_retried_transactions
    Slow_launch_threads
    Ssl_accept_renegotiates
    Ssl_accepts
    Ssl_callback_cache_hits
    Ssl_client_connects
    Ssl_connect_renegotiates
    Ssl_ctx_verify_depth
    Ssl_ctx_verify_mode
    Ssl_finished_accepts
    Ssl_finished_connects
    Ssl_session_cache_hits
    Ssl_session_cache_misses
    Ssl_session_cache_overflows
    Ssl_session_cache_size
    Ssl_session_cache_timeouts
    Ssl_sessions_reused
    Ssl_used_session_cache_entries
    Subquery_cache_hit
    Subquery_cache_miss
    Table_locks_immediate
    Table_locks_waited
    Tc_log_max_pages_used
    Tc_log_page_waits
    Transactions_gtid_foreign_engine
    Transactions_multi_engine
    ssl_crl
    ssl_crlpath
    XtraDB
    Information Schema CHANGED_PAGE_BITMAPS Table
    SHOW CLIENT_STATISTICS
    --des-key-file startup option
    max_connect_errors
    performance_schema.host_cache
    SHOW INDEX_STATISTICS
    Log of MariaDB contributors

    CHANGE MASTER TO

    The terms master and slave have historically been used in replication, and MariaDB has begun the process of adding primary and replica synonyms. The old terms will continue to be used to maintain backward compatibility - see MDEV-18777 to follow progress on this effort.

    Syntax

    Description

    CHANGE MASTER is used on a replica to set up or change settings for connecting to the primary.

    The FOR CHANNEL keyword was added for MySQL compatibility. This is identical to using the channel_name directly after CHANGE MASTER.

    FOR CHANNEL is not available.

    Multi-Source Replication

    If you are using , then you need to specify a connection name when you execute CHANGE MASTER. There are two ways to do this:

    • Setting the system variable prior to executing CHANGE MASTER.

    • Setting the connection_name parameter when executing CHANGE MASTER.

    default_master_connection

    connection_name

    Options

    Connection Options

    MASTER_USER

    The MASTER_USER option for CHANGE MASTER defines the user account that the will use to connect to the .

    This user account will need the privilege on the primary.

    This user account will need the privilege on the primary.

    For example:

    The maximum length of the MASTER_USER string is 128 characters.

    The maximum length of the MASTER_USER string is 96 characters.

    MASTER_PASSWORD

    The MASTER_PASSWORD option for CHANGE MASTER defines the password that the will use to connect to the as the user account defined by the option.

    For example:

    The maximum length of the MASTER_PASSWORD string is 32 characters. The effective maximum length of the string depends on how many bytes are used per character and can be up to 96 characters.

    Due to , the password can be silently truncated to 41 characters when MariaDB is restarted. For this reason, it is recommended to use a password that is shorter than this.

    MASTER_HOST

    The MASTER_HOST option for CHANGE MASTER defines the hostname or IP address of the .

    If you set the value of the MASTER_HOST option to the empty string, then that is not the same as not setting the option's value at all. If you set the value of the MASTER_HOST option to the empty string, then the CHANGE MASTER command will fail with an error.

    If you set the value of the MASTER_HOST option to the empty string, then that is not the same as not setting the option's value at all. If you set the value of the MASTER_HOST option to the empty string, then the CHANGE MASTER command will fail with an error. In MariaDB 5.3 and before, if you set the value of the MASTER_HOST option to the empty string, then the CHANGE MASTER command would succeed, but the subsequent command would fail.

    For example:

    If you set the value of the MASTER_HOST option in a CHANGE MASTER command, then the replica assumes that the primary is different from before, even if you set the value of this option to the same value it had previously. In this scenario, the replica will consider the old values for the primary's file name and position to be invalid for the new primary. As a side effect, if you do not explicitly set the values of the and options in the statement, then the statement will be implicitly appended with MASTER_LOG_FILE='' and MASTER_LOG_POS=4. However, if you enable mode for replication by setting the option to some value other than no in the statement, then these values will effectively be ignored anyway.

    Replicas cannot connect to primaries using Unix socket files or Windows named pipes. The replica must connect to the primary using TCP/IP.

    The maximum length of the MASTER_HOST string is 255 characters.

    The maximum length of the MASTER_HOST string is 60 characters.

    MASTER_PORT

    The MASTER_PORT option for CHANGE MASTER defines the TCP/IP port of the .

    For example:

    If you set the value of the MASTER_PORT option in a CHANGE MASTER command, then the replica assumes that the primary is different from before, even if you set the value of this option to the same value it had previously. In this scenario, the replica will consider the old values for the primary's file name and position to be invalid for the new primary. As a side effect, if you do not explicitly set the values of the and options in the statement, then the statement will be implicitly appended with MASTER_LOG_FILE='' and MASTER_LOG_POS=4. However, if you enable mode for replication by setting the option to some value other than no in the statement, then these values will effectively be ignored anyway.

    Replicas cannot connect to primaries using Unix socket files or Windows named pipes. The replica must connect to the primary using TCP/IP.

    MASTER_CONNECT_RETRY

    The MASTER_CONNECT_RETRY option for CHANGE MASTER defines how many seconds that the replica will wait between connection retries. The default is 60.

    MASTER_RETRY_COUNT

    The MASTER_RETRY_COUNT option limits the number of connection attempts (i.e., Connects_Tried in ). For example:

    Setting this option resets the Connects_Tried statistic in to 0.

    The default is the option, which be set either on the command-line or in a server in an prior to starting up the server. For example:

    The MASTER_RETRY_COUNT option for CHANGE MASTER is only supported by MariaDB 12.0.1 and later and by MySQL. Please use the option instead, which be set either on the command-line or in a server in an prior to starting up the server. For example:

    MASTER_BIND

    The MASTER_BIND option for CHANGE MASTER is only supported by MySQL 5.6.2 and later and by MySQL NDB Cluster 7.3.1 and later. This option is not supported by MariaDB. See for more information.

    The MASTER_BIND option for CHANGE MASTER can be used on replicas that have multiple network interfaces to choose which network interface the replica will use to connect to the primary.

    MASTER_HEARTBEAT_PERIOD

    The MASTER_HEARTBEAT_PERIOD option for CHANGE MASTER can be used to set the interval in seconds between replication heartbeats. Whenever the primary's is updated with an event, the waiting period for the next heartbeat is reset.

    This option's interval argument has the following characteristics:

    • It is a decimal value with a range of 0 to 4294967 seconds.

    • It has a resolution of hundredths of a second.

    • Its smallest valid non-zero value is 0.001.

    Heartbeats are sent by the primary only if there are no unsent events in the binary log file for a period longer than the interval.

    If the statement is executed, then the heartbeat interval is reset to the default.

    If the system variable is set to a value that is lower than the current heartbeat interval, then a warning will be issued.

    TLS Options

    The TLS options are used for providing information about . The options can be set even on replicas that are compiled without TLS support. The TLS options are saved to either the default master.info file or the file that is configured by the option, but these TLS options are ignored unless the replica supports TLS.

    See for more information.

    MASTER_SSL

    The MASTER_SSL option for CHANGE MASTER tells the replica whether to force for the connection. The valid values are 0 or 1. Required to be set to 1 for the other MASTER_SSL* options to have any effect.

    For example:

    MASTER_SSL_CA

    The MASTER_SSL_CA option for CHANGE MASTER defines a path to a PEM file that should contain one or more X509 certificates for trusted Certificate Authorities (CAs) to use for . This option requires that you use the absolute path, not a relative path.

    For example:

    See for more information.

    The maximum length of MASTER_SSL_CA string is 511 characters.

    MASTER_SSL_CAPATH

    The MASTER_SSL_CAPATH option for CHANGE MASTER defines a path to a directory that contains one or more PEM files that should each contain one X509 certificate for a trusted Certificate Authority (CA) to use for . This option requires that you use the absolute path, not a relative path. The directory specified by this option needs to be run through the command.

    For example:

    See for more information.

    The maximum length of MASTER_SSL_CA_PATH string is 511 characters.

    MASTER_SSL_CERT

    The MASTER_SSL_CERT option for CHANGE MASTER defines a path to the X509 certificate file to use for . This option requires that you use the absolute path, not a relative path.

    For example:

    The maximum length of MASTER_SSL_CERT string is 511 characters.

    MASTER_SSL_CRL

    The MASTER_SSL_CRL option for CHANGE MASTER defines a path to a PEM file that should contain one or more revoked X509 certificates to use for . This option requires that you use the absolute path, not a relative path.

    This option is only supported if the server was built with OpenSSL. If the server was built with yaSSL, then this option is not supported. See for more information about which libraries are used on which platforms.

    For example:

    See for more information.

    The maximum length of MASTER_SSL_CRL string is 511 characters.

    MASTER_SSL_CRLPATH

    The MASTER_SSL_CRLPATH option for CHANGE MASTER defines a path to a directory that contains one or more PEM files that should each contain one revoked X509 certificate to use for . This option requires that you use the absolute path, not a relative path. The directory specified by this variable needs to be run through the command.

    This option is only supported if the server was built with OpenSSL. If the server was built with yaSSL, then this option is not supported. See for more information about which libraries are used on which platforms.

    For example:

    See for more information.

    The maximum length of MASTER_SSL_CRL_PATH string is 511 characters.

    MASTER_SSL_KEY

    The MASTER_SSL_KEY option for CHANGE MASTER defines a path to a private key file to use for . This option requires that you use the absolute path, not a relative path.

    For example:

    The maximum length of MASTER_SSL_KEY string is 511 characters.

    MASTER_SSL_CIPHER

    The MASTER_SSL_CIPHER option for CHANGE MASTER defines the list of permitted ciphers or cipher suites to use for . Besides cipher names, if MariaDB was compiled with OpenSSL, this option could be set to "SSLv3" or "TLSv1.2" to allow all SSLv3 or all TLSv1.2 ciphers. Note that the TLSv1.3 ciphers cannot be excluded when using OpenSSL, even by using this option. See for details.

    For example:

    The maximum length of MASTER_SSL_CIPHER string is 511 characters.

    MASTER_SSL_VERIFY_SERVER_CERT

    The MASTER_SSL_VERIFY_SERVER_CERT option for CHANGE MASTER enables . This option is enabled by default.

    The MASTER_SSL_VERIFY_SERVER_CERT option for CHANGE MASTER enables . This option is disabled by default.

    For example:

    See for more information.

    Binary Log Options

    These options are related to the position on the primary.

    MASTER_LOG_FILE

    The MASTER_LOG_FILE option for CHANGE MASTER can be used along with MASTER_LOG_POS to specify the coordinates at which the should begin reading from the primary's the next time the thread starts.

    For example:

    The and options cannot be specified if the and options were also specified.

    The and options are effectively ignored if you enable mode for replication by setting the option to some value other than no in the statement.

    MASTER_LOG_POS

    The MASTER_LOG_POS option for CHANGE MASTER can be used along with MASTER_LOG_FILE to specify the coordinates at which the should begin reading from the primary's the next time the thread starts.

    For example:

    The and options cannot be specified if the and options were also specified.

    The and options are effectively ignored if you enable mode for replication by setting the option to some value other than no in the statement.

    Relay Log Options

    These options are related to the position on the replica.

    RELAY_LOG_FILE

    The RELAY_LOG_FILE option for CHANGE MASTER can be used along with the option to specify the coordinates at which the should begin reading from the the next time the thread starts.

    The CHANGE MASTER statement usually deletes all files. However, if the RELAY_LOG_FILE and/or RELAY_LOG_POS options are specified, then existing files are kept.

    When you want to change the position, you only need to stop the . The can continue running. The and statements support the SQL_THREAD option for this scenario. For example:

    When the value of this option is changed, the metadata about the position in the will also be changed in the relay-log.info file or the file that is configured by the system variable.

    The and options cannot be specified if the and options were also specified.

    RELAY_LOG_POS

    The RELAY_LOG_POS option for CHANGE MASTER can be used along with the option to specify the coordinates at which the should begin reading from the the next time the thread starts.

    The CHANGE MASTER statement usually deletes all files. However, if the RELAY_LOG_FILE and/or RELAY_LOG_POS options are specified, then existing files are kept.

    When you want to change the position, you only need to stop the . The can continue running. The and statements support the SQL_THREAD option for this scenario. For example:

    When the value of this option is changed, the metadata about the position in the will also be changed in the relay-log.info file or the file that is configured by the system variable.

    The and options cannot be specified if the and options were also specified.

    GTID Options

    MASTER_USE_GTID

    The MASTER_USE_GTID option for CHANGE MASTER can be used to configure the replica to use the when connecting to a primary. The possible values are:

    • current_pos - Replicate in mode and use as the position to start downloading transactions from the primary. Using to transition to primary can break the replication state if the replica executes local transactions due to actively updating gtid_current_pos with gtid_binlog_pos and gtid_slave_pos. Use the new, safe, option instead.

    • replica_pos - Replicate in

    The MASTER_USE_GTID option for CHANGE MASTER can be used to configure the replica to use the when connecting to a primary. The possible values are:

    • current_pos - Replicate in mode and use as the position to start downloading transactions from the primary. Using to transition to primary can break the replication state if the replica executes local transactions due to actively updating gtid_current_pos with gtid_binlog_pos and gtid_slave_pos. Use the new, safe, option instead.

    • slave_pos - Replicate in mode and use as the position to start downloading transactions from the primary. From , replica_pos is an alias for slave_pos.

    For example:

    Or:

    MASTER_DEMOTE_TO_SLAVE

    Used to transition a primary to become a replica. Replaces the old with a safe alternative by forcing users to set Using_Gtid=Slave_Pos and merging gtid_binlog_pos into gtid_slave_pos once at CHANGE MASTER TO time. If gtid_slave_pos is morerecent than gtid_binlog_pos (as in the case of chain replication), the replication state should be preserved.

    For example:

    MASTER_DEMOTE_TO_SLAVE is not available.

    Replication Filter Options

    Also see .

    IGNORE_SERVER_IDS

    The IGNORE_SERVER_IDS option for CHANGE MASTER can be used to configure a to ignore events that originated from certain servers. Filtered events will not get logged to the replica’s , and they will not be applied by the replica.

    The option's value can be specified by providing a comma-separated list of values. For example:

    If you would like to clear a previously set list, then you can set the value to an empty list. For example:

    DO_DOMAIN_IDS

    The DO_DOMAIN_IDS option for CHANGE MASTER can be used to configure a to only apply events if the transaction's is in a specific value. Filtered events will not get logged to the replica’s , and they will not be applied by the replica.

    The option's value can be specified by providing a comma-separated list of values. Duplicate values are automatically ignored. For example:

    If you would like to clear a previously set list, then you can set the value to an empty list. For example:

    The option and the option cannot both be set to non-empty values at the same time. If you want to set the option, and the option was previously set, then you need to clear the value of the option. For example:

    The DO_DOMAIN_IDS option can only be specified if the replica is replicating in mode. Therefore, the option must also be set to some value other than no in order to use this option.

    IGNORE_DOMAIN_IDS

    The IGNORE_DOMAIN_IDS option for CHANGE MASTER can be used to configure a to ignore events if the transaction's is in a specific value. Filtered events will not get logged to the replica’s , and they will not be applied by the replica.

    The option's value can be specified by providing a comma-separated list of values. Duplicate values are automatically ignored. For example:

    If you would like to clear a previously set list, then you can set the value to an empty list. For example:

    The option and the option cannot both be set to non-empty values at the same time. If you want to set the option, and the option was previously set, then you need to clear the value of the option. For example:

    The IGNORE_DOMAIN_IDS option can only be specified if the replica is replicating in mode. Therefore, the option must also be set to some value other than no in order to use this option.

    Delayed Replication Options

    MASTER_DELAY

    The MASTER_DELAY option for CHANGE MASTER can be used to enable . This option specifies the time in seconds (at least) that a replica should lag behind the primary up to a maximum value of 2147483647, or about 68 years. Before executing an event, the replica will first wait, if necessary, until the given time has passed since the event was created on the primary. The result is that the replica will reflect the state of the primary some time back in the past. The default is zero, no delay.

    Changing Option Values

    If you don't specify a given option when executing the CHANGE MASTER statement, then the option keeps its old value in most cases. Most of the time, there is no need to specify the options that do not need to change. For example, if the password for the user account that the replica uses to connect to its primary has changed, but no other options need to change, then you can just change the option by executing the following commands:

    There are some cases where options are implicitly reset, such as when the and options are changed.

    Option Persistence

    The values of the and options (i.e. the position on the primary) and most other options are written to either the default master.info file or the file that is configured by the option. The keeps this position updated as it downloads events only when optionis set to NO. Otherwise the file is not updated on a per event basis.

    The option can be set either on the command-line or in a server in an prior to starting up the server. For example:

    The values of the and options (i.e. the position) are written to either the default relay-log.info file or the file that is configured by the system variable. The keeps this position updated as it applies events.

    The system variable can be set either on the command-line or in a server in an prior to starting up the server. For example:

    GTID Persistence

    If the replica is replicating events that contain , then the will write every GTID that it applies to the table. This GTID can be inspected and modified through the system variable.

    If the replica has the system variable enabled and if the replica has the enabled, then every write by the will also go into the replica's . This means that of replicated transactions would be reflected in the value of the system variable.

    Creating a Replica from a Backup

    The CHANGE MASTER statement is useful for setting up a replica when you have a backup of the primary and you also have the position or position corresponding to the backup.

    After restoring the backup on the replica, you could execute something like this to use the position:

    Or you could execute something like this to use the position:

    See for more information on how to do this with .

    Example

    The following example changes the primary and primary's binary log coordinates. This is used when you want to set up the replica to replicate the primary:

    See Also

    • . Removes a connection created with CHANGE MASTER TO.

    This page is licensed: GPLv2, originally from

    CHANGE MASTER ['connection_name'] TO master_def  [, master_def] ... 
      [FOR CHANNEL 'channel_name']
    
    master_def:
        MASTER_BIND = 'interface_name'
      | MASTER_HOST = 'host_name'
      | MASTER_USER = 'user_name'
      | MASTER_PASSWORD = 'password'
      | MASTER_PORT = port_num
      | MASTER_CONNECT_RETRY = interval
      | MASTER_HEARTBEAT_PERIOD = interval
      | MASTER_LOG_FILE = 'master_log_name'
      | MASTER_LOG_POS = master_log_pos
      | RELAY_LOG_FILE = 'relay_log_name'
      | RELAY_LOG_POS = relay_log_pos
      | MASTER_DELAY = interval
      | MASTER_SSL = {0|1}
      | MASTER_SSL_CA = 'ca_file_name'
      | MASTER_SSL_CAPATH = 'ca_directory_name'
      | MASTER_SSL_CERT = 'cert_file_name'
      | MASTER_SSL_CRL = 'crl_file_name'
      | MASTER_SSL_CRLPATH = 'crl_directory_name'
      | MASTER_SSL_KEY = 'key_file_name'
      | MASTER_SSL_CIPHER = 'cipher_list'
      | MASTER_SSL_VERIFY_SERVER_CERT = {0|1}
      | MASTER_USE_GTID = {current_pos|slave_pos|no}
      | MASTER_DEMOTE_TO_SLAVE = bool
      | IGNORE_SERVER_IDS = (server_id_list)
      | DO_DOMAIN_IDS = ([N,..])
      | IGNORE_DOMAIN_IDS = ([N,..])
      | MASTER_RETRY_COUNT = long
    Its default value is the value of the slave_net_timeout system variable divided by 2.
  • If it's set to 0, then heartbeats are disabled.

  • mode and use
    as the position to start downloading transactions from the primary.
  • no - Don't replicate in GTID mode.

  • The MASTER_USE_GTID option for CHANGE MASTER can be used to configure the replica to use the global transaction ID (GTID) when connecting to a primary. The possible values are:

    • current_pos - Replicate in GTID mode and use gtid_current_pos as the position to start downloading transactions from the primary. Using to transition to primary can break the replication state if the replica executes local transactions due to actively updating gtid_current_pos with gtid_binlog_pos and gtid_slave_pos. Use the new, safe, MASTER_DEMOTE_TO_SLAVE= option instead.

    • slave_pos - Replicate in GTID mode and use as the position to start downloading transactions from the primary.

    • no - Don't replicate in mode.

    no - Don't replicate in GTID mode.

    Global Transaction ID

    replication
    multi-source replication
    default_master_connection
    replica
    primary
    REPLICATION REPLICA
    REPLICATION SLAVE
    replica
    primary
    MASTER_USER
    MDEV-29994
    primary
    START SLAVE
    binarylog
    MASTER_LOG_FILE
    MASTER_LOG_POS
    GTID
    MASTER_USE_GTID
    primary
    binarylog
    MASTER_LOG_FILE
    MASTER_LOG_POS
    GTID
    MASTER_USE_GTID
    SHOW REPLICA STATUS
    SHOW REPLICA STATUS
    --master-retry-count
    option group
    option file
    --master-retry-count
    option group
    option file
    MDEV-19248
    binary log
    RESET SLAVE
    slave_net_timeout
    TLS
    master_info_file
    Replication with Secure Connections
    TLS
    TLS
    Secure Connections Overview: Certificate Authorities (CAs)
    TLS
    openssl rehash
    Secure Connections Overview: Certificate Authorities (CAs)
    TLS
    TLS
    TLS and Cryptography Libraries Used by MariaDB
    Secure Connections Overview: Certificate Revocation Lists (CRLs)
    TLS
    openssl rehash
    TLS and Cryptography Libraries Used by MariaDB
    Secure Connections Overview: Certificate Revocation Lists (CRLs)
    TLS
    TLS
    Using TLSv1.3
    server certificate verification
    server certificate verification
    Secure Connections Overview: Server Certificate Verification
    binary log
    replica's I/O thread
    binary logs
    MASTER_LOG_FILE
    MASTER_LOG_POS
    RELAY_LOG_FILE
    RELAY_LOG_POS
    MASTER_LOG_FILE
    MASTER_LOG_POS
    GTID
    MASTER_USE_GTID
    replica's I/O thread
    binary logs
    MASTER_LOG_FILE
    MASTER_LOG_POS
    RELAY_LOG_FILE
    RELAY_LOG_POS
    MASTER_LOG_FILE
    MASTER_LOG_POS
    GTID
    MASTER_USE_GTID
    relay log
    RELAY_LOG_POS
    replica's SQL thread
    relay log
    relay log
    relay log
    relay log
    replica's SQL thread
    replica's I/O thread
    STOP SLAVE
    START SLAVE
    replica's SQL thread's
    relay logs
    relay_log_info_file
    RELAY_LOG_FILE
    RELAY_LOG_POS
    MASTER_LOG_FILE
    MASTER_LOG_POS
    RELAY_LOG_FILE
    replica's SQL thread
    relay log
    relay log
    relay log
    relay log
    replica's SQL thread
    replica's I/O thread
    STOP SLAVE
    START SLAVE
    replica's SQL thread's
    relay logs
    relay_log_info_file
    RELAY_LOG_FILE
    RELAY_LOG_POS
    MASTER_LOG_FILE
    MASTER_LOG_POS
    global transaction ID (GTID)
    GTID
    gtid_current_pos
    MASTER_DEMOTE_TO_SLAVE=
    GTID
    global transaction ID (GTID)
    GTID
    gtid_current_pos
    MASTER_DEMOTE_TO_SLAVE=
    GTID
    gtid_slave_pos
    MASTER_USE_GTID=current_pos
    Replication filters
    replica
    binary log
    binary log
    relay log
    server_id
    replica
    binary log
    GTID
    gtid_domain_id
    binary log
    relay log
    gtid_domain_id
    DO_DOMAIN_IDS
    IGNORE_DOMAIN_IDS
    DO_DOMAIN_IDS
    IGNORE_DOMAIN_IDS
    IGNORE_DOMAIN_IDS
    GTID
    MASTER_USE_GTID
    replica
    binary log
    GTID
    gtid_domain_id
    binary log
    relay log
    gtid_domain_id
    DO_DOMAIN_IDS
    IGNORE_DOMAIN_IDS
    IGNORE_DOMAIN_IDS
    DO_DOMAIN_IDS
    DO_DOMAIN_IDS
    GTID
    MASTER_USE_GTID
    delayed replication
    MASTER_PASSWORD
    MASTER_HOST
    MASTER_PORT
    MASTER_LOG_FILE
    MASTER_LOG_POS
    binary log
    master_info_file
    replica's I/O thread
    binary log
    MASTER_USE_GTID
    master_info_file
    option group
    option file
    RELAY_LOG_FILE
    RELAY_LOG_POS
    relay log
    relay_log_info_file
    replica's SQL thread
    relay log
    relay_log_info_file
    option group
    option file
    binary log
    GTIDs
    replica's SQL thread
    mysql.gtid_slave_pos
    gtid_slave_pos
    log_slave_updates
    binary log
    replica's SQL thread
    binary log
    GTIDs
    gtid_binlog_pos
    binary log
    GTID
    binary log
    GTID
    Setting up a Replication Slave with mariadb-backup
    mariadb-backup
    Setting up replication
    START SLAVE
    Multi-source replication
    RESET SLAVE
    fill_help_tables.sql
    gtid_slave_pos
    SET default_master_connection = 'gandalf';
    STOP SLAVE;
    CHANGE MASTER TO 
       MASTER_PASSWORD='new3cret';
    START SLAVE;
    STOP SLAVE 'gandalf';
    CHANGE MASTER 'gandalf' TO 
       MASTER_PASSWORD='new3cret';
    START SLAVE 'gandalf';
    STOP SLAVE;
    CHANGE MASTER TO
       MASTER_USER='repl',
       MASTER_PASSWORD='new3cret';
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO 
       MASTER_PASSWORD='new3cret';
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO
       MASTER_HOST='dbserver1.example.com',
       MASTER_USER='repl',
       MASTER_PASSWORD='new3cret',
       MASTER_USE_GTID=slave_pos;
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO
       MASTER_HOST='dbserver1.example.com',
       MASTER_PORT=3307,
       MASTER_USER='repl',
       MASTER_PASSWORD='new3cret',
       MASTER_USE_GTID=slave_pos;
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO 
       MASTER_CONNECT_RETRY=20;
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO
      MASTER_RETRY_COUNT=1; # attempt only once; do not retry if it fails
    START SLAVE;
    [mariadb]
    ...
    master_retry_count=4294967295
    STOP SLAVE;
    CHANGE MASTER TO
       MASTER_SSL=1;
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO
       MASTER_SSL_CERT='/etc/my.cnf.d/certificates/server-cert.pem',
       MASTER_SSL_KEY='/etc/my.cnf.d/certificates/server-key.pem',
       MASTER_SSL_CA='/etc/my.cnf.d/certificates/ca.pem',
       MASTER_SSL_VERIFY_SERVER_CERT=1;
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO
       MASTER_SSL_CERT='/etc/my.cnf.d/certificates/server-cert.pem',
       MASTER_SSL_KEY='/etc/my.cnf.d/certificates/server-key.pem',
       MASTER_SSL_CAPATH='/etc/my.cnf.d/certificates/ca/',
       MASTER_SSL_VERIFY_SERVER_CERT=1;
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO
       MASTER_SSL_CERT='/etc/my.cnf.d/certificates/server-cert.pem',
       MASTER_SSL_KEY='/etc/my.cnf.d/certificates/server-key.pem',
       MASTER_SSL_CA='/etc/my.cnf.d/certificates/ca.pem',
       MASTER_SSL_VERIFY_SERVER_CERT=1;
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO
       MASTER_SSL_CERT='/etc/my.cnf.d/certificates/server-cert.pem',
       MASTER_SSL_KEY='/etc/my.cnf.d/certificates/server-key.pem',
       MASTER_SSL_CA='/etc/my.cnf.d/certificates/ca.pem',
       MASTER_SSL_VERIFY_SERVER_CERT=1,
       MASTER_SSL_CRL='/etc/my.cnf.d/certificates/crl.pem';
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO
       MASTER_SSL_CERT='/etc/my.cnf.d/certificates/server-cert.pem',
       MASTER_SSL_KEY='/etc/my.cnf.d/certificates/server-key.pem',
       MASTER_SSL_CA='/etc/my.cnf.d/certificates/ca.pem',
       MASTER_SSL_VERIFY_SERVER_CERT=1,
       MASTER_SSL_CRLPATH='/etc/my.cnf.d/certificates/crl/';
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO
       MASTER_SSL_CERT='/etc/my.cnf.d/certificates/server-cert.pem',
       MASTER_SSL_KEY='/etc/my.cnf.d/certificates/server-key.pem',
       MASTER_SSL_CA='/etc/my.cnf.d/certificates/ca.pem',
       MASTER_SSL_VERIFY_SERVER_CERT=1;
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO
       MASTER_SSL_CERT='/etc/my.cnf.d/certificates/server-cert.pem',
       MASTER_SSL_KEY='/etc/my.cnf.d/certificates/server-key.pem',
       MASTER_SSL_CA='/etc/my.cnf.d/certificates/ca.pem',
       MASTER_SSL_VERIFY_SERVER_CERT=1,
       MASTER_SSL_CIPHER='TLSv1.2';
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO
       MASTER_SSL_CERT='/etc/my.cnf.d/certificates/server-cert.pem',
       MASTER_SSL_KEY='/etc/my.cnf.d/certificates/server-key.pem',
       MASTER_SSL_CA='/etc/my.cnf.d/certificates/ca.pem',
       MASTER_SSL_VERIFY_SERVER_CERT=1;
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO
       MASTER_LOG_FILE='master2-bin.001',
       MASTER_LOG_POS=4;
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO
       MASTER_LOG_FILE='master2-bin.001',
       MASTER_LOG_POS=4;
    START SLAVE;
    STOP SLAVE SQL_THREAD;
    CHANGE MASTER TO
       RELAY_LOG_FILE='slave-relay-bin.006',
       RELAY_LOG_POS=4025;
    START SLAVE SQL_THREAD;
    STOP SLAVE SQL_THREAD;
    CHANGE MASTER TO
       RELAY_LOG_FILE='slave-relay-bin.006',
       RELAY_LOG_POS=4025;
    START SLAVE SQL_THREAD;
    STOP SLAVE;
    CHANGE MASTER TO
       MASTER_USE_GTID = current_pos;
    START SLAVE;
    STOP SLAVE;
    SET GLOBAL gtid_slave_pos='0-1-153';
    CHANGE MASTER TO
       MASTER_USE_GTID = slave_pos;
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO
       MASTER_DEMOTE_TO_SLAVE = 1;
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO 
       IGNORE_SERVER_IDS = (3,5);
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO 
       IGNORE_SERVER_IDS = ();
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO 
       DO_DOMAIN_IDS = (1,2);
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO 
       DO_DOMAIN_IDS = ();
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO 
       IGNORE_DOMAIN_IDS = (), 
       DO_DOMAIN_IDS = (1,2);
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO 
       IGNORE_DOMAIN_IDS = (1,2);
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO 
       IGNORE_DOMAIN_IDS = ();
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO 
       DO_DOMAIN_IDS = (), 
       IGNORE_DOMAIN_IDS = (1,2);
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO 
       MASTER_DELAY=3600;
    START SLAVE;
    STOP SLAVE;
    CHANGE MASTER TO 
       MASTER_PASSWORD='new3cret';
    START SLAVE;
    [mariadb]
    ...
    master_info_file=/mariadb/myserver1-master.info
    [mariadb]
    ...
    relay_log_info_file=/mariadb/myserver1-relay-log.info
    CHANGE MASTER TO
       MASTER_LOG_FILE='master2-bin.001',
       MASTER_LOG_POS=4;
    START SLAVE;
    SET GLOBAL gtid_slave_pos='0-1-153';
    CHANGE MASTER TO
       MASTER_USE_GTID=slave_pos;
    START SLAVE;
    CHANGE MASTER TO
       MASTER_HOST='master2.mycompany.com',
       MASTER_USER='replication',
       MASTER_PASSWORD='bigs3cret',
       MASTER_PORT=3306,
       MASTER_LOG_FILE='master2-bin.001',
       MASTER_LOG_POS=4,
       MASTER_CONNECT_RETRY=10;
    START SLAVE;
    gtid_slave_pos
    GTID
    MariaDB 10.1.0
    MariaDB 10.8.8
    MariaDB 10.9.8
    MariaDB 10.10.6
    MariaDB 11.0.3
    MariaDB 11.1.2
    MariaDB 11.2.1
    10.9
    10.7.0
    11.6.0
    MariaDB 5.5
    Oracle SQL_MODE
    MariaDB 11.5
    MariaDB 11.5
    11.3.0
    MariaDB 5.2
    MariaDB 10.1.1
    Oracle SQL_MODE
    MariaDB 10.5.2
    10.7.0
    MariaDB 11.3.0
    MariaDB 10.3.23
    MariaDB 10.4.13
    MariaDB 10.5.2
    MariaDB 11.0.6
    MariaDB 11.1.5
    MariaDB 11.2.4
    10.11.12
    MariaDB 11.5
    MariaDB 11.5
    MariaDB 11.5
    MariaDB 10.5.1