Learn How to Master WordPress Database Optimization on - (r)

Apr 13, 2024
WordPress database optimization at

-sidebar-toc>

Although all the elements of a WordPress site are essential but your database may be the key. This is where practically all of your site's information is kept, and can be accessed. As such, your WordPress strategy for optimizing database performance has to be perfect.

If your database is afflicted by bloat and performance issues will make your website slower and impact your search results. Furthermore, you may influence the overall user experience (UX) too. This can impact your traffic figures as well as trickle back to your placings in search results (among many other problems).

Understanding the WordPress Database Structure

In short, the WordPress database serves as the foundation of your website. It is home to almost everything such as the content, user information configurations, user data, and more. Regarding WordPress Tables in the database have the responsibility of storing particular kinds of information.

The phpMyAdmin interface on a  hosting service, showing a list of WordPress database tables with options for actions like browse, structure, search, insert, and drop. The tables shown include wp_commentmeta, wp_comments, wp_links, wp_options, wp_postmeta, wp_posts, wp_termmeta, wp_terms, wp_term_relationships, wp_term_taxonomy, wp_usermeta, and wp_users.
Connecting to a WordPress database by using phpMyAdmin.

For instance For instance, post_wp_posts table includes your articles and pages, while users contains information about the users of your website. We'll look at some of these tables in greater depth in the near future.

Upon installation, WordPress creates a set of default tables to cover the most common scenarios you'd need. But, themes, plugins, and install may also create tables that can be used to hold specific and related details.

The modular design is great in many ways, since it allows for extensive functionality. On the flip side there are a lot of superfluous tables (along with management issues) could lead to excessive bloat.

The database structure that WordPress uses is important to understand. WordPress is vital for two reasons:

  • Performance. Good database organization allows you to retrieve information faster as well as having an immediate effect on loading times as well as performance.
  • Maintenance. Knowing which tables relate to different components of your site can help in the course of maintenance. For instance, if a particular plugin is causing issues, you might troubleshoot its associated tables.

A regular cleaning and optimizing of the database's tables will stop them from getting too big and cumbersome. We've mentioned that the performance impact could affect the user in a negative way.

WordPress-Specific Tables

While we won't cover every table here, we'll jump into certain tables more than others:

  • wp_postmeta. The metadata for your post is stored here. As your site grows and expands, it could be one of the biggest databases in your database.

Be aware that every themes or plugins you include to your site may modify the layout of your site as well. It's uncommon to have a theme or plugin remove one of these tables, nevertheless.

However, it is important to periodically review and analyze any potential adjustments. It's essential to keep an efficient database that enhances and not hinders your site's performance.

The reason WordPress Database Optimization is Necessary for Most Sites

In this regard, there are two general reasons why regular WordPress data optimization is a workflow staple:

  • Better the user's experiences. Users also expect an effortless and speedy browsing experience. Optimized databases result in quicker page loading and faster data processing. In simple terms, each on-site user interaction is dependent upon database queries. More efficient means improved UX.

Furthermore, as your website grows as does your database. Even if you have a small, manageable system at first, this will grow more complex quickly. Through regular maintenance, you will make sure that your database is able to handle the increasing demands of a website without degrading performance.

Simply put, WordPress database optimization will boost response times. If your website is slow to load, even a few seconds can lead to increased bounce rates and lost traffic, which doesn't spell the best for your search rankings.

What is the best way to carry out regular Maintenance and Cleaning

If you clean and regularly manage your WordPress database, then you've got the ideal method to ensure that your website runs as smoothly as possible. The problem is that databases get filled with data that is not needed over time, so the need for a consistent and frequent workflow is important.

Additionally, it's important to make use of all the tools and services that are available to the best way possible. It's good to know that WordPress offers a number options to keep your database.

A plugin has a variety of methods to optimize your database. WP-Optimize is one of the most popular solutions for the job. There are others, but this one is rated highly and user reviews on WordPress.org, is cost-free, and receives regular updates.

The WordPress.org header image for the WP-Optimize plugin with the slogan 'Make your site fast and efficient.' The graphic shows a red motorcycle racing against a car and a jet.
The WP-Optimize header from WordPress.org.

In the next sections, we'll look at this in greater details, while we'll also cover how to do it manually and use WP-Optimize. We'll cover 's own tools in the future. First, though, let's cover certain pre-optimization processes.

Things to Do Prior To You Tackle Optimization

Also, you should remove any themes or plugins you don't use on your site. This could solve a few issues, not just with your database. It can help harden your website's security as well.

The WordPress dashboard showing a list of installed plugins. Each plugin has a description, with options to activate, deactivate, or delete, and settings for automatic updates.
The Plugins screen within WordPress

But, be aware that based on the plugin or theme the plugin or theme, it can create unwanted tables behind. Of course, this is precisely why we want to optimize the database, so understanding the reasons why plugins or themes are able to leave temporary data behind can help down the line.

The ultimate task will be one you'll discover when you login to your preferred database management program of choice. Database errors can obviously be indicators of problems with performance So, they should be resolved prior to implementing further optimization.

In short, the process is to choose all of your tables. Then, use the Check button on the table button to create reports.

The phpMyAdmin tool showing the 'Check table' option. Visible on the left are various table names like wp_termmeta and wp_users, each with action icons for tasks such as browsing and searching. To the right, a context menu shows options for table operations like exporting and optimizing.
Choosing the Check table option in the phpMyAdmin.

If you see an error that is not there, then this is a good sign. Any errors require resolving before you carry on. This is where an issue with support is an ideal option.

1. Make Your Database Tables More Optimized

The first thing to do is improve the table structure inside your database. With a manual approach, head to your Databases hyperlink within your management tool, then select your preferred database

The  phpMyAdmin interface showing the Databases tab. Two databases are listed, and both have check privileges actions available.
The choice of a database is made within phpMyAdmin.

Many times, you will already be on the database of your WordPress website. In any case, you'll be able to see a list of tables within your database. Simply bulk select them all and then select one of them. Optimize table option from the drop-down menu prior to you click to go.:

A context menu in phpMyAdmin for a selected list of WordPress database tables, with the 'Optimize table' option highlighted. Other options include copy table, show create, export, empty, drop, and table maintenance actions.
Selecting to optimize all the tables in databases making use of phpMyAdmin.

Once you've had a while, you'll see a report that outlines the current status of each table within your database.

The phpMyAdmin interface displaying a message indicating successful SQL query execution for optimizing WordPress database tables. Below the message, individual tables are listed with notes on their optimization support status.
The optimization report within phpMyAdmin.

In WP-Optimize's settings, click WP-Optimize > Database > Optimizations. Then, you can click on the Run Optimization button that is next to the Optimize Database Tables option:

A section of the WP-Optimize plugin interface in the WordPress dashboard, showing the 'Optimize database tables' option selected with a 'Run optimization' button highlighted. The interface indicates that the optimization will affect 159 tables.
The Run optimizations button within WP-Optimize's dashboard.

The software will process every table, and then give you the success signal. At this point, you can move on to post modifications.

2. Cleaning Up Post Revisions and Clean-Up

DELETE FROM wp_posts WHERE post_type = 'revision';

The deletion will remove all kinds of revision posts from the table. But, there's associated data in other tables too. To capture and remove all of this it is possible to use the below SQL commands:

DELETE FROM wp_posts WHERE post_type = 'revision';
 DELETE FROM wp_term_relationships WHERE object_id NOT IN (SELECT ID FROM wp_posts);
 DELETE FROM wp_postmeta WHERE post_id NOT IN (SELECT ID FROM wp_posts);

Pro tip: When wrangling database tables with many rows (particularly with more-complex joins like those mentioned above) the long-running query may time-out. In MySQL, MariaDB and PostgreSQL it is possible to use a LIMIT clause to divide your task into smaller actions:

DELETE FROM WP_postmeta WHERE post_id NOT IN (SELECT ID from wp_posts)
Limit 10000

That SQL can be repeated, removing as many as 10,000 entries at a time in this case until your table is clear.

Also it is essential to select the right table prefix for your database when you copy-paste the following SQL examples.

By using a plugin, this task takes seconds. Much like general WordPress optimizing your database, WP-Optimize provides you with a one-click button from within WordPress:

The WP-Optimize plugin dashboard with a focus on database optimization. Options include cleaning all post revisions and auto-draft posts, with a blue 'Run optimization' button next to each task.
The options to clear drafts, revisions and auto-drafts are available in WP-Optimize.
define( "WP_POST_REVISIONS' );

Here, here, X is the revision count you'd like to keep. You could also specify False in this field, however we do not recommend it. It is always advisable to have at least one revision that you can fall back to in case you require it.

3. Remove Spam Commentaries and Trashed Items

It is also possible to use SQL queries to get rid of spam comments. When you moderate comments, unwanted ones stay in your database for thirty days. This means comments marked as spam within that time frame will sit in your database.

They can be cleared in a single line of SQL within the database management software:

DELETE FROM wp_comments, wp_commentmeta
 USING wp_comments
 LEFT JOIN wp_commentmeta ON wp_comments.comment_ID = wp_commentmeta.comment_id
 WHERE wp_comments.comment_approved = 'spam';

Similar to things you can send to garbage bin within WordPress. There could be lots of content  in limbo' which you can delete with an additional SQL query:

DELETE p, pm, tr
 FROM wp_posts p
 LEFT JOIN wp_postmeta pm ON p.ID = pm.post_id
 LEFT JOIN wp_term_relationships tr ON p.ID = tr.object_id
 WHERE p.post_status = 'trash';

Like post revisions you can define limits for the amount of time required to eliminate garbage items from wp-config.php:

define( 'EMPTY_TRASH_DAYS', X )

Within WP-Optimize, there are three choices to assist you eliminate spam commenters and WordPress garbage:

A section of the WP-Optimize plugin in the WordPress dashboard showing various cleanup options such as removing spam and trashed comments, unapproved comments, and expired transient options, with checkboxes to select each optimization task.
You can delete junk comments, spam and comments that are not approved in WP-Optimize.

It is also possible to remove unapproved comments. This could be helpful for certain scenarios, but we wouldn't recommend this. Better to moderate your comments before removing them if you need to.

4. Remove Unused Tags

Taxonomies are important for WordPress but they may turn into a massive collection in the course of time. This can be a great application for maximizing your database. Along like other methods using SQL queries, it's possible to make use of the following SQL query:

DELETE t, tt
 FROM wp_terms AS t
 INNER JOIN wp_term_taxonomy AS tt ON t.term_id = tt.term_id
 LEFT JOIN wp_term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id
 WHERE tt.taxonomy = 'post_tag' AND tt.count = 0;

The most effective method to eliminate the tags that are not being used in WP-Optimize is Clean post meta data. This assesses whether you have any missing metadata, and then eliminate it

The WP-Optimize plugin interface displaying options for cleaning up the WordPress database, including removing pingbacks and trackbacks, cleaning post meta data, and cleaning user meta data with respective counts for each.
The options within WP-Optimize to clear out orphaned post metadata.

While this option may remove categories and other data, also, it's a secure option to choose, particularly in the event that no other article or web page makes use of them.

5. Eliminate Pingbacks and Trackbacks

The WordPress dashboard’s 'Discussion Settings' screen showing checkboxes for default post settings such as notifying linked blogs, allowing link notifications from other blogs, and allowing people to submit comments on new posts.
It is located on the Discussion Settings screen in WordPress shows the pingback and trackbacks options.

Within the Standard Post Settings area, be sure you untick the "Attempt to notify blogs of any changes" ..." and "Allow link notifications ..." options. Save the changes. Then, go back to your database management tool and run the following query:

DELETE c
FROM wp_comments cLEFT JOIN WP_COMMENTMETA cm ON c.comment_ID = cm.comment_id
WHERE c.comment_type is entered ('trackback'or "pingback');

They are both at the same time as comments. The kind is distinct and what the query focuses on. The WP-Optimize plugin offers two different options for each of these:

The WordPress dashboard displaying the WP-Optimize plugin settings with options to remove expired transient options, pingbacks, trackbacks, and to clean post meta data, showing counts of items found for each category.
The options offered by WP-Optimize for eliminating trackbacks and Pingbacks.

After you've completed this task, you shouldn't find trackbacks or pingbacks within your database for a while!

Utilizing's Automated WordPress Database Optimization

APM cleanses the database by getting rid of unneeded data like the metadata of transients, abandoned orphans, as well as spam comments. This way, you'll be able to make sure that your database is optimal without any the input of.

The  APM dashboard featuring the 'Overall transaction time' chart, which breaks down the response time into PHP, MySQL, and external services over a specified period. The section below lists 'Slowest transactions' with metrics like total duration and average duration.
It is the APM tool.
The  APM interface displaying a chart titled 'Slowest database queries', which lists various WordPress options-related SQL operations such as SELECT, UPDATE, INSERT, SHOW, and DELETE, along with their total duration percentages, total duration in milliseconds, maximum duration, average duration, and rate per minute.
An analysis from APM which shows the most slow query running in the database.

Access to APM via the My Dashboard, specifically that APM screen. It is possible that you have to enable this before you can use it:

A  hosting service dashboard displaying the Application Performance Monitoring (APM) section. It includes a brief explanation of the APM feature, along with warnings about its usage. An 'Enable APM' button is prominently displayed for the user to activate the service.
The option to enable APM in My dashboard. My dashboard.

In this case, you'll need to give APM enough time to gather information. Once it's available you'll be able to look at those queries that may need more enhancement.

How To Optimize Database Queries for Greater Efficiency

Making sure you optimize the database queries that used by your site is essential in boosting the efficiency as well as speed on your WordPress website. Faster queries lead to faster retrieval of data that in turn lead to a faster load time and an improved user experience.

If you are using queries to carry out WordPress databases optimization here are some suggestions on how to improve their efficiency:

  • Optimize the query structure. You'll notice that we don't use wildcards (or asterisks) in our examples of queries. Instead of making use of the SELECT *, be particular about the columns you require. Additionally, you should use join in place of subqueries when it is possible. Subqueries can be less efficient particularly if they do not possess a well-structured arrangement or have large data sets.
  • Make use of query caching. Tools such as Redis are able to save the results of queries in memory. The results from the query are served by the cache, rather than making the database query again each time.

These are vague guidelines, however there's lots more to do there. We'll take a look next.

Advanced WordPress Techniques for Optimizing Databases and Troubleshooting

'Indexing' can help you add a quick reference guide to your database. This can help the database server locate data more quickly without scanning every row of a table.

In order to do this, determine the columns which are in frequent use in your queries and think about adding indexes to them. You can do this from within phpMyAdmin (or similar). First, click on the table that you want to index, then click the structure tab:

The 'Structure' tab in phpMyAdmin for the 'wp_posts' table of a WordPress database. It displays a list of columns with types, collation, attributes, and actions available like change and drop.
Accessing the Structure tab for a table in PHPMyAdmin.

Select those columns you would like to index and select to select the Index option on the end of the table.

A close-up of a section in phpMyAdmin showing the index option highlighted for a WordPress database table. Other options such as browse, change, drop, primary, unique, spatial, and fulltext are also visible.
Choosing to index columns within phpMyAdmin.

When you save your modifications the changes will be indexed in those columns.

It is important to understand that the "EXPLAIN statement can also help you to understand how MySQL runs the query. It can assist you in identifying the inefficiencies, and also understand how your query interacts with indexes. To run this, insert the following statement at the front of a query you already have. When you run it, SQL will break down how it will execute the query:

The phpMyAdmin SQL query output window showing a successful SQL query execution message. Below the message is an SQL command to explain a delete operation on WordPress comment tables, with details of the query execution plan.
The results of performing a query is accompanied by an EXPLAIN statement.

We can't cover everything about the EXPLAIN statement, however MySQL's documentation is comprehensive. MySQL document provides almost all the information you need to be aware of.

Monitoring Performance

Monitoring the performance of your WordPress database is a vital element of operating a website. It can help you identify possible issues prior to them becoming serious and help ensure that your website remains efficient and responsive.

The phpMyAdmin 'Status' tab showing a pie chart and a list of SQL statement operations along with their frequency. The chart indicates the distribution of operations like 'set option,' 'show variables,' and 'select' since the server startup.
The screen for phpmyAdmin status.

You can see the execution time of queries and processes (on the Statistics for queries tab), which helps to identify those queries that need improvement. If you want to monitor more advanced aspects of your query, MySQL Workbench can be a great tool:

A detailed view of MySQL Workbench showing two SQL queries in the editor and the results pane below. The left sidebar lists database schemas, and the toolbar at the top provides various functions for database management. A snippet box on the right side offers SQL syntax help.
The MySQL Workbench main user interface.

The program offers you the latest features for database design, development and administration. It also provides performance reports and diagnostics that help you fine-tune your database.

The WordPress.org header for the Query Monitor plugin. It shows queries by component with a focus on components like 'wordpress-seo' and 'woocommerce'. HTTP requests are listed with methods, URLs, and statuses, along with a panel for warnings and notices.
The Query Monitor plugin.

How To Handle Large Databases within WordPress

If a WordPress site expands in its the number of users, content, and visitors, the database naturally expands. An enormous database is something you will encounter (or worry about) often when managing a website.

Most of the advice we give in this article can be suitable for a large database - or even reduce the size of it. But, there's a lot of other tips we can give for those databases which are inherently more than typical.

  • Archive data from the past. Instead of keeping your data up-to-date, you should consider archiving old posts or information from users that you do not frequently access.
  • Use an Content Delivery Network (CDN). Serving and offloading static content such as images, videos, as well as downloads from a different server can reduce the load on your website, and also help to improve speed. What's more, your site is able to load quicker for visitors regardless of their location.
  • Personal query. If you're a WordPress developer, write efficient queries to your themes and plugins. It will allow you to find only the data you need, to keep your efficiency up.
The  hosting dashboard displaying 'Site Information' with sections for basic details, environment details, and SFTP/SSH information. Graphs for site visits and overall transaction time are visible, providing analytics on website performance.
The WordPress hosting website.

Summary

Your WordPress database is just like the engine of a car in that it is tuned but isn't as efficient as you'd like it to. A lack of WordPress optimize your database can see dropping from first place to last position in search rankings. Your users will also notice that your website is becoming a no-go and a well-maintained database that runs fast is vital to your the success of your site.

We'd like to hear if our WordPress database optimization tips are working for you. Let us know which had the most impact by leaving a comment below!

Jeremy Holcombe

Content & Marketing Editor , WordPress Web Developer, and Content Writer. Outside of everything WordPress I love the beach, golf, as well as movies. Also, I have height problems ;).