01 Basic architecture: How is an SQL query executed?

  • Mysql can be divided into two aspects: Server layer and storage engine

  • The Server layer includes connectors, query caches, profilers, optimizers, actuators, and so on

  • The storage engine layer is responsible for storing and extracting data. The architecture is plug-in. When you need to build a table, specify the storage engine you want. The default is InnoDB

1 connector

  • There are times when MySQL memory usage increases very quickly because the memory temporarily used by MySQL during execution is managed in connection objects. These resources are released when the connection is disconnected. If long connections are accumulated, the system may use too much memory and kill it forcibly (OOM). In this case, MySQL restarts abnormally.

  • You can use showProcessList to check connection times and idle connections (connections are idle if there is no action after they are connected)

  • If the client does not perform any operation for a long time, the connector will be automatically disconnected after eight hours

A long connectionIf the client continues to receive requests after a successful connection, the same connection is used all the time.

A short connection is one that is disconnected after a few queries are executed and then re-established the next time

How to solve:

2 Querying Cache

  • Storage is performed by key-value

  • If the query is found, it returns directly

  • The query cache invalidates so frequently that whenever a table is updated, all the query cache on that table is cleared. Not recommended

  • For databases under pressure to update, the hit ratio of the query cache can be very low. Unless your business has a static table, it only updates once in a while. For example, a system configuration table, the query on that table is suitable for query caching

3 analyzer

  • Syntax analysis: The system checks whether the SQL statement you entered meets the MySQL syntax based on the syntax rules

  • Lexical analysis: The parser first does “lexical analysis”. You are entering an SQL statement consisting of multiple strings and Spaces. MySQL needs to identify what the strings are and what they represent.


MySQL knows from the keyword “select” that you typed in. This is a query. It also recognizes the string “T” as “table name T” and the string “ID” as “column ID.”


Parsing: Based on the results of lexical analysis, the parser determines whether the SQL statement you entered meets the MySQL syntax based on the syntax rules.

4 the optimizer

  • Decide which index to use

  • Determine how tables are joined, which tables are joined, and which tables are joined

  • Decide on the program to be implemented

5 actuators

  • First determine permissions

  • If you have permission, open the table and continue. When a table is opened, the executor uses the interface provided by the table engine according to its definition.

  • You’ll see a ROWS_EXAMINED field in the database’s slow query log that shows how many rows were scanned during this statement execution. This value is accumulated each time the executor calls the engine to retrieve the row

To consider

  • Select *fromTwhere k=1; Unknown column ‘k’ in ‘where clause’ At what stage do you think this error was reported?

  • Answer: Profiler phase

02 Logging System: How is an SQL update statement executed

WAL: Logs are written before disks

  • These reviews

1 redo log

  • Two position information
    • Checkpoint:Location where data is flushed
    • The write pos:Write to file 3 and return to file 0
  • InnoDB’s redo log is fixed in size. For example, it can be configured as a group of 4 1GB redo logs. This pink log can record 4GB of operations

role

  • The redo log is used to ensure the crash-safe capability.Innodb_flush_log_at_trx_commit when the parameter is set to 1The redo log is persisted directly to disk for each transaction. I suggest you set this parameter to 1, so that the data will not be lost after MySQL restarts abnormally

Redo log too small

  • If the value of redolog is too small, it indicates that you need to keep pushing the checkpoint, which means that you need to keep flushing the disk, resulting in a large number of random writes, affecting the efficiency

2 binlog

  • Belongs to the Server layer diary, so as long as the use of mysql have bin log

  • When sync_binlog is set to 1, the binlog of each transaction is persisted to disk. I also recommend setting this parameter to 1, so that the binlog will not be lost after MySQL restarts unexpectedly.

  • Binlog is used for archiving and replication

3 Differences between the two types of logs:

  1. Redo logs are unique to InnoDB; Binlog is implemented in the Server layer of MySQL and is available to all engines.
  2. A redo log is a physical log of what was changed on a data page. The binlog is the logical log that records the original logic of the statement, such as “add 1 to the C field on the line ID=2”.
  3. Redo logs are written in a redo log cycle. Binlog can be appended. “Appending” means that the binlog file will be switched to the next one after being written to a certain size without overwriting the previous log.
  4. Binlog is used for archiving and replication, while redolog is used for exception recovery

4 Update operation process

  • There are two phases of commit, redolog to prepare, binlog to commit

5 How do I implement the file rollback operation

The full Binlog is required

First, find the most recent full backup, or if you’re lucky, last night’s backup, and restore from it to the temporary repository. Then, from the backup point in time, take out the backup binlog one by one, and resend to the time before the table was deleted by mistake at noon

To consider

The period of periodic full backup “depends on the importance of the system, some are daily, some are weekly”. So in what context is daily prep more advantageous than weekly prep? Or, what metrics does it affect in the database system?

In the one day mode, the worst case scenario is to apply a one-day binlog. For example, if you do a full backup every day at 0:00, you want to restore a backup that was up to 23:00 last night.

One week for worst case, one week for binlog

Transaction isolation: Why can’t I see you change it?

1 Isolation and isolation level

  • ACID: atomicity, consistency, isolation, persistence

  • Isolation level

  • MVCC needs to be used in conjunction with undoLog. The pointer points to the previous version of the data, and then determines whether the data needs to be displayed based on your transaction version and data version

2 Disadvantages of long transactions

  • Long transactions mean that there are old transaction views in the system. Since these transactions can access any data in the database at any time, any rollback records that may be used in the database must be retained until the transaction commits, which can lead to a large storage footprint.
  • In short, long transactions result in a very large amount of data in Undolog

3 How transactions are started

  • The displayed start transaction begin or Start transaction is combined with commit or rollback
  • Turn autocommit off by setting autocommit = 0 until you commit or rollback

To consider

How to avoid long transactions?

  1. Verify that set Autocommit =0 is used. This validation can be done in a test environment by running MySQL’s general_log and then running random business logic to verify the general_log log. If the framework sets this value, it will provide parameters to control the behavior, and your goal is to change it to 1.

  2. Verify that there are no unnecessary read-only transactions. Some frameworks tend to box any statement with begin/commit first. I’ve seen businesses that don’t need this, but put several SELECT statements into a transaction. This read-only transaction can be removed.

  3. When a service connects to the database, you can run the SETMAX_EXECUTION_TIME command to control the maximum execution time of each statement based on the service estimate. This prevents a single statement from being unexpectedly executed for too long. (Why the surprise? This will be mentioned in a later article.)

  4. Monitor the Information_schema. Innodb_trx table and set the long transaction threshold to alarm/kill if it is exceeded;

  5. Percona pt-kill is a good tool to use.

  6. In the business function test phase, all general_logs are required to be output to analyze the log behavior to find problems in advance.

  7. Set innodb_unDO_TABLespaces to 2 (or greater) if you are using MySQL 5.6 or later. This makes it easier to clean up if a rollback segment is too large due to a really large transaction

04 | construct index (on)

1 Common index models

hash

The hash table structure is suitable for scenarios where there are only equivalent queries

Can not carry out range search, fuzzy query

Orderly array

Ordered array indexes are only suitable for static storage engines, and insertion and deletion operations are very complex

B tree

Unable to implement a range query,

The non-leaf node of the tree has the entire data information of the node, which requires multiple IO

2 InnoDB index model

B + tree

Leaf nodes indexed by primary keys hold entire rows of data. In InnoDB, primary key indexes are also called clustered indexes.

Leaf node contents that are not primary key indexes are primary key values. In InnoDB, non-primary key indexes are also called secondary indexes.

Non-primary key indexes need to return to the table if there is no index overwrite


Index maintenance

  • When inserting and deleting data, you need to insert and delete data wherever there is an index

Why do YOU need to rebuild an index

An index may be deleted, or a page split, resulting in a void in the data page. The process of reconstructing an index creates a new index and inserts the data in order, so that the page utilization is maximized. This means that the index is more compact and saves space

To consider

  • The method of rebuilding index K is reasonable and can achieve the purpose of saving space.
  • However, the process of rebuilding the primary key does not make sense. Whether a primary key is deleted or created, the entire table is rebuilt. So if you execute these two statements in tandem, the first statement is done for nothing. These two statements, you can replace them with this statement
  • Alter table T engine=InnoDB

05 | construct index (below)

1 Index overwrite

When a person’s name and ID card are queried at the same time

2 Left-most prefix rule

3 Index push down

  • In simple terms, index push-down means that the index level is filtered once, and then the table is returned
  • If there is an associative index (name, age), you need to query the first name is zhang and the age is less than 10 years old
  • If there is no index push down, all the information will be returned to the table to determine the age less than 10 years old after the first name is zhang
  • If the index is pushed down, the index level will continue to judge, and the age less than 10 years old will return to the table (reduce the number of return to the table).

  • No push down

  • An index pushdown

To consider

  • The answer
  • C-a index: returns the first statement based on the a index after the first statement completes the C index
  • C -b index: can let the second statement through the C index, directly according to the b index information, return the first

06 | global lock and table lock: add a field to watch how there are so many obstacles?

  • Mysql can be divided into three types of global locks, table locks, and row locks

1 the global lock

  • For global logical backup
  • Flush tables with Read Lock (FTWRL), which makes the entire library read-only

Mysqldump backup tool mysqldump backup tool mysqldump

2 table locks

Table locks

lock tables xxx read/write
Copy the code

Metadata Locking (MDL)

  • Do not need to display the specified, will be added automatically
  • Purpose: THE purpose of MDL is to maintain consistency of data
  • Add, delete, change and check the table operation, add MDL read lock, add MDL write lock when the table structure changes

Adding fields to small tables can cause the library to break down

A — added an MDL read lock

B – added an MDL read lock

C – “MDL write lock cannot be added, blocked

D – “the MDL write lock will block all subsequent queries

  • If the queries on a table are frequent and the client has a retry mechanism, meaning that a new session will be requested after a timeout, the library threads will quickly fill up

How do I add fields safely

  • Alter TABLE statement set the wait time, if the specified wait time can get the MDL write lock, do not block the following business statement, abandon. The process is then repeated by the developer or DBA with a retry command

Intent locks

  • Intent shared lock, a transaction that wants to assign a shared lock to some rows of the database needs to assign an intent shared lock first
  • An intentional mutex, a transaction that wants to add a mutex to some rows in the database, needs to add an intentional mutex
  • Purpose of intentional lock: When it is necessary to apply A row-level lock on A table, it is necessary to determine whether there is an internal row lock and traverse all data, which is too slow. With intentional lock, object A will obtain the row-level X lock on A certain record of the table firstTable leveltheIX lockAnd then getX lock

07 | row locking merits: how to reduce the row locks the performance impact?

  • Note:Row locks are added when the transaction needs them and released at the end of the transaction, so if you need to acquire more than one lock in a transaction, place smaller locks in front and larger locks in back.

Deadlocks and deadlock detection

  • Characteristics of deadlock detection: CPU is under pressure, but very few transactions are executed
  • Assuming 1000 concurrent threads are updating the same row at the same time, deadlock detection operations are on the order of 1 million. Although the final result of the test is no deadlock, it consumes a lot of CPU resources in the process. As a result, you can see high CPU utilization, but not many transactions per second
  • Solution:
    • Turn off deadlock detection directly: make sure there is no deadlock
    • Control concurrency
    • Split data (update 1 data, update 10 data, the sum of 10 data is 1 data)

To consider

  • Delete the first 10000 rows from the table
    • The first option is to delete itdelete fromTlimit 10000
    • The second scenario is executed in 20 connectionsdelete fromTlimit 500
    • The third scenario is performed 20 times in one connectiondelete fromTlimit 500
  • The answer:
    • The first scheme locks the first 10,000 pieces of data
    • The second scenario creates lock conflicts
    • The third plan is the best, the minimum granularity of the lock, each time a little lock, and then execute on the release

08 | transaction is isolated or not?

1, MVCC

  • The dashed boxes in the figure show four versions of the same row, the latest version is V4, the k value is 22, it was updated by the transaction ID 25, so its rowtrx_id is also 25, and the three arrows are UndoLog

The visibility of MVCC can be judged quickly

  • The view is created when the SELECT is first initiated

  • All previously committed transactions are visible to select

  • After select, committed transactions are not visible

  • Changes to their own transactions are visible

  • example

  1. If the view is not created initially, just start transaction in order
  • For transaction A, the view is not created when the transaction is started
  • For transaction B, the transaction is not created when it is started
  • K starts at 1, so C is updated and k is equal to 2
  • Transaction B updates, queries but does not commit, but transaction B gets k = 3
  • K =2; k =2; k =2; k =2
  1. If the transaction is created as shown above, the view is created
  • For transaction A, A view is created
  • For transaction B, a view is created
  • For event C, the transaction K = 2 is committed
  • For event B, there is another update, and the changes to its own transaction are visible so K =3;
  • For event A, k=1 when the view was created, so the query will be 1 again

Remember two rules two rules

  1. The view is created during select time, and all committed transactions are visible before the view is created
  2. Self-committed transactions can be seen by themselves

09 | normal index and the only index

1, the query process performance gap is not large

  • A unique index can be returned if it finds one
  • A normal index needs to find the first one to return
  • In terms of performance, there is not much difference, since InnoDB defaults to 16KB for each data page, at most the next node, one more pointer search

2. There is a big performance gap in the update process

  • A unique index that must be pulled into memory for updating
  • A common index that writes the data update operation to change Buffer and then returns to wait for the operating system to refresh the data in ChangeBuffer.

  • The change buffer uses memory in the buffer pool, so it cannot grow indefinitely. The size of change buffer can be set dynamically with innodb_change_buffer_max_size. When this parameter is set to 50, it means that the changeBuffer can occupy at most 50% of the buffer pool.

3. Performance analysis of Changebuffer

  • If the data is queried immediately after the data is written, the data will be pulled from the disk to the memory and updated through changeBuffer. In this case, the performance is low
  • If the query is not done immediately, the performance will be higher and the system I/O times will be reduced. In particular, when using mechanical hard disks, the effect of change Buffer mechanism is very significant

4. Change Buffer and Redolog

  • If data page1 is in memory, update memory directly and write redolog
  • If page2 is not in memory, in the changeBuffer area of memory, write “I want to update page2”, and then add the contents of changge buffer to redolog as well

10 | Mysql index analysis

1. Index selection logic

  • The number of rows scanned is not the only criterion. The optimizer also takes into account factors such as whether to use temporary tables and whether to sort.

2. How to judge the scanning function

  • MySQL does not know exactly how many records meet this condition until it actually starts executing the statement, but can only estimate the number of records based on statistics.

  • This statistic is the “differentiation” of the index. Obviously, the more different values there are on an index, the better the index is differentiated. The number of different values in an index is called cardinality.

  • We can use the showindex method to see the cardinality of an index.

  • How does Mysql get cardinals?
    • Sampling statistics, randomly select N data pages, count the different values on these data pages, get an average, finally multiply by the number of data, get the base of the index
  • If the statistical information differs greatly, use the Analyze command to refresh the statistics

3. Index selection exception and handling

1. Forcibly select a force index

2. Try using the Analyze Table to refresh index statistics

3, create a new index, delete the previous error index

11 | how to add a string field index

  • conclusion
    • Creating a full index directly takes up more space, but in some cases you do not need to return to the table

    • Creating a prefix index saves space but increases the number of queries

    • Count the differences between different prefixes and select them

    • Create indexes in reverse order, saving space, but losing range queries

  • In general, string field indexes need to be created based on your business needs

To consider

12 | MySQL moment caton

  • Mysql caton is analyzed from three aspects

    • memory

      • When memory is full, a page flush occurs (dirty pages need to be flushed to disk), which can cause stuttering

      • InnoDB uses a buffer pool for memory management. There are three types of memory pages in the buffer pool

        • Those not in use can be overwritten directly

        • Yes, but in a hurry. It can be overwritten

        • Used dirty page, need to brush the disk (this time may occur stall)

    • Disk I/o

      • There are roughly three types of disk-related operations

        • Log writing sequence: Generally, what problems do not occur, good performance

        • Disk random read: go is the index, generally also relatively fast, will not appear what problem

        • Memory flush, random write: The impact is very large, need to flush dirty pages in memory back to disk, I/O overhead

    • CPU

      • The CPU is full
        • Deadlock detection, in which the CPU usage is very high but the number of events executed is small

        • Some complex operations, such as join and group by, will be delayed for a long time rather than a moment, and the DISK I/OS will be large

  • conclusion

    • In general, there are two possibilities for the instantaneous lag mainly occurring when the system memory brushes dirty pages

      • One is that the memory is insufficient and must be cleaned to have new space for the data pulled from the disk

      • One is that Redolog’s checkpoint setting is too small

    • The solution

      1. Innodb_io_capacity Sets the read and write capability of the system

      2. Innodb_max_dirty_pages_pct is the maximum number of dirty pages, half set to 75%

      3. Innodb_flush_neighbors flushes dirty pages together

To consider

  • What’s wrong with redolog being set too small

  • A redo log is written every time a transaction commits. If the redo log is set too low, it quickly fills up, which is the state of the graph below

The “rings” will soon be full, and write POS is always chasing CP.

– At this point, the disk pressure is very low, the memory pressure is very low, but the database has intermittent performance degradation (intermittent lag)

13 | database to delete data commonly, but take up the space is the same

1. Data page reuse

  • Data page reuse: When an entire data page is deleted, the data page is marked as reusable and can be reused anywhere in the B+ tree

2. Record reuse

  • Record reuse: Deleted records do not reclaim space, but only leave a space for the next data insertion

  • What if we use the delete command to delete the entire table? As a result, all data pages are marked as reusable. But on disk, files don’t get smaller.

3. Rebuild the table

  • To reduce memory space, you can use a rebuilt table

  • alter table A engine=InnoDB

To consider

  • What is the cause of the larger storage footprint after table reconstruction?

  • When rebuilding tables, InnoDB does not fill the entire table, leaving 1/16 of each page for subsequent updates. In other words, the rebuilt table is not the “most” compact.

14 | count (*) so slowly

  • MyISAM saves the total number of rows in a table on disk, so it returns that number directly when it executes count(*).

  • The InnoDB engine is a bit of a hassle. When it executes count(*), it reads the data line by line from the engine and accumulates the count

1 Why can’t Mysql tell you how many entries there are in a single record

  • Because of MVCC, the query data returned by a transaction is different at different times

2. Different use of count ()

  • In terms of velocity
    • Count (id)

15 | log and indexes related problem

1. What happens when mysql restarts abnormally during two-phase commit

  • If the redo log transaction is complete and has a commit representation, it is committed
  • If only a complete prepare is present in the redo log, the bin log for the transaction is complete
    • If the binlog is complete, commit the transaction and set redo log to commit
    • If the binlog is incomplete, the transaction is rolled back

2. If until bin log is complete

  • The statement bin log has a commit at the end
  • The bin log in row format has an XID at the end

How do redo logs and bin logs relate

Through the XID

16 | order by workflow

  • Give the definition of a table:

  • Give the SQL statement

Using filesort

  • Initialize sort_buffer and place three fields: name city age
  • Through the indexhangzhouFind the first primary key ID that matches
  • Select name city age from sort_buffer
  • Repeat until city is not satisfied
  • Quicksort the data in sort_buffer by the name field and select 1000 rows

2. Rowid sorting

  • In simple terms, when the single line of the sort is too long, only the primary key and the fields to be sorted are extracted into the sort_buffer for sorting

3. Index method

Create (city, name) index, can be directly selected through the way of index, no need to sort, this is related to the underlying structure of B+ tree

To consider

  • If you already have city_name(city, name) in your table, then you want to look at the names of all the residents of hangzhou and Suzhou, and sort them by name to display the top 100 entries. If the SQL query is written like this:

  • Mysql > select * from t where city in (‘ hangzhou ‘, ‘suzhou’) order by name limit 100;

  • Ask can walk sort?

  • Answer: will not go sort, because want to query is hangzhou and Suzhou

  • How to modify?

  • Select * from t where city=” hangzhou “order by name limit 10100;

  • Select * from t where city=” suzhou “order by name limit 10100;

  • Merge sort the two statements above

17 | how to correctly display random news

  • APP has a requirement to randomly extract three words from the data table, which is relatively large and supports insert and delete operations.

Select * from temporary table order by rand ()

  • select word from words order by rand() limit 3;

Full table scan required!!

  • Execution process:
    1. A random number greater than 0 and less than 1 is generated by calling the rand () function in sort_buffer
    2. Sort by primary key and generated random number, and then back to the table
    3. Back to the first three

2. Use disk temporary tables

  • Order by rand () is the same order by rand ()

3. Disk temporary tables and memory temporary tables

  • Temporary tables are used by MySQL to store some intermediate result sets. Temporary tables are only visible to the current connection. When a connection is closed, MySQL automatically drops the table and frees all space. Why temporary tables are created: Complex SQL causes a large number of temporary tables to be created. Temporary tables are classified into memory temporary tables and disk temporary tables.

  • The memory engine is used for memory temporary tables, and the MyISAM engine is used for disk temporary tables. (InnoDB can also be used for disk temporary tables. Internal_tmp_disk_storage_engine controls which storage engine is used. Innodb storage engine by default since mysql5.7.6, myISam storage engine by default in previous versions). The Created_tmp_disk_tables and Created_tmp_tables parameters are used to see how many disk temporary tables are generated and all the temporary tables (memory and disk) are generated.

The size of the memory temporary table space is controlled by two parameters: tmp_table_size and max_heap_table_size. The maximum size of a temporary table space in memory is generally controlled by the smaller of the two parameters. For temporary tables that are initially created in memory and later moved to disk due to large data, only the max_HEap_table_size parameter controls the maximum size of a temporary table space in memory. There is no size control for temporary tables that are generated directly on disk.

Temporary tables are used by the following operations:

1, Union query

2. For view operations, such as using some TEMPTABLE algorithm, union, or aggregation

3. Subquery

4. Join includes not in, exist, etc

5, query the generated derived table

6. Complex group by and order by

Mysql > create temporary table (select * from table)

8, multiple table updates

GROUP_CONCAT() or COUNT(DISTINCT) statements Mysql also prevents the use of memory table Spaces

Use disk temporary tables directly:

1. The table contains BLOB or TEXT columns

When using union or union all, the select clause has columns larger than 512 bytes

3, Show columns or desc

Random sorting method

  • All sorts through the order by RAND () scheme result in a very complex computation, requiring full table sort and full table scan

  • If you already know the maximum and minimum primary key values, you can select a value by generating X = (m-n)* rand() + N

  • Defect: the above scheme is only suitable for uniform distribution of primary keys, if the primary keys are 1,2,2000,4000, it will not work, so the compression operation is needed.

  • You figure out that at sign C is the total function of the table, and then you pick a random value based on the total number of rows, and you go to that random value limit 1. You can.

18 | why these SQL statements logic, the same performance but great differences?

1, add a function to the field operation, directly do not go index

  • Modify it to pass the index operation

Implicit type conversion

  • Therefore, it will not go to the index. You need to change it to “110717”

In MySQL, when you compare a string to a number, you convert a string to a number.

Tradeid will become a number and cannot be indexed

3. Character coding conversion

  • The character set UTF8MB4 is a superset of UTF8, so when the two types of strings are compared, MySQL converts the utF8MB4 character set to utF8MB4 character set and then compares them.

19 | why do I query a row only perform so slowly

1. Simple query statements are not put back for a long time

  • There is a high probability that the table is locked
  • Show ProcessList to see the status of the current thread

  • Write lock for metadata

  • Such as the refresh

  • Such as row locks

  • Session A took the row lock, transaction B cannot query

    • Innodb can query the row lock table and find that the statement executed by the Querey 4 thread locked the current row. Kill 4 to disconnect the current connection and let it be released

2. Query is slow

The query was written incorrectly

  • When C has no index on it, 50000 rows of data need to be traversed

  • Further processing and analysis can be done by adding slow queries to the slow query table

If a snapshot exists, the table must be returned all the time

To consider

  • There are a million rows of data, and the value of B for 100,000 rows of data is 1234567890, assuming it is executed now

  • The statement reads like this:

  • Q: How does MySql perform

20 | magic to read

  • Table:

  • Remember that phantom reads are mainly for insertion and non-repeatable reads are mainly for modification

  • Phantom reading is solved by gap locking and row locking

Consider:

c: 5 10 15 20 25

Where do you scan, you need to add a gap lock. C scans 10, okay

21 | why do I only change a line statements, lock so much?

1 Basic rules for locking

  1. Principle 1: The basic unit of locking is next-key lock. I hope you remember that the next-key lock is a front-open and back-closed interval.

  2. Principle 2: Only objects accessed during lookup are locked.

  3. Optimization 1: equivalent query on index, next-key lock degenerates to row lock when unique index is locked.

  4. Optimization 2: the next-key lock degrades to a gap lock when the last value does not meet the equivalence condition

  5. One bug: Range queries on unique indexes access up to the first value that does not meet the criteria.


  • Conclusion:

  • First of all, the lock is left open right closed, all objects can be scoped will be locked

  • Second: if the equivalent query is matched when it is the only index, it will become a row lock with only one lock. When it is not matched, it will degenerate into a gap lock

  • Finally: If it is an equivalent query, if it is a common index that needs to access the first index that does not meet the conditions, when the closure on the right cannot be obtained, the gap lock is backward


Case 1: Unique index equivalent query gap lock

  • According to principle 1, the lock unit is next-key lock, session A lock range is (5,10);

  • At the same time, according to optimization 2, this is an equivalent query (id=7), and id=10 does not meet the query conditions, so next-key lock degenerates into a gap lock, so the final lock range is (5,10).

  • If this is the id

Case 2: Non-unique index equivalent lock

According to the principle of

  1. The lock unit is next-key lock, so (0,5) is assigned a next-key lock.
  2. Note that c is a normal index, so only access to c=5 cannot be stopped immediately. You need to traverse right until c=10. According to principle 2, everything accessed should be locked, so (5,10) should be next-key locked.
  3. But at the same time, this conforms to optimization 2: equivalence judgment and traversal to the right. The last value does not meet the equivalence condition of C =5, so it degenerates into a gap lock (5,10).

Case 3 unique index range lock

0 — 5 — 10 — 15 — 20 — 25

  • The primary key index is the only one to find the first row with id=10, so it should be next-key lock(5,10).

  • According to optimization 1, the equivalent condition on the primary key ID degenerates into a row lock, and only the row lock with id=10 is added

  • Id =15, so next-key lock(10,15) is required. — Bug unique index range access to the first condition is not met

Session A The scope of the lock is primary key index, row lock id=10 and next-key lock(10,15). So in this case, session B and session C you can understand

The first session A locates and searches the row whose ID =10 as an equivalent query, while the right scan to the row whose ID =15 uses A range query.

Case 4: Non-unique index range lock

0 — 5 — 10 — 15 — 20 — 25

When c=10 is used for the first time, A next-key lock (5,10) is applied to index c. The next key lock (5,10) is applied to index c. The two next-key-locks (5,10] and (10,15] on index c.

Case 5: Unique index range lock bug

0 — 5 — 10 — 15 — 20 — 25

  • In principle 1, only (10,15) next-key lock should be placed on the index id, and since id is the only key, the loop should stop at id=15.

  • InnoDB scans forward to the first behavior that does not meet the criteria, that is, id=20. And since this is a range scan, the next-key lock on the index id (15,20) is also locked

  • Lock range (10,20)

22 | MySQL what are the methods to improve the performance of the “go”?

1 Dispose of threads that occupy links but are not working

  • If the number of connections is too high, you can preferentially disconnect connections that have been idle for too long. If this is not enough, consider breaking connections that have been idle for too long within a transaction.

  • In the result of showProcessList, kicking the thread shown as sleep may be lossy

Reduce the loss of connection process

  • Some business code will apply for a large number of database connections in a short period of time for backup, if the database is confirmed to be suspended by the connection behavior, then one possible approach is to let the database skip the permission verification phase.

3 Slow query optimization

  1. Create more appropriate indexes
    • Create an emergency index

  1. SQL not written well

  2. Choose the wrong index

    • Plus force index,

23 | MySQL is how to ensure that data is not lost?

1. Write to binlog

2, redolog write

  • As you can see, each thread has its own binlog cache, but shares the same binlog file

  • Redolog is shared in the redolog buffer in memory

  • The redo log buffer is also in memory. A file system is a place in memory

  • Increase the amount of time you can stay in the write phase to allow more data to be written at once

  • Data in the prepare state is also persisted

  • IO bottleneck:

24 | MySQL is how to ensure the main case of consistent?

1 Flowchart of active/standby mode

2 binlog format

How do you guarantee idempotency

  • In the double principal case, you can write both sides, how do you guarantee idempotency
  • Through the GTID
  • Record the server ID. If the server ID is the same, the server is sent by itself

How to ensure the high availability is 25 | MySQL?

  • The main standby mode

1. Active/standby delay

The most direct manifestation of the master/slave delay is that the slave consumes relay logs more slowly than the master produces binlogs.

2. Source of master/slave delay

  1. In some deployment conditions, the performance of the machine where the standby library is located is worse than that of the machine where the primary library is located
  2. The standby database is under great pressure and undertakes the query task
  3. Deal with big issues
  4. Parallel replication capability of the standby

3. Active/standby switchover

3.1 Reliability Priority

3.2 Availability takes precedence

If I force steps 4 and 5 to be executed at the beginning, that is, before the master/slave data is synchronized, I directly cut the connection to standby database B and make standby database B read and write, then the system will be almost unavailable.

To consider

26 why | for library will be delayed several hours?

If the standby database continues to execute logs at a slower rate than the primary database generates logs, the delay can become an hour. And for a master with a consistently high level of stress, the standby will probably never catch up with the master

1 Prior to Mysql5.5

Only parallel replication is supported

Parallel replication scheme:

  1. Distribute tables === “different tables must be parallel
  2. Distribute by row === if two transactions do not update the same row, they can be executed in parallel on the standby repository. Obviously, this pattern requires that the binlog format be ROW

2 Mysql5.6 parallel replication policy

According to the library in parallel

In the hash table used to determine the distribution policy, the key is the database name

27 | there is something wrong with the main library, from the library?

  • Active/standby multi-slave structure

  • Failure to switch

1 Location-based active/standby switchover

When A breaks down, A2 takes over. In this case, you need to run the change master command on B, C, and D

You need to know the file name and offset of the log corresponding to the master library

So you need to look for synchronization sites

  • However, this synchronization site is inaccurate. It is possible that at that point in time, the binlog has already been sent, and the slave library has already executed, and if you continue to select this synchronization point, the execution will be repeated. A primary key conflict error is displayed, which can be executed by setting the specified error to be skipped

This scheme is not suitable! It is very easy to exist from the standby library not executed statements, you can skip the error method to ignore, error prone, and then MYSQL5.6, the introduction of GTID line improvement

2 Synchronization based on GTID

  • The Global Transaction Identifier (ID) is the unique Identifier of a Transaction that is generated when a Transaction is committed. It consists of two parts:

  • Modify command

  • If master_auto_position=1, the MASTER_LOG_FILE and MASTER_LOG_POS parameters need not be specified in the previous site-based method

  • Synchronous operation

In the case of double M, complete the table structure modification: through GTID

To consider

What are the pit 28 separation |, speaking, reading and writing?

  • Due to the delay of the master/slave synchronization, when the master finishes an update operation, the client immediately initiates a read request, and the read data may be expired

1. Forcibly remove the master library

  • Process according to business requirements

2. Sleep plan

3. Determine the scheme without delay in active/standby mode

Seconds_behind_master Check whether the value is 0. If not, the query request cannot be executed until this parameter is 0

4, such as the main storage point scheme

5. Wait for GTID scheme

To consider

29 | how to determine a database is the problem?

1 Select (1)

  • In fact, the successful return of select 1 only means that the library process is still alive, not that the master library is ok

Concurrent connections and concurrent queries

  • A few thousand concurrent connections doesn’t matter much, just a bit more memory. We should focus on concurrent queries, because too many concurrent queries are CPU killers.

The thousands of connections you see in the result of ShowProcessList refer to concurrent connections. The “currently executing” statement is what we call a concurrent query

2 Check the table

  • In order to detect system unavailability caused by excessive number of concurrent InnoDB threads, we need to find a scenario to access InnoDB. Create a table in the mysql database (for example, health_check) and place only one row of data in it.

  • We can detect database unavailability due to too many concurrent threads. However, we soon run into the next problem, which is that when the space is full, this method doesn’t work well.

  • As we know, update transactions write binlogs, and once the binlog disk is 100% occupied, all update statements and commit statements are blocked. However, the system can still read data normally at this time, in fact, the system is abnormal

3 Update judgment

  • A timestamp field is used to indicate the last time the detection was performed. This update statement looks something like:

  • You can imagine a scenario where the I/O utilization of a log disk is 100%. At this time, the whole system response is very slow, has to master standby switch.

  • But remember that 100% IO utilization means that the system’s I/O is working, and each request has a chance to get the I/O resources to perform its task. However, the update command used in our detection requires few resources, so it may be able to successfully submit the IO resources when it gets them and return them to the detection system before the timeout period of N seconds is reached.

  • Check the system and the update command has not timed out, so it concludes that “the system is fine.” That is, the normal SQL statements on the business system are already executing slowly, but the DBA goes up and sees that the HA system is still working and thinks that the master library is now available.

  • The fundamental reason for this phenomenon is that all of the methods we mentioned above are based on external detection. One problem with external detection, of course, is randomness

4 Internal Statistics

Count the I/O time of each request

You can determine whether the system is normal by setting the REQUEST I/O time threshold

| FAQ (2) of article 30: the lock with a dynamic point of view

1 equal query in inequality condition

Some students raised a question about “equivalent query” : what is the difference between equivalent query and “traversal”? Why is it that in the example of our article, where condition is not equal, there is an equivalent query in this procedure?

0-5-10-15-20

Primary key index search =12 becomes locked (10,15), using unique optimization 15 cannot wait to become (10,15)

Walk to the left, lock the range to 5 (0-5) (5-10) so lock the range (0-15)

What about deadlocks

Partial output from the show engine Innodb status command. This command outputs a lot of information, including the section LATESTDETECTED DEADLOCK, which records the last DEADLOCK information

  • conclusion

In addition to run after 31 | mistaken delete data, also can do?

Procedure 1 Delete data rows by mistake using the delete statement

  • You can use the Flashback tool to recover data by Flashback.

  • The principle of Flashback data recovery is to modify the contents of the binlog and retrieve the original database for replay. And to be able to use it,

  • Ensure that binlog_format=row and binlog_ROW_image =FULL.

2 Use the DROP table or TRUNCate TABLE statement to delete data tables or databases

  • You can also use Flashback to restore data that was deleted using the delete command. However, data deleted using TRUNCate/DROP table and drop database cannot be restored using Flashback

  • In this case, full backup with incremental logging is required to restore the data. This solution requires regular full backups online, with binlogs backed up in real time

3 Delay replication for the standby database

  • If the backup of a library is very large, or the time of the misoperation is longer than the time of the previous full backup, for example, if the misoperation occurs six days after the backup, the logs of the database need to be restored for six days. The recovery time may be calculated by day.

  • The problem with the normal master/slave replication structure is that if a table on the master database is deleted by mistake, this command is quickly sent to all slave databases, causing all slave databases to be deleted by mistake as well. The standby for delayed replication is a special standby. By running the CHANGE MASTER TOMASTER_DELAY =N command,

  • You can specify that the standby database will persist with a delay of N seconds with the primary database. For example, if you set N to 3600, this means that if data is mistakenly deleted on the primary database, and the command is discovered within 1 hour, the command has not been executed on the standby database with delayed replication. In this case, run stop slave on the slave database and skip the misoperation command to recover the required data.

32 | why and kill not to drop statements?

  • There are two kill commands in MySQL:

  • One is kill query+ thread ID, which terminates the statement being executed in the thread.

  • Kill connection + thread ID, where connection can be used by default to disconnect the thread. Of course, if the thread has a statement in progress, it must stop the statement in progress first

1. What does the thread do after receiving a kill

  • Kill does not mean to stop immediately, but tells the thread of execution that the statement is no longer needed to continue execution and can begin “executing stop logic.” It’s going to be in the process of ending

2, kill not to drop the situation

Case 1 the thread did not execute to the state of the thread logic

  • Query C does not terminate successfully, but its network connection is broken

  • The kill_query_C state is changed and a signal is emitted when the kill query C is executed.

  • However, session C is signaled and cannot execute due to insufficient concurrent threads, so there is no way to kill session C

  • When session E executes the kill connection command, it does so.

    1. Set thread 12 state to KILL_CONNECTION;

    2. Shut down the network connection for thread 12. Because of this operation, you’ll see that session C gets a disconnection message at this point

  • kill connection

  • kill query

  • The two things are different

Case 2 terminates logically for too long

33 | I find so much data, the database memory ringing?

  • The server is used to read while sending

1. The process of fetching and sending data on the server

  • If the client does not read data from the socket, the server will stop sending to Clent

Mysql_use_result: The client reads a line, the server sends a line, and continues to query the next line

Mysql_store_result: The server caches the data that needs to be sent locally and sends it gradually

Sending to Clien: Indicates that the client is waiting to receive the result

Sending Data: An operation is being performed

  • The size of the InnoDB Buffer Pool is determined by the innodb_buffer_pool_size parameter. It is recommended to set it to 60% to 80% of the available physical memory. Used to cache the contents and indexes of the table

2. Improved LRU algorithm

  • In the case of full table scan, if the table is large, all data in the Buffer Pool need to be eliminated, which is not friendly to Mysql that is performing business, resulting in a sharp drop in memory hit ratio and the improved LRU algorithm

  • In InnoDB implementation, the whole LRU linked list is divided into young region and old region in a ratio of 5:3. In the figure, LRU_old refers to the first location of the old region, which is 5/8 of the entire list. That is, 5/8 near the head of the list is the young region, and 3/8 near the end of the list is the old region.

  1. In Figure 7, state 1 is to access data page P3. Since P3 is in the Young area, it is moved to the head of the linked list and becomes state 2, just like the LRU algorithm before optimization.

  2. To access a new data page that does not exist in the current list, the data page Pm is still eliminated, but the newly inserted data page Px is placed at LRU_old.

  3. Data pages in the old section should make the following judgment each time they are accessed:

    If the data page has been in the LRU list for more than a second, it is moved to the head of the list;

    If the data page exists in the LRU list for less than 1 second, the position remains the same. The time of one second is controlled by innodb_old_blocks_time. The default value is 1000 milliseconds.

summary

  • Because MySQL uses the logic of calculating and issuing at the same time, it does not save a complete result set on the server for query results with a large amount of data. Therefore, if the client does not read the result in time, it will block the MySQL query process, but will not burst the memory.

  • Inside the InnoDB engine, large queries do not cause memory inflation due to the elimination strategy. In addition, due to InnoDB’s improved LRU algorithm, the impact of cold data on the Buffer Pool can be controlled by full table scanning.

To consider

34 | how can use the join?

  • Both tables have a primary key index ID and an index A, with no indexes on field B. Stored procedure idata() inserts 1000 rows into table T2 and 100 rows into table T1

1 Index Nested-Loop Join

  • I switched to Straight_JOIN to let MySQL execute the query using a fixed join so that the optimizer would only join as we specified. In this statement, T1 is the driver table and T2 is the driven table.

  • 1 select * from t1;

  • Select column A from row R and search in table T2.

  • Take out the rows satisfying the conditions in table T2 and form a row with R as part of the result set;

  • Repeat steps 1 through 3 until the end of table T1 completes the loop.

2 How to select the driver table

N has a bigger effect on the function, so you need to choose a smaller N so you need to use a smaller table as the driver table

3 Simple Nested-Loop Join

Not going to the index

Table A has a normal index on it, but table B has no index. Therefore, table T2 needs to be scanned every time a query is made

4 Block Nested-Loop Join

Because the T2 table has no index

  1. Insert table T1 into join_buffer (select * from join_buffer);
  2. Scan table T2, extract each row from table T2, compare it with join_buffer, and return the rows that meet join conditions as part of the result set

  • You need to put all indexed T1 tables into join_buffer. If they cannot fit into join_buffer, they are added into blocks

  • Steps 4 and 5 in the figure indicate that the join_buffer reuse is cleared.

  • If your JOIN statement is slow, increase join_buffer_size

summary

To consider

Optimization of 35 | join statements?

  • I insert 1000 rows in t1 with a=1001-id for each row. That is, field A in table T1 is in reverse order. At the same time, I insert 1 million rows into table T2

  • Id is the primary key. A is a common index, and B has none

1 Multi-range Read optimization

Is the table lookup a row by row or a batch lookup?

A primary key index is a B+ tree in which only one row of data can be retrieved at a time based on a primary key ID. Therefore, the back table must search the primary key index row by row

2 NLJ optimization == Batched Key Access

The traditional NLJ does not apply to Join_buffer

  • Select a from the driver table T1 and join the driven table T2. That is, for table T2, one value is matched each time. At this point, the advantages of the MRR will not be used.

  • How can I pass more values to table T2 at once? To do this, take more rows from table T1 at once and pass them to table T2.

  • In that case, let’s take some of the data from table T1 and put it in a temporary memory. This temporary memory is none other than join_buffer

3 BNL optimization

  • When the Block nested-loop Join(BNL) algorithm is used, multiple scans of the driven table may be performed. If the driven table is a large cold data table, what impact will it have on the system besides causing IO stress?

  • When we talked about InnoDB’s LRU algorithm, we mentioned that since InnoDB has optimized the Bufffer Pool’s LRU algorithm,

That is, the data page read into memory from disk for the first time is placed in the old area. If the data page is no longer accessed after 1 second, it will not be moved to the head of the LRU list, thus having little impact on the Buffer Pool hit ratio.

  • However, if a JOIN statement using the BNL algorithm scans a cold table multiple times and the statement takes more than one second to execute, the data page of the cold table will be moved to the LRU head when the cold table is scanned again.

  • In this case, the amount of data in the cold table is less than 3/8 of the entire Buffer Pool and can be fully put into the old area.

  • If the cold table is large, another situation will occur: a normally accessed data page will not have a chance to enter the Young region due to the optimization mechanism, and a normally accessed data page will have to be accessed again after 1 second to enter the Young region. However, since our JOIN statement is iterating through disk and weeding out memory pages, data pages that enter the old region are likely to be weeded out in less than a second. As a result, pages in the young section of the MySQL instance’s Buffer Pool are not properly weeded out during this time.

You can consider increasing join_BUFFer_SIZE to reduce the number of scans of the driven table

The influence of BNL algorithm on the system mainly includes three aspects:

  1. The drive table may be scanned for many times, occupying disk I/O resources.

  2. To judge join conditions, M*N comparisons are required (M and N are respectively the number of rows of two tables). If the table is large, it will occupy a lot of CPU resources.

  3. Hot data in the Buffer Pool may be discarded, affecting the memory hit ratio.

A common approach to optimization is to index the join field of the driven table and convert the BNL algorithm to the BKA algorithm

Turn – 4 BNL

  1. Index the driven table into a BKA,
  2. Create temporary table, use index, trigger BKA algorithm

summary

To consider

36 | why can temporary table name repetition?

The difference between a memory table and a temporary table

  • Create table… create table… Engine = the memory. The data in these tables is stored in memory and will be cleared when the system restarts, but the table structure remains. Apart from these two “strange” features, it is a normal table.

  • Temporary tables that can be used with various engine types. If InnoDB engine or MyISAM engine is used for temporary tables, data is written to disk. Of course, Memory engines can also be used for temporary tables.

  • If session A has A temporary table with the same name and A regular table with the same name, the showcreate statement and the add, delete, alter, query statement access the temporary table.

  1. Create temporary table… .
  2. A temporary table can only be accessed by the session that created it and is not visible to other threads. Therefore, the temporary table T created by Session A in the figure is not visible to Session B.
  3. Temporary tables can have the same name as regular tables.
  4. The showtables command does not display temporary tables.
  5. Temporary tables of different sessions can have the same name. If multiple sessions perform join optimization at the same time, there is no need to worry about table creation failure caused by duplicate table names.
  6. There is no need to worry about data deletion. If a normal table is used and the client is abnormally disconnected during process execution or the database is abnormally restarted, you also need to clean up the data tables generated during the process. Temporary tables do not need this extra operation because they are automatically reclaimed.

Lord for copy

Implementationally, each thread maintains its own temporary linked list. In this way, when a table is operated in each session, the linked table is first traversed to check whether there is a temporary table with this name. If there is a temporary table, the temporary table is operated first. If there is no common table, the temporary table is operated first. At the end of the session, execute “DROPTEMPORARY TABLE + TABLE name” for each temporary TABLE in the list.

If the current binlog_format=row, temporary table statements will not be recorded in the binlog. That is, temporary table operations are only recorded in binlog if binlog_format=statment/mixed

In this case, the statement that creates the temporary table is passed to the standby database for execution, so the synchronous thread of the standby database creates the temporary table. The primary database automatically deletes temporary tables when a thread exits, but the standby database synchronizes the thread to run continuously. Create a DROPTEMPORARY TABLE on the primary database and pass it to the standby database.

How do I distinguish between different temporary tables in the standby database

MySQL writes the id of the thread that executed the statement to the binlog. In this way, the application thread in the standby library can know the primary library thread ID that executes each statement and use this thread ID to construct the temporary table

summary

** In practical applications, temporary tables are generally used to handle complex computational logic. Since temporary tables are visible to each thread, there is no need to worry about duplicate names of temporary tables when multiple threads execute the same processing logic. The temporary table can also be deleted automatically when the thread exits, eliminating the need for finishing and exception handling. 六四屠杀

When binlog_format=’row ‘, temporary table operations are not recorded in binlog, which saves a lot of trouble. This can also be a consideration when you choose binlog_format.

37 when | will use internal temporary tables?

1, the Union

create table t1(
id int primary key, 
a int, 
b int,
index(a));
(select 1000 as f) union (select id from t1 order by id desc limit 2);
Copy the code
  • This statement uses union, which takes the union of the results of the two subqueries. Union means that when the two sets are added together, the repeated rows keep only one row

2、 group by

  1. Select * from table where primary key = m; create table where primary key = m;

0. Scan index A of table T1, extract id values of leaf nodes in turn, calculate the result of ID %10, denoted as X;

If there is no row with primary key x in the temporary table, insert a record (x,1); If there is a row in the table whose primary key is X, increment the c value of the row x by 1;Copy the code
  1. After traversal, sort the result set according to field M and return it to the client.

summary

  1. If the result of a group by statement is not ordered, add order byNULL after the statement;
  2. Select * from ‘group by’ where index = ‘temporary’ and ‘filesort’;
  3. If group by requires a small amount of data, try to use only temporary tables in memory. You can also avoid using disk temporary tables by appropriately increasing the tmp_table_size parameter.
  4. If the amount of data is too large, use the SQL_BIG_RESULT prompt to tell the optimizer to get the group by result directly using the sorting algorithm.

38 | all say InnoDB good, that also don’t use the Memory engine?

Why do 39 | on the primary key is not straight?

Where is the increment of 1 stored

AUTO_INCREMENT=2: indicates that id=2 will be generated if auto-increment is required when data is inserted next time.

2 The self-added value cannot be rolled back

If there are two transactions executing in parallel, lock them and apply them sequentially in order to prevent the two transactions from applying for the same increment ID.

  1. If transaction A applies to id=2 and transaction B applies to ID =3, then the auto-increment of table T is 4, and then the execution continues.

  2. Transaction B committed correctly, but transaction A had A unique key conflict.

  3. If transaction A is allowed to roll back the increment ID of table T, that is, to change the current increment of table T back to 2, then we have A situation where there are already rows in the table with ID =3 and the current increment ID is 2.

  4. Next, other transactions that continue will apply to id=2, and then to id=3. At this point, the parenthesis error “primary key conflict” occurs.

To resolve this primary key conflict, there are two methods:

  1. Before applying for an ID, check whether the ID already exists in the table. If it exists, the ID is skipped. However, the cost of this approach is high. The primary key index tree is used to determine whether the id exists.

  2. To extend the lock scope of the increment ID, a transaction must wait until it completes and commits before the next transaction can apply for the increment ID. The problem with this method is that the granularity of the lock is too large, and the system concurrency is greatly reduced.

Therefore, self-appreciation cannot be rolled back

3 Auto-increment lock optimization

Normal INSERT statement, autolock is released immediately after the request;

Similar to the insert… The lock is not released until the end of the select statement

When I do batch inserts,

  • The statement records the inserted statement and does not specify the value of the primary key

  • Insert statement from session B; insert statement from session B; This discontinuous id cannot be executed sequentially in statement binlog format.

  • Libraries are prone to inconsistency

40 | insert statement lock why so many?

44 | FAQ article (3) : say these good questions

Where and On

When using left Jion, the difference between on and WHERE conditions is as follows:

1. The ON condition is a condition used when generating temporary tables, which returns the records in the left table regardless of whether the condition in ON is true. 2. The WHERE condition is used to filter temporary tables after they are generated. At this point, there is no sense of left JOIN (you must return the records from the left table), and all filters are filtered if the condition is not true

3. Inner jion does not have this particularity. If the condition is placed in ON and WHERE, the result set returned is the same

45 | on the id finished?

1 Table definition increment

2 InnoDB system autoincrement

3 XID

4 Innodb trx_id

  • Xids are maintained by the Server layer. InnoDB uses Xid internally in order to be able to link InnoDB transactions with servers. However, InnoDB’s own TRx_ID is maintained separately

  • The core idea of InnoDB data visibility is that each row of data is recorded with its updated TRx_ID. When a transaction reads a row of data, the way to determine whether the data is visible is to compare the trx_ID of the row with the consistency view of the transaction

5 thread_id

  • The logic of thread_id is easy to understand: the system holds a global variable thread_ID_counter, and assigns thread_ID_counter to the thread variable of each new connection.

  • Thread_id_counter defines a size of 4 bytes, so when it reaches 2-1, it resets to 0 and keeps increasing.

  • However, you won’t see two thread_id identical in showProcessList. MySQL assigns a thread_id to a new thread as follows:

summary