,

MySql Troubleshooting Advance Guides

Posted by

Finding and fixing issues with configuration, performance, database connectivity, query optimisation, and other areas can all be part of troubleshooting MySQL issues. This is a detailed tutorial to assist you in troubleshooting common MySQL issues:

Check MySQL Service Status:

Check to see if the MySQL service is available and operating:

systemctl status mysql

With the help of this command, you may get comprehensive details about the MySQL service, such as its status and any possible faults.


To check the status of the MySQL service, you typically use command-line tools provided by your operating system. Here’s how you can do it on a Unix-based system (like Linux) using the systemctl command:

  1. Open Terminal: First, open a terminal window. You’ll use this to enter commands.
  2. Check MySQL Service Status: Use the following command to check the status of the MySQL service:

bashCopy code

systemctl status mysql

This command will provide you with detailed information about the MySQL service, including whether it’s running or not, any errors that may have occurred, and more.

Here’s an example output:

● mysql.service - MySQL Community Server
   Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2024-02-07 10:30:15 PST; 1h 20min ago
 Main PID: 1234 (mysqld)
   Status: "Server is operational"
    Tasks: 32 (limit: 4915)
   Memory: 472.8M
   CGroup: /system.slice/mysql.service
           └─1234 /usr/sbin/mysqld

Feb 07 10:30:14 server systemd[1]: Starting MySQL Community Server...
Feb 07 10:30:15 server systemd[1]: Started MySQL Community Server.

Review MySQL Error Log:

Look for any error messages or cautions in the MySQL error log that could point to problems.

tail -f /var/log/mysql/error.log

You can scroll over the contents of the error log file in the less pager by using this command to open it. Depending on how your system is configured, accessing the log file can require superuser rights (sudo).

Example Output:

2024-02-07T10:30:15.123456Z 0 [ERROR] [example] Error: Table 'example_table' doesn't exist
2024-02-07T10:30:20.123456Z 0 [Warning] [example] Access denied for user 'user'@'localhost' (using password: YES)
2024-02-07T10:30:25.123456Z 0 [Note] [example] Aborted connection 1234 to db: 'example_db' user: 'user' host: 'localhost' (Got an error reading communication packets)

Check MySQL Configuration:

Check for any problems or misconfigurations in the my.cnf or my.ini file that contains the MySQL configuration:

cat /etc/mysql/my.cnf

Suppose we have the following MySQL configuration file (my.cnf):

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mysql/error.log
pid-file=/var/run/mysqld/mysqld.pid
max_connections=1000
max_allowed_packet=64M
innodb_buffer_pool_size=4G
innodb_log_file_size=512M

[client]
port=3306
socket=/var/lib/mysql/mysql.sock

Verify MySQL Version:

Ensure that you are using a supported version of MySQL. Check the MySQL version:

mysql --version

This command will output the version information of the MySQL client that is installed on your machine when you run it in your terminal.

This is an example of a result:

Check Database Size and Usage:

Keep an eye on your MySQL databases’ and tables’ sizes and usage. Utilise programmes such as MySQL Workbench or Mysqltuner to examine database performance.

To check the size and usage of a MySQL database, you can execute SQL queries against the database server. Here’s how you can do it:

  • Connect to MySQL:
mysql -u your_username -p
  • Select Database:
USE your_database_name;
  • Check Database Size and Usage:
SELECT table_name AS `Table`, 
       round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB` 
FROM information_schema.tables 
WHERE table_schema = 'your_database_name';
  • Example Output:

Let’s say we have a database named example_db. Here’s an example output for the above queries:

+------------------------+-------------+
| Table                  | Size in MB  |
+------------------------+-------------+
| table1                 | 23.45       |
| table2                 | 12.34       |
| table3                 | 6.78        |
+------------------------+-------------+

+-------------+
| Size in MB  |
+-------------+
| 42.57       |
+-------------+

Optimize MySQL Queries:

Optimise MySQL Queries: Use tools like EXPLAIN or SHOW PROFILE to identify and improve slow or inefficient MySQL queries.

Improving MySQL query performance is essential if you want to see an increase in database application performance. Here are some general pointers and methods for making MySQL queries more efficient, along with some examples:

  • Use Indexes:
CREATE INDEX idx_name ON table_name (column_name);
  • Limit the Result Set:
SELECT * FROM table_name LIMIT 10;
  • Avoid SELECT
SELECT column1, column2 FROM table_name WHERE condition;
  • Use WHERE Clause Wisely
SELECT * FROM table_name WHERE indexed_column = 'value';
  • Optimize Joins:
SELECT * FROM table1 INNER JOIN table2 ON table1.id = table2.id;
  • Avoid Subqueries:
SELECT column FROM table WHERE id IN (SELECT id FROM another_table WHERE condition);

Rewrite:

SELECT t1.column FROM table1 t1 INNER JOIN another_table t2 ON t1.id = t2.id WHERE t2.condition;
  • Use EXPLAIN:
EXPLAIN SELECT * FROM table_name WHERE indexed_column = 'value';
  • Avoid LIKE with Wildcards at the Start:
SELECT * FROM table_name WHERE column_name LIKE '%value';

Review MySQL User Privileges:

Verify that users have the required permissions to access databases and run queries by checking their MySQL user privileges:

You can query the mysql.user table, which contains details on MySQL user accounts and the privileges that go along with them, to evaluate the privileges granted to users. Here’s how to accomplish it:

  • Connect to MySQL: First, connect to your MySQL server using the mysql command-line client with appropriate credentials (username and password).
mysql -u your_username -p
  • Review User Privileges: Once logged in, you can execute SQL queries against the mysql.user table to review user privileges.
SELECT user, host, authentication_string, plugin, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Grant_priv, References_priv, Alter_priv, Create_tmp_table_priv, Lock_tables_priv, Create_view_priv, Show_view_priv, Create_routine_priv, Alter_routine_priv, Execute_priv, Event_priv, Trigger_priv 
FROM mysql.user;

Select_priv, Insert_priv, Update_priv, Delete_priv, and many more columns that show if a user has particular privileges like select, insert, update, delete, create, drop, grant, etc. are among the many columns linked to user privileges that this query retrieves.

Example Output:

+------------+-----------+-----------------------+-------------+------------+----
| user       | host      | authentication_string | plugin      | Select_priv| Insert_priv| Update_priv| Delete_priv| Create_priv| Drop_priv| Grant_priv | References_priv | Alter_priv| Create_tmp_table_priv | Lock_tables_priv | Create_view_priv | Show_view_priv | Create_routine_priv | Alter_routine_priv | Execute_priv | Event_priv | Trigger_priv |
+------------+-----------+-----------------------+-------------+------------+----
| user1      | localhost | *xxxxxxxxxxxxxxxxxx   | mysql_native_password | Y | Y | Y | Y | Y | Y | N | Y | N | N | N | N | N | N | N | N | N | N | N |
| user2      | %         | *xxxxxxxxxxxxxxxxxx   | mysql_native_password | Y | Y | N | N | N | N | N | N | N | N | N | N | N | N | N | N | N | N | N |
+------------+-----------+-----------------------+-------------+------------+----

In this example:

  • user1 has privileges for SELECT, INSERT, UPDATE, DELETE, CREATE, GRANT, etc.
  • user2 has privileges for SELECT, INSERT, but not for UPDATE, DELETE, or other administrative privileges.
  • *xxxxxxxxxxxxxxxxxx represents the hashed password string.

Test Database Connectivity:

Check whether MySQL can be accessed and operated upon via the command line or client software:

Use the mysql command-line client to connect to your MySQL server. You’ll need the MySQL server hostname or IP address, username, and password.

mysql -h hostname_or_ip_address -u username -p

Once the command has been executed, you will be required to enter your MySQL password. Replace hostname_or_ip_address with the hostname or IP address of your MySQL server and username with your MySQL username.

Example:

mysql -h localhost -u your_username -p

Example Output:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 12345
Server version: X.X.X MySQL Community Server (GPL)

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Check Disk Space:

Ensure there’s enough disk space for MySQL to operate:

df -h

All mounted filesystem details, including filesystem type, total size, used space, available space, and utilisation percentage, will be provided by this command.

Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/sda1      104857600 4852400  99605200   5% /
/dev/sdb1      209715200 1071032 208644168   1% /mnt/data

Monitor MySQL Performance:

Performance monitoring for MySQL is necessary to guarantee optimal database performance. You can keep an eye on MySQL performance using a variety of tools and techniques, such as third-party monitoring programmes and the built-in MySQL tools. Here’s an example of how to use some standard tools to monitor MySQL performance:

  • MySQL Workbench:
  • MySQL Command-Line Client:

Example queries:

SHOW STATUS LIKE 'Threads%';
SHOW PROCESSLIST;
EXPLAIN SELECT * FROM your_table;
  • Third-Party Monitoring Solutions:
  • MySQL Performance Schema:
SELECT * FROM performance_schema.events_statements_summary_by_digest;
  • Slow Query Logs:

Example configuration in my.cnf:

slow_query_log = 1
long_query_time = 1
slow_query_log_file = /path/to/slow-query.log

Review InnoDB Status:

The SHOW ENGINE INNODB STATUS command in MySQL can be used to examine the InnoDB status. This command gives you comprehensive information about the InnoDB storage engine’s current status, including details about locks, transactions, buffer pool usage, and more.

SHOW ENGINE INNODB STATUS;

This script will display a lot of data, therefore for easier examination, it’s usually beneficial to paginate the output or redirect it to a file.

Example Output:

*************************** 1. row ***************************
  Type: InnoDB
  Name:
Status:
=====================================
2024-02-07 12:34:56 0x1234567f7000 INNODB MONITOR OUTPUT
=====================================
Per second averages calculated from the last 25 seconds
-----------------
BACKGROUND THREAD
-----------------
...
...
...

Review MySQL Processes:

The SHOW PROCESSLIST command provides a list of all active connections and their states, making it easy to review MySQL processes. This can be especially helpful in locating lingering queries or processes that can be affecting system performance.

Using the SHOW PROCESSLIST command is as follows:

  • Log in to MySQL: Open your terminal or command prompt and log in to your MySQL server. If you’re logging in locally as the root user, you can use the following command:
mysql -u root -p
  • Show Active Processes: To view the list of active MySQL processes, run the following command at the mysql> prompt:
SHOW PROCESSLIST;
  • Identify Long-Running Processes: Look for processes with a high Time value in seconds, as these are typically the ones that have been running for a long time and might be causing performance issues.
  • Terminate a Specific Process:  If you need to terminate a specific process, you can use the KILL statement followed by the process ID. For example, to kill the process with an ID of 14, you would run:
KILL  14;
  • Terminate All Processes for a Specific User: If you need to terminate all processes for a specific user, you can generate a series of KILL statements and execute them. For instance, to kill all processes for the user ‘root’, you can run:
SELECT CONCAT('KILL ', id, ';')  
FROM information_schema.processlist  
WHERE user = 'root'  
INTO OUTFILE '/tmp/process_list.txt';

Check for Long-Running Queries:

You can use the MySQL command-line client, MySQL Workbench, or a query against the information_schema.processlist table to search for long-running queries in MySQL. Using the MySQL command-line client, you can accomplish this as follows:

SELECT * 
FROM information_schema.processlist 
WHERE command = 'Query' 
  AND time > 60; -- Adjust the threshold as needed (e.g., 60 seconds)

Example Output:

+----+------+-----------+------+---------+------+----------+---------------------
| ID | USER | HOST      | DB   | COMMAND | TIME | STATE    | INFO                                    |
+----+------+-----------+------+---------+------+----------+---------------------
|  1 | user | localhost | db1  | Query   |  120 | Sending data | SELECT * FROM your_table WHERE ...   |
+----+------+-----------+------+---------+------+----------+---------------------

Examine MySQL Indexes:

Check table indexes and optimize them if necessary:

SHOW INDEX FROM tablename;

Inspect MySQL Replication:

You can use a variety of techniques, such as SQL queries, MySQL utilities, and system commands, to examine MySQL replication and confirm its status. Here’s how to see if MySQL replication is active:

SHOW SLAVE STATUS\G

Example output:

*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: master.example.com
                  Master_User: replication_user
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000123
          Read_Master_Log_Pos: 123456789
               Relay_Log_File: slave-relay-bin.000001
                Relay_Log_Pos: 123456789
        Relay_Master_Log_File: mysql-bin.000123
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
                Last_Errno: 0
                Last_Error:
          Exec_Master_Log_Pos: 123456789
              Relay_Log_Space: 123456789
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: 0

Review MySQL Logs for Slow Queries:

You must first enable the slow query log in your MySQL configuration before you can examine the logs for any slow queries. After that, you can find and improve slow-running queries by looking through the logged requests. Here’s how to accomplish it:

SET GLOBAL slow_query_log = 'ON';

Check for MySQL Deadlocks:

Check the error log for deadlocks, or use SHOW ENGINE INNODB STATUS.


To check for MySQL deadlocks, you can examine the MySQL error log or use SQL queries to query the information_schema.innodb_trx table. Here’s how you can do it:

  • Check MySQL Error Log:
  • Query information_schema.innodb_trx:

You can query the information_schema.innodb_trx table to check for active transactions, including any transactions involved in deadlocks

SELECT * FROM information_schema.innodb_trx WHERE trx_state = 'ROLLING BACK';
SELECT * FROM information_schema.innodb_lock_waits;
  • Analyze Deadlock Information:
  • Prevent Future Deadlocks:

Verify MySQL Configuration Parameters:

Examine and modify configuration parameters in light of system resources and workload.

To verify MySQL configuration parameters, you can either use SQL queries to retrieve the current configuration values from MySQL itself or directly inspect the MySQL configuration files (my.cnf or my.ini). Here’s how you can do it using both methods:

  1. Using SQL Queries:
  2. Using Configuration Files:

Consult MySQL Documentation:

For specific concerns, see online resources or the official MySQL manual.

You can use the MySQL command-line client to get direct access to help information or visit the official MySQL documentation website to review the documentation. Here’s how to accomplish it:

  • Official MySQL Documentation Website:
  • MySQL Command-Line Client:
help SELECT

Backup and Restore:

Test restoration techniques and backup databases on a regular basis.

Backing up and restoring MySQL databases is essential for data protection and disaster recovery. There are several methods to perform backups and restores in MySQL, including using native MySQL utilities, third-party tools, and manual methods. Here, I’ll cover the basic steps for performing backups and restores using native MySQL utilities:

  • Using mysqldump for Backup:
  • Using mysql for Restore:
mysql -u your_username -p -e "CREATE DATABASE your_database;"

Then, restore the backup using the following command:

mysql -u your_username -p your_database < backup.sql
  • Additional Options:

Consider Database Maintenance:

Plan routine database maintenance activities, such as clearing out outdated data and optimising tables.

Maintaining your MySQL database is essential to its security, dependability, and performance. It entails a number of activities meant to guarantee data integrity, avoid data corruption, and maximise database performance. The following are some crucial things to keep in mind when maintaining a MySQL database:

  • Regular Backups:
mysqldump -u your_username -p your_database > backup.sql
  • Database Optimization:
EXPLAIN SELECT * FROM your_table WHERE condition;
  • Statistics Collection:
ANALYZE TABLE your_table;
  • Backup and Restore Testing:
mysql -u your_username -p your_database < backup.sql
  • Monitor Database Health:
df -h
  • Update Statistics and Indexes:
ANALYZE TABLE your_table;
  • Security Hardening:
GRANT SELECT, INSERT, UPDATE, DELETE ON your_database.* TO 'user'@'localhost';
  • Data Archiving and Purging:
CREATE TABLE archive_table SELECT * FROM your_table WHERE date < '2023-01-01';
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x