mysql -u root -p
Step 5: Verifying the KillAfter running this command, you’ll be prompted to enter a password. Paste or type the MySQL root password you retrieved from your RunCloud dashboard. You’ll be greeted with the MySQL monitor prompt (mysql>
) if the credentials are correct.📖 Suggested read: How to Connect a MySQL Database to PHP (A Developer’s Guide)
- View currently running processes using SHOW PROCESSLIST.
- Identify the specific slow query or problematic process ID.
- Safely terminate (KILL) the query when required.
The thread will disappear shortly after showing the ‘Killed’ state. However, if you used KILL QUERY and the thread persists, it might indicate the query itself is resistant to termination in its current state. In such scenarios, you can use the more forceful KILL CONNECTION command to terminate the connection and release its resources.
Table of Contents
- 1 Prerequisites
- 2 How to Kill MySQL Queries via Command Line
- 3 Important Considerations and Best Practices for Killing MySQL Queries
- 4 Final Thoughts
- 5 Frequently Asked Questions About Managing MySQL Queries
- 5.1 How can I list only queries that are running longer than a certain time in MySQL?
- 5.2 Is it better to kill a query manually or let MySQL’s timeout settings handle it?
- 5.3 How often should I monitor running MySQL queries?
- 5.4 Will killing a query cause data loss or corruption?
- 5.5 What’s the safest way to kill a problematic query?
- 5.6 How can I prevent long-running queries in the future?
Prerequisites
You can filter the information_schema.PROCESSLIST table directly. For example: SELECT id, user, time, info FROM information_schema.PROCESSLIST
This shows queries that have been active for more than 60 seconds, making it easier to detect slow or stuck queries.
WHERE command = 'Query' AND time > 60;
- Shell access to your server
- MySQL user account with specific privileges. For administrative tasks like this, it is common to use the MySQL root user as it has all the necessary privileges.
How to Kill MySQL Queries via Command Line
Step 1: Connecting to Your MySQL Server via Command Line
RunCloud provides a simple, powerful platform that handles the heavy lifting of server management for you. Instead of spending hours troubleshooting MySQL issues through command-line sessions, you can:In production environments, continuous automated monitoring is ideal. RunCloud’s Slow Script Monitoring can alert you to persistent slow queries without constant manual checks. Manual investigation should be triggered whenever performance drops or after major deployment changes.
mysql
: Invokes the MySQL command-line client program.-u root
: Specifies that you want to log in as the MySQL user named root. Replace root if you are using a different administrative MySQL user.-p
: Tells the client to prompt you for the password. It’s more secure than typing the password directly in the command line.
If you are using RunCloud, you can use the Slow Script Monitoring functionality from your RunCloud dashboard to identify slow database operations over time. This method is ideal for less technical users as it doesn’t require connecting to your server via SSH or performing any other command-line operations.You can access the MySQL command-line interface via SSH once you’ve connected to your server. The most common way to connect locally is using the MySQL root user. Open your SSH terminal and execute the following command:

Step 2: Viewing Running Processes in MySQL
The most straightforward way to do this is to run SHOW PROCESSLIST; again immediately. If the kill was successful, the process ID you targeted should no longer be in the list. After issuing a KILL QUERY or KILL CONNECTION command, you must confirm that it worked.Once you have this query text, the next critical step is understanding its execution plan. In a separate MySQL session, execute EXPLAIN <query_text>;
to get an overview of your SQL command. Replace the <query_text>
with the SQL statement you retrieved.This is generally the preferred first attempt. This command tries to terminate only the specific statement that the thread is currently executing, leaving the connection itself open. This is less disruptive to the connecting application.
- Id: This is the unique identifier for the connection thread. You will need this number later if you decide to terminate a query or connection using the KILL command.
- User: Shows the MySQL username associated with the connection thread. This helps you trace the query back to a specific application user or system process.
- Host: Displays the hostname or IP address (and port) from which the connection originates. This is useful for identifying queries coming from specific application servers, cron jobs, or even unexpected locations.
- DB: This column indicates the thread’s current default database. If no database is selected, it will be NULL.
- Command: Describes the type of command the thread is currently executing. For example, the query command means that the thread is actively executing an SQL statement.
- Time: This is one of the most important columns for performance troubleshooting. It tells us the amount of time (in seconds) that the thread has spent in its current state. For ‘Query’ states, a high ‘Time’ value is a strong indicator of a long-running, potentially problematic query.
- State: This column provides more granular details about what the thread is doing within its current command. Some states are benign (starting, checking permissions), but others often point towards bottlenecks or issues:
- System lock: The query is waiting to acquire a lock on a table or row currently held by another thread. This is a common cause of application hangs.
- Sending data: The thread is processing and sending results back to the client. If this state persists for a long time, it might indicate a query returning a huge result set or network latency.
- Writing to net: Similar to sending data, indicates network transfer activity.
- Info: This column displays the actual SQL statement being executed by the thread.
For example, if process ID 12345 is running a slow query, you would run:

While the MySQL command-line tool provides a direct way to manage running queries, using the KILL command should always be done thoughtfully and with an understanding of the potential repercussions.

But even with the right techniques, managing servers directly through the terminal takes time, demands technical expertise, and leaves too much room for human error.If the KILL QUERY command doesn’t work or if you need to terminate the entire connection associated with the thread, you can forcefully terminate the connection. This terminates the statement and drops the client connection. Analyze your slow queries using EXPLAIN plans and optimize indexing, query structure, or application code. Additionally, set reasonable limits like max_execution_time and actively monitor performance metrics using tools such as RunCloud’s dashboard.SHOW FULL PROCESSLIST;
SHOW PROCESSLIST;
Thousands of developers and businesses already trust RunCloud to manage their mission-critical servers – and for good reason. It saves time, reduces stress, and gives you peace of mind that your applications are running at their best.The output of either command presents a table with several columns, and understanding these columns is key to identifying problematic queries:Is your application slow? Are users complaining about lag? This slowdown might be because your MySQL server is struggling under the weight of a long-running or problematic database query.We’ll guide you through using the command line to:Now that you’re connected to your MySQL server via the command line, you can run the SHOW PROCESSLIST command to get a snapshot of all the active connections (threads) to your database server and what they are doing at that precise moment. Simply type the following at the mysql> prompt and press ‘Enter’:
Step 4: Killing the Query or Connection (KILL)
SELECT id, info FROM information_schema.PROCESSLIST
WHERE COMMAND = 'Query' AND TIME > 60
ORDER BY TIME DESC;
Ready to experience better server management? Sign up for RunCloud today.
KILL QUERY <process_id>;
Stop putting out fires. Start focusing on building, growing, and delivering better results – with RunCloud by your side.This EXPLAIN command provides insights into how MySQL intends to execute the query. This can reveal potential bottlenecks, such as full table scans, which would indicate potentially missing indexes on columns used in WHERE or JOIN clauses, inefficient join types, or an unexpectedly high number of rows being examined.📖 Suggested read: How to Change/Reset MySQL Root Password on Ubuntu Linux?

KILL CONNECTION <process_id>;
Before killing a slow or seemingly stuck MySQL query, it’s important to investigate the underlying cause first to ensure it doesn’t happen again. You can begin by copying the complete query text from the ‘Info’ column associated with the problematic process.An alternative method offers more flexibility for users comfortable with SQL.

Once you’ve identified a suspicious query using the command described above, you can use the kill command to terminate the thread and manually restore server performance. In emergencies, manually killing a slow query is faster. However, using server settings like max_execution_time provides automatic safeguards to prevent long-running queries from becoming a recurring problem without human intervention.For instance, to find all actively running queries (Query command) that have been executing for more than 60 seconds, and order them by the longest running first, you could use:⚠️ Warning: Always double-check that you are using the correct process ID obtained from SHOW PROCESSLIST before executing any KILL command. Terminating the wrong process can lead to unexpected application errors or data inconsistencies.MySQL provides the PROCESSLIST table within the information_schema database. You can query this table directly using standard SQL SELECT statements to create powerful filters.
Important Considerations and Best Practices for Killing MySQL Queries
That’s where RunCloud can transform your workflow.
- Kill with Caution: Terminating queries, especially KILL CONNECTION, isn’t always clean. Be aware of the potential consequences:
- Transaction Rollbacks: If you kill a thread executing Data Manipulation Language (DML) statements like INSERT, UPDATE, or DELETE within a transaction (particularly with InnoDB), the entire transaction will typically be rolled back to ensure data consistency. This might be desirable, but it’s important to understand it will happen.
- Application Errors: Applications are often not designed to handle unexpected database connection drops. Killing a connection might result in application-level errors, incomplete operations, or confusing states for end-users.
- Resource Cleanup: While modern storage engines such as InnoDB are good at cleaning up, forcefully killing threads can sometimes, albeit rarely, leave behind temporary tables or orphaned locks that might require manual cleanup later.
- Don’t Kill System Threads: Exercise extreme caution when viewing the process list. You might see threads run by internal system users (e.g., system user, event_scheduler) or replication users (often named repl or similar). Avoid killing these threads unless you have a deep understanding of MySQL internals and are sure it’s necessary and safe, as doing so can disrupt essential background processes, break replication, or even lead to server instability.
- Focus on Root Cause Analysis: Killing a query is almost always a temporary band-aid, not a permanent solution. The most important step after resolving an immediate performance crisis is to investigate why the query was slow or problematic in the first place. Was it due to missing indexes? Poorly written SQL? Inefficient application logic? A bad schema design? It is always recommended that the application code be analyzed to identify and fix the underlying issue. Otherwise, the problem is likely to recur.
- Proactive Prevention with max_execution_time: You can consider setting the max_execution_time system variable. This allows you to define a timeout (in milliseconds). The server will automatically abort queries exceeding this time limit, preventing runaway read queries from consuming excessive resources.
Final Thoughts
KILL QUERY 12345;
Use KILL QUERY <process_id>; first, as it only attempts to stop the active SQL statement without closing the entire database connection. If that fails or the thread is unresponsive, escalate to KILL CONNECTION <process_id>; to terminate the session.Although many third-party tools are available to help with specific problems, in this article, we will use the built-in MySQL command-line tool, which offers a direct, powerful, and quick way to diagnose these issues.;","tagName":"h4"},{"id":"#kill-connection-processid","name":"KILL CONNECTION Killing a query mid-execution won’t typically cause corruption if you use transactional storage engines like InnoDB. However, it may cause the current transaction to roll back, potentially undoing changes made during that session. Always investigate and resolve the underlying issue afterward.Yes, selectively killing idle or stuck queries can immediately free up connections. However, this is a temporary fix. For long-term stability, you should also optimize your database configuration and connection pooling.📖 Suggested read: SQLite vs MySQL vs PostgreSQL (Detailed Comparison)
Frequently Asked Questions About Managing MySQL Queries
Occasionally, you might see the thread you attempted to kill still listed, but with ‘Killed’ appearing in the Command column. This usually means MySQL has registered the kill request but hasn’t terminated the thread yet. This can happen if the thread is engaged in an operation that cannot be interrupted instantly, such as waiting for disk I/O or performing cleanup tasks.
How can I list only queries that are running longer than a certain time in MySQL?
Is it better to kill a query manually or let MySQL’s timeout settings handle it?
How often should I monitor running MySQL queries?
KILL CONNECTION 12345;

Identifying and killing problematic queries manually using MySQL’s command-line tool is an essential skill for any serious developer or server administrator. Knowing how to spot performance bottlenecks quickly can save your application from crashes, downtime, and user frustration.
Will killing a query cause data loss or corruption?
What’s the safest way to kill a problematic query?
How can I prevent long-running queries in the future?
Managing a MySQL server often raises important questions, especially when diagnosing slow queries or optimizing database performance. Below, we answer the most common questions developers and administrators ask about viewing, analyzing, and safely killing MySQL queries.