Administration
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
This page covers the routine work of running a MySQL server: who may connect and what they may do, how the server is
configured, how to see what it is doing, and how to change schemas and clean up without taking the application
down. Everything was run against the mysql:latest Docker image, which reported version 26.10.0, with the shop
example loaded (see Getting Started). Where the page says "this server" it
means that container. The generic GRANT and REVOKE syntax is in DCL; this page adds
what is specific to MySQL.
Accounts: user@host
A MySQL account is the pair of a user name and the host the client connects from, written 'user'@'host'. The same
name with two different hosts is two independent accounts, each with its own password and privileges. The host part
may be a name, an address, a wildcard pattern (10.0.%) or % for any host. When several rows match a connection the
most specific one wins, which is why 'app'@'%' and 'app'@'localhost' can behave differently.
CREATE USER 'app'@'%' IDENTIFIED BY 'S3cret-pass!'
PASSWORD EXPIRE INTERVAL 90 DAY FAILED_LOGIN_ATTEMPTS 5 PASSWORD_LOCK_TIME 1;
CREATE USER 'report'@'10.0.%' IDENTIFIED WITH caching_sha2_password BY 'R3port-pass!';
SELECT user, host, plugin, account_locked FROM mysql.user WHERE user IN ('app','report');
+--------+--------+-----------------------+----------------+ | user | host | plugin | account_locked | +--------+--------+-----------------------+----------------+ | app | % | caching_sha2_password | N | | report | 10.0.% | caching_sha2_password | N | +--------+--------+-----------------------+----------------+
The host match is on the address the server sees. The report account above is restricted to 10.0.%, so
connecting as it from 127.0.0.1 is refused even with the right password:
$ mysql -ureport -p'R3port-pass!' -h 127.0.0.1 -e "select 1" ERROR 1045 (28000): Access denied for user 'report'@'127.0.0.1' (using password: YES)
Useful account clauses: PASSWORD EXPIRE, FAILED_LOGIN_ATTEMPTS with PASSWORD_LOCK_TIME (temporary lockout after
repeated failures), ACCOUNT LOCK/UNLOCK, WITH MAX_USER_CONNECTIONS n and REQUIRE SSL (or X509). ALTER USER
changes any of them and DROP USER removes the account. Accounts live in the mysql system schema; never edit those
tables by hand, use the account statements.
Authentication plugins
caching_sha2_password is the default plugin on this server, and the server variable that controls the default for
new accounts is authentication_policy:
SHOW VARIABLES LIKE 'authentication_policy';
SELECT user, host, plugin FROM mysql.user WHERE user IN ('root','mysql.sys');
CREATE USER 'legacy'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Legacy-pass1!';
+-----------------------+-------+ | Variable_name | Value | +-----------------------+-------+ | authentication_policy | *,, | +-----------------------+-------+ (root and mysql.sys both use caching_sha2_password) ERROR 1524 (HY000): Plugin 'mysql_native_password' is not loaded
The *,, policy means "first factor: any plugin, defaulting to caching_sha2_password, no second or third factor". On
this release mysql_native_password no longer exists: it was deprecated in 8.0.34, disabled by default in 8.4 and removed
in 9.0.0, so the server reports it as not loaded. An old account definition or a
client that only speaks that plugin has to be migrated (modern clients and drivers support caching_sha2_password; it needs either TLS
or the server’s RSA key pair for the first password exchange, after which a hash is cached in memory). Other plugins
exist for LDAP, Kerberos, FIDO and OpenID Connect in the Enterprise edition or through plugins, and
authentication_policy can require multi-factor authentication for new accounts.
Password policy
The password-validation component is not installed by default. It is installed and removed with the component statements, after which new passwords are checked:
INSTALL COMPONENT 'file://component_validate_password';
SHOW VARIABLES LIKE 'validate_password%';
CREATE USER 'weak'@'localhost' IDENTIFIED BY 'abc';
SELECT validate_password_strength('abc'), validate_password_strength('Str0ng-Passw0rd!');
validate_password.length = 8, policy = MEDIUM, mixed_case_count = 1, number_count = 1, special_char_count = 1,
check_user_name = ON, dictionary_file = (empty), changed_characters_percentage = 0
ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
+-----------------------------------+------------------------------------------------+
| validate_password_strength('abc') | validate_password_strength('Str0ng-Passw0rd!') |
+-----------------------------------+------------------------------------------------+
| 0 | 100 |
+-----------------------------------+------------------------------------------------+
(The variable list is condensed to one line here.) The policy level is LOW (length only), MEDIUM (default: mixed
case, digit, special character) or STRONG (adds a dictionary check). Password reuse and rotation are separate:
password_history, password_reuse_interval and default_password_lifetime, or per account with
PASSWORD HISTORY and PASSWORD EXPIRE.
Roles
A role is a named bundle of privileges that is granted to accounts, so permissions are managed once and accounts
inherit them. Roles are accounts too ('shop_read'@'%') that cannot log in by default.
CREATE ROLE 'shop_read','shop_write';
GRANT SELECT ON shop.* TO 'shop_read';
GRANT INSERT, UPDATE, DELETE ON shop.* TO 'shop_write';
GRANT 'shop_read' TO 'report'@'10.0.%';
GRANT 'shop_read','shop_write' TO 'app'@'%';
SET DEFAULT ROLE ALL TO 'app'@'%';
SHOW GRANTS FOR 'app'@'%' USING 'shop_read';
+-----------------------------------------------------+ | Grants for app@% | +-----------------------------------------------------+ | GRANT USAGE ON *.* TO `app`@`%` | | GRANT SELECT ON `shop`.* TO `app`@`%` | | GRANT `shop_read`@`%`,`shop_write`@`%` TO `app`@`%` | +-----------------------------------------------------+
A granted role is not active until it is made one. SET DEFAULT ROLE activates roles at login, SET ROLE activates
them in a session, and the global variable activate_all_roles_on_login (OFF on this server) would activate every
granted role for everybody. After the statements above, a login as app shows both roles and the privileges they
carry:
$ mysql -uapp -p... -e "SELECT CURRENT_USER(), CURRENT_ROLE(); SELECT COUNT(*) FROM shop.customers; DELETE FROM shop.orders WHERE 1=0;" app@% `shop_read`@`%`,`shop_write`@`%` 4 ERROR 1142 (42000): DELETE command denied to user 'app'@'localhost' for table 'orders'
The delete is denied because only INSERT and UPDATE were granted to shop_write. The data dictionary tables show the
wiring:
SELECT * FROM mysql.default_roles;
SELECT * FROM mysql.role_edges;
+------+------+-------------------+-------------------+ | HOST | USER | DEFAULT_ROLE_HOST | DEFAULT_ROLE_USER | +------+------+-------------------+-------------------+ | % | app | % | shop_read | | % | app | % | shop_write | +------+------+-------------------+-------------------+ +-----------+------------+---------+---------+-------------------+ | FROM_HOST | FROM_USER | TO_HOST | TO_USER | WITH_ADMIN_OPTION | +-----------+------------+---------+---------+-------------------+ | % | shop_read | % | app | N | | % | shop_read | 10.0.% | report | N | | % | shop_write | % | app | N | +-----------+------------+---------+---------+-------------------+
Mandatory roles are roles the server grants to every account automatically, handy for a baseline of read access.
They are set with the mandatory_roles system variable, which is dynamic and can be persisted:
SET PERSIST mandatory_roles='shop_read';
SHOW VARIABLES LIKE 'mandatory_roles';
RESET PERSIST mandatory_roles;
+-----------------+-----------+ | Variable_name | Value | +-----------------+-----------+ | mandatory_roles | shop_read | +-----------------+-----------+
GRANT and REVOKE, privilege levels
GRANT attaches privileges at one of five levels, from broadest to narrowest. A privilege held at a broader level
covers the narrower ones.
| Level | Syntax example |
|---|---|
Global (all databases) |
|
Database |
|
Table |
|
Column |
|
Routine |
|
GRANT SELECT (name, city) ON shop.customers TO 'report'@'10.0.%';
REVOKE DELETE ON shop.* FROM 'shop_write';
SHOW GRANTS FOR 'shop_write';
SHOW GRANTS FOR 'report'@'10.0.%';
+------------------------------------------------------+ | Grants for shop_write@% | +------------------------------------------------------+ | GRANT USAGE ON *.* TO `shop_write`@`%` | | GRANT INSERT, UPDATE ON `shop`.* TO `shop_write`@`%` | +------------------------------------------------------+ +--------------------------------------------------------------------------+ | Grants for report@10.0.% | +--------------------------------------------------------------------------+ | GRANT USAGE ON *.* TO `report`@`10.0.%` | | GRANT SELECT (`city`, `name`) ON `shop`.`customers` TO `report`@`10.0.%` | | GRANT `shop_read`@`%` TO `report`@`10.0.%` | +--------------------------------------------------------------------------+
USAGE means "no privileges, may connect". Changing a role’s privileges takes effect for accounts that already use it
the next time they activate the role (a new session). Besides the static privileges (SELECT, INSERT, ALTER, …)
MySQL has dynamic privileges that split the old SUPER privilege into narrow rights, for example SYSTEM_VARIABLES_ADMIN
(change global variables), CONNECTION_ADMIN (kill other users' sessions), BACKUP_ADMIN, BINLOG_ADMIN and
ROLE_ADMIN; SHOW PRIVILEGES lists all of them (several dozen on this server). Grant the narrow right instead of
SUPER or ALL PRIVILEGES, and grant to roles rather than directly to accounts. WITH GRANT OPTION lets the
grantee pass a privilege on.
Configuration
The server reads option files in a fixed order, later files overriding earlier ones. mysqld --verbose --help prints
the list; in this image it is:
Default options are read from the following files in the given order: /etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf The following groups are read: mysql_cluster mysqld server mysqld-26.10
An option file has a section per program. Server settings go in [mysqld], client defaults in [client] and
[mysql]. This is the image’s own /etc/my.cnf, trimmed:
[mysqld] # innodb_buffer_pool_size = 128M # log_bin host-cache-size=0 skip-name-resolve datadir=/var/lib/mysql socket=/var/run/mysqld/mysqld.sock secure-file-priv=/var/lib/mysql-files user=mysql pid-file=/var/run/mysqld/mysqld.pid [client] socket=/var/run/mysqld/mysqld.sock
In a Docker setup the cleanest way to add settings is to mount a file under /etc/mysql/conf.d/ (the /etc/mysql
directory and its conf.d exist in the image, and /etc/my.cnf ends with an !includedir /etc/mysql/conf.d/ line), or to pass options on
the command line (docker run mysql:latest --max-connections=300). Static options such as datadir need a restart.
Check where each value came from with performance_schema.variables_info:
SET GLOBAL max_connections = 300;
SELECT variable_name, variable_source, variable_path, set_user
FROM performance_schema.variables_info
WHERE variable_name IN ('max_connections','datadir','log_error');
SET GLOBAL datadir='/x';
+-----------------+-----------------+---------------+----------+ | variable_name | variable_source | variable_path | set_user | +-----------------+-----------------+---------------+----------+ | datadir | GLOBAL | /etc/my.cnf | NULL | | log_error | COMPILED | | NULL | | max_connections | DYNAMIC | | root | +-----------------+-----------------+---------------+----------+ ERROR 1238 (HY000): Variable 'datadir' is a read only variable
SET GLOBAL, SET SESSION and SET PERSIST
-
SET SESSION var = valueaffects only the current connection. -
SET GLOBAL var = valuechanges the running server for new sessions (existing ones keep their session copy) and is lost at restart. -
SET PERSIST var = valuedoesSET GLOBALand also writes the value tomysqld-auto.cnfin the data directory so it survives a restart.SET PERSIST_ONLYwrites the file without changing the running server, which is the only way to set a read-only (static) variable.RESET PERSISTremoves entries from the file; it does not change the running value.
SET PERSIST max_connections = 250;
SET PERSIST_ONLY innodb_buffer_pool_instances = 2;
SELECT variable_name, variable_value FROM performance_schema.persisted_variables;
RESET PERSIST;
SELECT @@global.max_connections;
+------------------------------+----------------+ | variable_name | variable_value | +------------------------------+----------------+ | max_connections | 250 | | innodb_buffer_pool_instances | 2 | +------------------------------+----------------+ +--------------------------+ | @@global.max_connections | +--------------------------+ | 250 | +--------------------------+
The file the server wrote for those two statements (formatted over one line in the file, shown trimmed):
{"Version": 2, "mysql_static_variables": {"innodb_buffer_pool_instances": {"Value": "2", ...}},
"mysql_dynamic_parse_early_variables": {"max_connections": {"Value": "250", ...}}}
Note that RESET PERSIST left the running value at 250: it only forgets the persisted setting for the next start. Use
SET GLOBAL max_connections = DEFAULT to return the live value to the default. Prefer SET PERSIST for operational
changes made at the SQL prompt, and the option file for settings that belong in version-controlled deployment config.
Looking at the server: SHOW
SHOW VARIABLES lists configuration, SHOW STATUS lists counters that change as the server works. Both accept
LIKE patterns and a GLOBAL or SESSION scope. The same data is in performance_schema.global_variables,
global_status and the session_ variants, which can be joined and filtered with ordinary SQL.
SHOW GLOBAL STATUS LIKE 'Threads%';
SHOW STATUS LIKE 'Created_tmp%';
+-------------------+-------+ +-------------------------+-------+ | Variable_name | Value | | Variable_name | Value | +-------------------+-------+ +-------------------------+-------+ | Threads_cached | 0 | | Created_tmp_disk_tables | 0 | | Threads_connected | 1 | | Created_tmp_files | 10 | | Threads_created | 1 | | Created_tmp_tables | 5 | | Threads_running | 2 | +-------------------------+-------+ +-------------------+-------+
(Two results shown side by side.) Counters are cumulative since startup, so rates are computed from two samples.
Uptime, Threads_running, Connections, Aborted_connects, Questions and the Com_* counters are the usual
starting points; the tuning page uses buffer pool and temporary-table counters.
Monitoring with performance_schema and sys
performance_schema is a set of in-memory tables fed by instrumentation inside the server: statements, stages, waits,
memory, locks, file and table I/O. The sys schema (version 2.1.3 on this server) is a collection of readable views and
procedures built on top of it. Which statement-level consumers are collecting is controlled in performance_schema.setup_consumers:
SELECT name, enabled FROM performance_schema.setup_consumers WHERE name LIKE 'events_statements%';
+--------------------------------+---------+ | name | enabled | +--------------------------------+---------+ | events_statements_cpu | NO | | events_statements_current | YES | | events_statements_history | YES | | events_statements_history_long | NO | +--------------------------------+---------+
Statement digests
The server normalises each statement (literals become ?) and keeps one row per distinct shape in
events_statements_summary_by_digest with counts, latency and rows examined. It is the first place to look for the
queries that cost the most:
SELECT LEFT(digest_text,60) digest, count_star, ROUND(sum_timer_wait/1e9,1) AS total_ms,
sum_rows_examined, sum_no_index_used
FROM performance_schema.events_statements_summary_by_digest
WHERE schema_name='shop' ORDER BY sum_timer_wait DESC LIMIT 4;
+--------------------------------------------------------------+------------+----------+-------------------+-------------------+ | digest | count_star | total_ms | sum_rows_examined | sum_no_index_used | +--------------------------------------------------------------+------------+----------+-------------------+-------------------+ | SELECT `SLEEP` (?) | 2 | 22073.7 | 2 | 0 | | UPDATE `customers` SET `tier` = ? WHERE `id` = ? | 2 | 15101.8 | 1 | 0 | | ALTER TABLE `ddl_demo` MODIFY `amount` DECIMAL (...) NOT NUL | 1 | 1984.7 | 0 | 0 | | INSERT INTO `ddl_demo` WITH RECURSIVE `n` ( `i` ) AS ( SELEC | 1 | 1434.5 | 1000000 | 1 | +--------------------------------------------------------------+------------+----------+-------------------+-------------------+
The digest text is truncated here by LEFT() to fit the page. The top two rows come from the lock demonstration below
(a long sleep and an update that waited for a row lock), a reminder that total time includes waiting, not only work.
sys.statement_analysis presents the same data with formatted latencies and flags such as full_scan.
Digests are reset with TRUNCATE TABLE performance_schema.events_statements_summary_by_digest or the sys helper
procedures. The slow-query workflow built on these tables is in
Diagnosing slow queries.
Waits and memory
Where the server spends its time waiting, and where its memory is, are one query each:
SELECT * FROM sys.waits_global_by_latency LIMIT 3;
SELECT event_name, current_alloc FROM sys.memory_global_by_current_bytes LIMIT 4;
SELECT table_schema, table_name, total_latency, rows_fetched
FROM sys.schema_table_statistics WHERE table_schema='shop' LIMIT 3;
+--------------------------------------+-------+---------------+-------------+-------------+ | events | total | total_latency | avg_latency | max_latency | +--------------------------------------+-------+---------------+-------------+-------------+ | wait/io/file/innodb/innodb_data_file | 3119 | 174.06 ms | 55.80 us | 3.58 ms | | wait/io/file/innodb/innodb_log_file | 2999 | 141.06 ms | 46.99 us | 3.86 ms | | wait/io/file/sql/binlog | 980 | 33.10 ms | 33.76 us | 4.11 ms | +--------------------------------------+-------+---------------+-------------+-------------+ +---------------------------------------------------------------+---------------+ | event_name | current_alloc | +---------------------------------------------------------------+---------------+ | memory/innodb/buf_buf_pool | 130.88 MiB | | memory/innodb/log_buffer_memory | 64.00 MiB | | memory/performance_schema/events_statements_summary_by_digest | 40.28 MiB | | memory/innodb/ut0link_buf | 24.00 MiB | +---------------------------------------------------------------+---------------+ +--------------+------------+---------------+--------------+ | table_schema | table_name | total_latency | rows_fetched | +--------------+------------+---------------+--------------+ | shop | items | 1.85 ms | 50050 | | shop | orders | 41.15 us | 19 | | shop | customers | 38.90 us | 16 | +--------------+------------+---------------+--------------+
Other sys views worth knowing: host_summary and user_summary (connections and work per client),
schema_unused_indexes, statements_with_full_table_scans, statements_with_temp_tables, io_global_by_file_by_bytes
and innodb_lock_waits.
Sessions: SHOW PROCESSLIST and KILL
SHOW FULL PROCESSLIST (or information_schema.processlist, or performance_schema.threads which is the
recommended source on busy servers because it does not take a global mutex) lists the connections and what they
are doing. Here two sessions are in conflict: one holds an open transaction on a customer row, the second tries to update
the same row and waits.
SHOW FULL PROCESSLIST;
SELECT wait_started, locked_table, locked_index, waiting_pid, waiting_query,
blocking_pid, blocking_query
FROM sys.innodb_lock_waits;
+----+-----------------+-----------+------+---------+------+------------------------+-------------------------------------------------+ | Id | User | Host | db | Command | Time | State | Info | +----+-----------------+-----------+------+---------+------+------------------------+-------------------------------------------------+ | 5 | event_scheduler | localhost | NULL | Daemon | 211 | Waiting on empty queue | NULL | | 23 | root | localhost | shop | Query | 5 | User sleep | SELECT SLEEP(20) | | 24 | root | localhost | shop | Query | 3 | updating | UPDATE customers SET tier='free' WHERE id='c-2' | | 25 | root | localhost | shop | Query | 0 | init | SHOW FULL PROCESSLIST | +----+-----------------+-----------+------+---------+------+------------------------+-------------------------------------------------+ +---------------------+--------------------+--------------+-------------+-------------------------------------------------+--------------+------------------+ | wait_started | locked_table | locked_index | waiting_pid | waiting_query | blocking_pid | blocking_query | +---------------------+--------------------+--------------+-------------+-------------------------------------------------+--------------+------------------+ | 2026-11-10 19:06:31 | `shop`.`customers` | PRIMARY | 24 | UPDATE customers SET tier='free' WHERE id='c-2' | 23 | SELECT SLEEP(20) | +---------------------+--------------------+--------------+-------------+-------------------------------------------------+--------------+------------------+
The blocker (session 23) is idle inside its transaction, shown as the SELECT SLEEP(20) it last ran. The sys view
names both sides, so the fix is to commit or kill the blocker. KILL QUERY id aborts the statement and leaves the
connection; KILL CONNECTION id (or plain KILL id) closes the connection and rolls its transaction back. Killing
another user’s session needs CONNECTION_ADMIN:
KILL QUERY 26;
The session that had been running SELECT SLEEP(60) returned at once with the value 1, which is how SLEEP reports it
was interrupted.
The error log
In this image the error log goes to standard error (log_error is stderr), so docker logs is the file.
The same entries are queryable through performance_schema.error_log:
SELECT logged, prio, error_code, subsystem, LEFT(data,70) FROM performance_schema.error_log
ORDER BY logged DESC LIMIT 3;
2026-11-10 19:07:51.338523 Warning MY-014089 InnoDB Redo log writer is waiting for a new redo log file. Consider increasin 2026-11-10 19:07:50.899894 Warning MY-014084 InnoDB Threads are unable to reserve space in redo log which can't be reclaim 2026-11-10 19:07:50.837169 Warning MY-014089 InnoDB Redo log writer is waiting for a new redo log file. Consider increasin
These warnings appeared while loading a million rows into the test table: the default redo log capacity (100 MiB) was
too small for that burst. It is the kind of signal the error log gives, and it is followed up in
Performance Tuning. log_error_verbosity (2 here) selects errors,
warnings, or also notes; log_error_services selects the filter and sink components, for example the JSON sink.
Maintenance statements
ANALYZE TABLE shop.orders;
ANALYZE TABLE shop.orders UPDATE HISTOGRAM ON status WITH 8 BUCKETS;
CHECK TABLE shop.orders;
OPTIMIZE TABLE shop.ddl_demo;
analyze status OK histogram status Histogram statistics created for column 'status'. check status OK optimize note Table does not support optimize, doing recreate + analyze instead optimize status OK
Each statement returns a small table with the columns Table, Op, Msg_type and Msg_text; the lines above show
Op, Msg_type and Msg_text only.
-
ANALYZE TABLErefreshes the index statistics the optimizer uses. InnoDB re-samples automatically (persistent statistics) so it is needed after a large load or when plans look wrong.UPDATE HISTOGRAMstores a value distribution for a non-indexed column; thestatuscolumn got asingletonhistogram (one bucket per distinct value) visible ininformation_schema.column_statistics. -
CHECK TABLEverifies the structure of a table and reportsOKor the problem. For InnoDB corruption the usual remedy is restoring a backup or recovering withinnodb_force_recovery, notREPAIR TABLE, which InnoDB does not support. -
OPTIMIZE TABLEon InnoDB isALTER TABLE ... FORCEplusANALYZE: it rebuilds the table to reclaim space left by deletes. It is online for most of the work, but needs temporary disk space for the copy and should not be run as a nightly reflex.
Online DDL
Changing a table’s structure uses one of three algorithms, chosen by the server or forced with ALGORITHM=. If the
requested algorithm is impossible the statement fails instead of silently doing something slower, which is the safe way
to run DDL in production: ask for the cheapest algorithm you expect, and let the error tell you if you were wrong.
| Algorithm | What it does |
|---|---|
|
changes metadata only; no table rebuild, no lock held while data is read; takes milliseconds regardless of size |
|
modifies the table without creating a full copy at the SQL layer; may rebuild in InnoDB; concurrent DML allowed with |
|
creates a new table, copies every row, swaps; the original is read-only ( |
A 1,000,000-row table (ddl_demo: an integer key, a short string and a decimal) and the elapsed time of each
statement as measured inside the server:
ALTER TABLE ddl_demo ADD COLUMN note varchar(50) NULL, ALGORITHM=INSTANT;
ALTER TABLE ddl_demo ADD COLUMN flag tinyint NOT NULL DEFAULT 0, ALGORITHM=INPLACE;
ALTER TABLE ddl_demo ADD INDEX idx_label (label), ALGORITHM=INPLACE, LOCK=NONE;
ALTER TABLE ddl_demo MODIFY label varchar(30) NOT NULL, ALGORITHM=INPLACE, LOCK=NONE;
ALTER TABLE ddl_demo MODIFY amount decimal(12,2) NOT NULL, ALGORITHM=COPY, LOCK=SHARED;
ALTER TABLE ddl_demo DROP COLUMN flag, ALGORITHM=INSTANT;
ALTER TABLE ddl_demo RENAME COLUMN note TO memo, ALGORITHM=INSTANT;
| Operation | Elapsed (ms) |
|---|---|
|
2.2 |
|
589.2 |
|
657.5 |
widen |
1.5 |
change |
1984.8 |
|
3.9 |
|
3.6 |
Absolute numbers depend on the machine; the ratio is the point. The same table also shows the limits of each algorithm. Real error messages from the server:
ALTER TABLE ddl_demo MODIFY amount decimal(12,2) NOT NULL, ALGORITHM=INPLACE; ERROR 1846 (0A000): ALGORITHM=INPLACE is not supported. Reason: Cannot change column type INPLACE. Try ALGORITHM=COPY. ALTER TABLE ddl_demo ADD INDEX idx_label (label), ALGORITHM=INSTANT; ERROR 1845 (0A000): ALGORITHM=INSTANT is not supported for this operation. Try ALGORITHM=COPY/INPLACE. ALTER TABLE ddl_demo MODIFY memo varchar(300), ALGORITHM=INPLACE; ERROR 1846 (0A000): ALGORITHM=INPLACE is not supported. Reason: Cannot change column type INPLACE. Try ALGORITHM=COPY.
The last one is the classic trap: a VARCHAR can be widened in place only while its length prefix stays one byte
(up to 255 bytes, so VARCHAR(63) with utf8mb4); crossing that boundary changes the on-disk format and needs a rebuild.
Adding an index is online (INPLACE, LOCK=NONE) but not instant, and DROP INDEX was accepted as INPLACE while
INSTANT was refused.
For tables too large or too busy for even an INPLACE rebuild, external tools such as gh-ost or pt-online-schema-change
copy the table in the background and swap at the end; the broader practice of changing schemas without downtime is in
Schema evolution.
Binary logs
The binary log is on by default on this server (log_bin is ON) and is the basis for replication and point-in-time
recovery, so it must be managed. Files are rotated on size, on restart or with FLUSH BINARY LOGS, and expire
automatically after binlog_expire_logs_seconds (2592000 seconds, 30 days) while binlog_expire_logs_auto_purge is ON.
SHOW BINARY LOGS;
FLUSH BINARY LOGS;
FLUSH BINARY LOGS;
SHOW BINARY LOGS;
PURGE BINARY LOGS TO 'binlog.000003';
SHOW BINARY LOGS;
+---------------+-----------+-----------+ +---------------+-----------+-----------+ | Log_name | File_size | Encrypted | | Log_name | File_size | Encrypted | +---------------+-----------+-----------+ +---------------+-----------+-----------+ | binlog.000001 | 2981501 | No | | binlog.000003 | 242 | No | | binlog.000002 | 26333671 | No | | binlog.000004 | 198 | No | +---------------+-----------+-----------+ +---------------+-----------+-----------+
(Before, and after the two FLUSH statements and the PURGE BINARY LOGS TO, which deleted files 1 and 2.) Never delete
binlog.* files with rm: purge through SQL so the index file stays consistent, and never purge files a replica has not
yet read (SHOW REPLICA STATUS tells you). Backups that rely on the log for recovery are described in
Backup & Restore, and the replica side in
Replication & High Availability.
Next: Performance Tuning and the MySQL Reference.