


Common SQL statements for database optimization in MySQL (summary sharing)
Recommended learning: mysql video tutorial
1.SHOW ENGINES
View execution engine and default engine.
2.SHOW PROCESSLIST
SHOW PROCESSLIST is very useful to view the usage of the current database connection and various status information. SHOW PROCESSLIST; Only the first 100 items are listed. If you want to list all, please use SHOW FULL PROCESSLIST;
Attribute columns and meanings:
id | An identifier, very useful when you want to kill a statement. |
---|---|
user | Display the current user. If you are not root, this command will only display the sql statements within your authority. |
host | Shows which IP and which port this statement is sent from. Can be used to track the user who posted the problematic statement. |
db | Displays which database this process is currently connected to. |
command | Displays the executed command of the current connection, usually sleep, query, and connect. |
state column and its meaning, the status listed by mysql:
Checking table | is Check the datasheet (this is automatic). |
---|---|
Closing tables | The modified data in the table is being flushed to disk, and the exhausted table is being closed. This is a quick operation, but if this is not the case, you should verify that the disk space is full or that the disk is under heavy load. |
Connect Out | The replication slave server is connecting to the master server. |
Copying to tmp table on disk | Since the temporary result set is larger than tmp_table_size (default 16M), the temporary table is being converted from memory storage to disk storage to save memory. . |
Creating tmp table | A temporary table is being created to store part of the query results. |
deleting from main table | The server is performing the first part of a multi-table delete and has just deleted the first table. |
3.SHOW STATUS LIKE 'InnoDB_row_lock%'
InnoDB's row-level lock status variable.
InnoDB's row-level lock status variable not only records the number of lock waits, but also records the total lock duration, the average duration each time, and the maximum duration. In addition, there is a non- The cumulative status amount shows the number of waits currently waiting for a lock. The description of each status quantity is as follows:
- InnoDB_row_lock_current_waits: the number of locks currently waiting for;
- InnoDB_row_lock_time: the total lock time from system startup to now;
- InnoDB_row_lock_time_avg: the average time spent waiting each time;
- InnoDB_row_lock_time_max: the time spent waiting for the most common time from system startup to now;
- InnoDB_row_lock_waits: the total number of waits from system startup to now ;
For these five status variables, the more important ones are InnoDB_row_lock_time_avg (average waiting time), InnoDB_row_lock_waits (total number of waiting times) and InnoDB_row_lock_time (total waiting time). Especially when the number of waits is high and the length of each wait is not small, we need to analyze why there are so many waits in the system, and then start specifying an optimization plan based on the analysis results.
If you find that the lock contention is serious, such as the values of InnoDB_row_lock_waits and InnoDB_row_lock_time_avg are relatively high, you can also set InnoDB Monitors to further observe the tables and data rows where lock conflicts occur, and analyze the reasons for the lock contention.
4.SHOW ENGINE INNODB STATUS
SHOW ENGINE INNODB STATUS command will output a lot of information currently monitored by the InnoDB monitor. Its output is a single string, without rows and columns, and the content It is divided into many small sections, each section corresponding to information about different parts of the innodb storage engine. Some of the information is very useful for innodb developers.
There is a section LATEST DETECTED DEADLOCK, which is the last recorded deadlock information, as shown in the following case:
- ##"(1) TRANSACTION" is displayed Information about the first transaction;
- "(1) WAITING FOR THIS LOCK TO BE GRANTED" displays the lock information that the first transaction is waiting for
- "(2) TRANSACTION" displays the second Transaction information;
- “(2) HOLDS THE LOCK(S)” displays the lock information held by the second transaction;
- “(2) WAITING FOR THIS LOCK TO BE GRANTED" displays the lock information waiting for the second transaction
- The last line indicates the processing result, such as "WE ROLL BACK TRANSACTION (2), indicating that the second transaction was rolled back.
CREATE TABLE contacts( contact_id INT AUTO_INCREMENT, first_name VARCHAR(100) NOT NULL comment 'first name', last_name VARCHAR(100) NOT NULL, email VARCHAR(100), phone VARCHAR(20), PRIMARY KEY(contact_id), UNIQUE(email), INDEX phone(phone) , INDEX names(first_name, last_name) comment 'By first name and/or last name' );The stored procedure inserts fifty thousand Piece of data:
CREATE PROCEDURE zqtest ( ) BEGIN DECLARE i INT DEFAULT 0; DECLARE j VARCHAR ( 100 ) DEFAULT 'first_name'; DECLARE k VARCHAR ( 100 ) DEFAULT 'last_name'; DECLARE l VARCHAR ( 100 ) DEFAULT 'email'; DECLARE m VARCHAR ( 20 ) DEFAULT '11111111111'; SET i = 0; START TRANSACTION; WHILE i < 50000 DO IF MOD ( i, 100 ) = 0 THEN SET j = CONCAT( 'first_name', i ); END IF; IF MOD ( i, 200 ) = 0 THEN SET k = CONCAT( 'last_name', i ); END IF; IF MOD ( i, 50 ) = 0 THEN SET m = CONCAT( '', CAST( m as UNSIGNED) + i ); END IF; INSERT INTO contacts ( first_name, last_name, email, phone ) VALUES ( j, k, CONCAT(l,i), m ); SET i = i + 1; END WHILE; COMMIT; END;Use show index from contacts; and the result is as follows:
Table name | |
---|---|
The unique index is 0, and other indexes are 1. The primary key index is also the only index. | |
Index name. If the names are the same, it means it is the same index and it is a joint index. Each row represents a column in the joint index. | |
The column sequence number in the index, starting from 1. It can also indicate the order of the column in the joint index. | |
Index column name, if it is a joint index, it is the name of a certain column | |
How the column is stored in the index, It probably means character order. | |
The number of different values on an index is called "cardinality", also known as distinction degree, the larger the base, the better the index distinction. The statistics of this value are not necessarily accurate and can be corrected using ANALYZE TABLE. | |
prefix index. If the column is only partially indexed, the number of characters indexed. NULL if the entire column's values are indexed. | |
How keywords are compressed. NULL if not compressed. Compression generally includes compression transport protocols, compressed column solutions and compressed table solutions. | |
If the column value can contain null, YES | |
Index structure Types, common ones include FULLTEXT, HASH, BTREE, RTREE | |
Comments |
The above is the detailed content of Common SQL statements for database optimization in MySQL (summary sharing). For more information, please follow other related articles on the PHP Chinese website!

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

SQL commands in MySQL can be divided into categories such as DDL, DML, DQL, DCL, etc., and are used to create, modify, delete databases and tables, insert, update, delete data, and perform complex query operations. 1. Basic usage includes CREATETABLE creation table, INSERTINTO insert data, and SELECT query data. 2. Advanced usage involves JOIN for table joins, subqueries and GROUPBY for data aggregation. 3. Common errors such as syntax errors, data type mismatch and permission problems can be debugged through syntax checking, data type conversion and permission management. 4. Performance optimization suggestions include using indexes, avoiding full table scanning, optimizing JOIN operations and using transactions to ensure data consistency.

InnoDB achieves atomicity through undolog, consistency and isolation through locking mechanism and MVCC, and persistence through redolog. 1) Atomicity: Use undolog to record the original data to ensure that the transaction can be rolled back. 2) Consistency: Ensure the data consistency through row-level locking and MVCC. 3) Isolation: Supports multiple isolation levels, and REPEATABLEREAD is used by default. 4) Persistence: Use redolog to record modifications to ensure that data is saved for a long time.

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

InnoDB effectively prevents phantom reading through Next-KeyLocking mechanism. 1) Next-KeyLocking combines row lock and gap lock to lock records and their gaps to prevent new records from being inserted. 2) In practical applications, by optimizing query and adjusting isolation levels, lock competition can be reduced and concurrency performance can be improved.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment