DEV Community

Arthur
Arthur

Posted on

How to Troubleshoot Slow Database Queries on a Linux Server

Hello, I'm Arthur.
A database can become slow even when a Linux server has enough CPU power, memory, and storage.

Users may experience delayed page loading, applications may time out, and background jobs may take longer than expected. In many cases, the problem is not the server itself but the way an application interacts with its database.

Slow queries can result from missing indexes, inefficient SQL statements, excessive database connections, or storage bottlenecks.

In this guide, we'll explore practical ways to identify slow database queries and improve database performance on Linux servers.

1. Identify the Symptoms

Before making changes, understand how the database is behaving.

Common signs of database performance problems include:

  • Web pages taking longer to load
  • Database queries running for several seconds
  • Applications reporting connection timeouts
  • High CPU usage during database operations
  • Increased disk activity
  • A growing number of database connections

Start by checking the overall server resources:

top
Enter fullscreen mode Exit fullscreen mode

Check memory usage:

free -h
Enter fullscreen mode Exit fullscreen mode

Check disk space:

df -h
Enter fullscreen mode Exit fullscreen mode

These commands help identify resource pressure, but they do not explain which SQL query is responsible.

You need to inspect database activity to find the actual cause.

2. Check Active Database Queries

For MySQL or MariaDB, you can inspect currently running queries using:

SHOW FULL PROCESSLIST;
Enter fullscreen mode Exit fullscreen mode

This command displays active database connections and the queries they are executing.

Pay attention to queries that remain active for a long time.

You may notice queries waiting for a lock, scanning a large table, or processing more records than expected.

A single long-running query is not always a problem. Some reports and data-processing operations are naturally expensive.

However, if the same query repeatedly takes too long, it deserves further investigation.

For PostgreSQL, you can inspect active queries through pg_stat_activity:

SELECT
    pid,
    state,
    query_start,
    query
FROM pg_stat_activity
WHERE state = 'active';
Enter fullscreen mode Exit fullscreen mode

This provides a useful starting point for identifying queries that are currently running.

3. Use the Query Execution Plan

One of the most useful ways to investigate a slow SQL query is to examine its execution plan.

For MySQL or MariaDB, use:

EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 1001;
Enter fullscreen mode Exit fullscreen mode

For PostgreSQL, use:

EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 1001;
Enter fullscreen mode Exit fullscreen mode

The execution plan shows how the database intends to retrieve the requested data.

Look for operations such as full table scans, inefficient joins, or unexpectedly large numbers of rows being processed.

A full table scan is not automatically bad. It may be reasonable for small tables or queries that need a large percentage of the available records.

The goal is to determine whether the database is doing unnecessary work.

4. Review Database Indexes

Indexes help databases find records without scanning every row in a table.

For example, if an application frequently searches orders by customer ID, an index on that column may improve query performance.

In MySQL or MariaDB:

CREATE INDEX idx_orders_customer
ON orders(customer_id);
Enter fullscreen mode Exit fullscreen mode

Before creating an index, check whether a suitable one already exists.

Too many indexes can increase storage requirements and slow down insert, update, and delete operations.

For PostgreSQL, a similar index can be created with:

CREATE INDEX idx_orders_customer
ON orders(customer_id);
Enter fullscreen mode Exit fullscreen mode

Test the query again after creating an index and compare the execution plan.

An index is useful only when it matches the way the application retrieves data.

5. Avoid Retrieving Unnecessary Data

One common source of inefficient database queries is retrieving more data than an application actually needs.

For example:

SELECT *
FROM orders;
Enter fullscreen mode Exit fullscreen mode

This retrieves every column from every matching row.

If the application only needs the order ID and status, a more targeted query is:

SELECT order_id, status
FROM orders;
Enter fullscreen mode Exit fullscreen mode

Reducing unnecessary data can lower the amount of work required by the database and reduce the amount of information transferred to the application.

This becomes especially important when tables contain large text fields, JSON documents, or other data that the application does not need for every request.

6. Check Database Connections

Applications sometimes create too many database connections.

A large number of connections can consume memory and increase the workload on the database server.

For MySQL or MariaDB, check the current connection count:

SHOW STATUS LIKE 'Threads_connected';
Enter fullscreen mode Exit fullscreen mode

Review the maximum allowed connections:

SHOW VARIABLES LIKE 'max_connections';
Enter fullscreen mode Exit fullscreen mode

If the number of connections is consistently close to the limit, investigate the application connection behavior.

A connection pool can help reuse existing connections instead of creating a new one for every request.

However, increasing the maximum connection limit without checking available resources may create additional problems.

The correct connection limit depends on the database workload and the resources available to the server.

7. Monitor Database Logs

Database logs can help identify queries that take longer than expected.

MySQL and MariaDB support a slow query log that records queries exceeding a configured execution time.

For MySQL, you can inspect the current settings with:

SHOW VARIABLES LIKE 'slow_query_log';
SHOW VARIABLES LIKE 'long_query_time';
Enter fullscreen mode Exit fullscreen mode

The slow query log can help identify repeated performance problems that may not be visible during a short monitoring session.

Use the log to identify queries worth optimizing, then review their execution plans and database indexes.

Avoid enabling verbose logging without considering its storage and performance impact on a production server.

8. Review the Server's Storage Performance

Database performance depends heavily on storage.

When a query needs to read or write large amounts of data, slow storage can increase query execution time.

On Linux, the following command can help inspect disk activity:

iostat -xz 1
Enter fullscreen mode Exit fullscreen mode

The command is available through the sysstat package on many distributions.

Look for sustained storage utilization and high I/O wait.

If the database is experiencing storage bottlenecks, review the database's disk configuration, workload, and available storage performance.

For applications with large databases or frequent disk operations, choosing suitable server infrastructure is an important part of performance planning.

For example, SeiMaxim's dedicated server hosting provides an option to evaluate when planning infrastructure for database-intensive applications.

9. Monitor Performance After Making Changes

Database optimization should be based on measurable results.

After making a change, compare the same query before and after optimization.

Useful metrics include:

  • Query execution time
  • Number of rows examined
  • CPU usage
  • Memory consumption
  • Disk activity
  • Database connection count

Avoid making several unrelated changes at the same time.

If performance improves, you should be able to identify which change contributed to the improvement.

For workloads that need additional computing resources, SeiMaxim's server hosting solutions can also be reviewed as part of infrastructure planning.

The important point is to understand whether the bottleneck is caused by inefficient queries, limited resources, or the overall application architecture.

Final Thoughts

Slow database queries can affect the performance of an entire application, even when the Linux server appears healthy.

Start by identifying the symptoms, inspect active queries, and use execution plans to understand how the database retrieves information.

Then review indexes, connection behavior, logging, and storage performance.

The best approach is to identify the actual bottleneck before making changes.

With regular monitoring and careful query optimization, developers can improve database performance and build more reliable applications.

Top comments (0)