Useful WordPress SQL Queries

WordPress is one on the most popular CMS around and for good reason. The ease at which it allows anybody to build and maintain websites can’t compare to other systems like Drupal or Joomla. Sometimes though, you’ll need to transfer a WordPress site to another URL or clean up your database to boost server performance. This can sometimes be tricky if you attempt to handle everything through the admin panel. To make life a little bit easier, I’ve put together a list of the most useful WordPress SQL queries.

Before you proceed…

It’s always good practice to backup your database before making any major changes. Should something go wrong, you’ll always be able to restore the old site. If you need help, try one of these useful WordPress plugins:

  • WP-DB-Backup
    WP-DB-Backup allows you easily to backup your core WordPress database tables. You may also backup other tables in the same database.

  • WP-DBManager
    Allows you to optimize database, repair database, backup database, restore database, delete backup database , drop/empty tables and run selected queries. Supports automatic scheduling of backing up, optimizing and repairing of database.

Alternatively, you can backup your database through phpMyAdmin manually.

The Most Useful WordPress SQL Queries

Running simple SQL queries like the ones listed below is easy. One of the easiest ways to accomplish it is through phpMyAdmin. If you don’t have phpMyAdmin installed or unsure how to access it, like with most things WordPress, there’s a plugin that can help you out. The WordPress SQL Executioner is a plugin that allows you to execute SQL queries through the admin panel.


# Update the site URL & home URL

When you install WordPress for the first time, it stores the absolute path of the site URL and home URL in the database. This can make it a little tricky when you transfer your WordPress site from one URL to another. When you try, your site won’t load because the absolute URL is still set to the old URL. Fixing this is easy by updating the site URL and home URL in the database:

UPDATE wp_options SET option_value = replace(option_value, 'http://www.oldsiteurl.com', 'http://www.newsiteurl.com') WHERE option_name = 'home' OR option_name = 'siteurl';

# Update the GUID

One of the most crucial updates to make after a site transfer is the GUIDs. This is important because the GUID is used to translate post and page slugs to the correct absolute path. Updating this is just as easy as updating the site URL and home URL:

UPDATE wp_posts SET guid = REPLACE (guid, 'http://www.oldsiteurl.com', 'http://www.newsiteurl.com');

# Update the URLs in your content

Like the site URL and home URL, WordPress uses absolute paths when embedding media and links into your posts or page content. When you transfer a WordPress site to a new URL, you’ll need to make sure to update those URLs so they don’t get broke. This can be a tedious and time-consuming process if you have a lot of content to update. Running the SQL query below will make it fast and easy:

UPDATE wp_posts SET post_content = REPLACE (post_content, 'http://www.oldsiteurl.com', 'http://www.newsiteurl.com');

# Update image paths only

If you use a CDN or cloud service like Amazon CloudFront to serve images, you’ll need to update the image paths in your existing posts and pages so they get loaded by the service instead of your server. Use the query below to only update image paths:

UPDATE wp_posts SET post_content = REPLACE (post_content, 'src="https://www.oldsiteurl.com"', 'src="https://yourcdn.newsiteurl.com"');

# Update your posts meta information

WordPress stores special post information in a separate table. If you’ve transferred your WordPress site, you’ll need to update that information should any of it point to your old URL. Use the query below to easily do this:

UPDATE wp_postmeta SET meta_value = REPLACE (meta_value, 'http://www.oldsiteurl.com', 'http://www.newsiteurl.com');

# Change the default “admin” username

When you first install WordPress, it’s default account username is set to “admin”. Since this is widespread knowledge, it causes security concerns and should be changed. Changing it to a more unique name can boost your site’s security. Use the query below to change the default “admin” username:

UPDATE wp_users SET user_login = 'Your New Username' WHERE user_login = 'Admin';

# Change your WordPress password

Need to change your WordPress password and can’t find where to do it in the admin panel? Use the query below to quickly make the change:

UPDATE wp_users SET user_pass = MD5( 'new_password' ) WHERE user_login = 'your-username';

# Assign posts from one author to another

Say you want to transfer articles from one author to another. This is another time consuming and tedious process if you’ve got a lot of posts on your site. You can easily and quickly make this change, but first need to obtain the author’s ID by going to your user page in the WordPress admin panel. Click the user’s name to view their profile and then look at the address bar taking note of the “user_id”. Then, use the query below to easily transfer ownership from articles assigned to one author to another:

UPDATE wp_posts SET post_author = 'new-author-id' WHERE post_author = 'old-author-id';

# Delete revisions

When you edit WordPress posts of pages, by default, it saves each revision so you can easily revert should something go wrong. This can cause use up your server resources when you have thousands of entries. Your database will grow significantly and will cause an increase in loop iterations, data retrieval and will affect page load times. To help optimize your WordPress database, delete old revisions that you don’t need anymore by using the query below:

DELETE a,b,c FROM wp_posts a
LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c ON (a.ID = c.post_id)
WHERE a.post_type = 'revision'
Note: Bear in mind that all revisions from each post will be deleted, including all of its meta data.

# Delete post meta

Installing or removing plugins is a very common task for WordPress. Some of the plugins make use of the post meta to store data pertaining to the plugin. After you have removed the plugin, those data are still left inside the post_meta table, which will no longer be needed. Run the following query to clean up the unused post meta value. This will help to speed up and reduce the size of your database.

DELETE FROM wp_postmeta WHERE meta_key = 'your-meta-key';

# Export all comment emails with no duplicates

Over a period of time, your blog will have received many comments. These comments will include the email addresses left by the commenter. You can retrieve all these emails for your mailing list without any duplicate.

SELECT DISTINCT comment_author_email FROM wp_comments;

# Delete all pingbacks

Popular articles receive plenty of pingback. When this happens, the size of your database increases. In order to reduce size of the database, you can try removing all the pingbacks.

DELETE FROM wp_comments WHERE comment_type = 'pingback';

# Delete all spam comments

If you have plenty of spam comments, going through each page to delete spam can be tedious and frustrating. With the following SQL query, even if you have to face deleting 500 over spam comments, it will be a breeze.

DELETE FROM wp_comments WHERE comment_approved = 'spam';
  • 0 = Comment Awaiting Moderation
  • 1 = Approved Comment
  • spam = Comment marked as Spam

# Delete unused tags

In a WordPress database, if you run a query to delete old posts manually from MySQL, the old tags will remain and appear in your tag cloud/listing. This query allows you to delete the unused tags.

DELETE FROM wp_terms wt
INNER JOIN wp_term_taxonomy wtt ON wt.term_id = wtt.term_id WHERE wtt.taxonomy = 'post_tag' AND wtt.count = 0;

# Find how many entries are spam

We look at the column comment_approved. Here WordPress stores the type of the comment. We collect the amount of the different values with COUNT(*) and put it into the variable amount.

SELECT `comment_approved`, COUNT(*) as amount 
FROM `wp_comments` 
GROUP BY `comment_approved` 
ORDER BY amount DESC
LIMIT 0, 30
comment_approved amount 
spam              12118
1                   104
post-trashed          1

The 1 represents approved, real comments. We are already seeing: only 0.85% of all comments are spam. Unfortunately, this is a normal value. The mean part is: MySQL must always go through the entire table to find the real comments for the output in the published articles. With an index, an optimized query structure, this goes faster.

# Find which posts suffer from the most spam

The more popular a post is, the more spam it attracts. Some posts get almost never spam, others are downright overwhelmed. We get the 20 most spammed posts with this query:

SELECT `comment_post_ID`, COUNT(*) as amount 
FROM `wp_comments` 
WHERE `comment_approved` = 'spam'
GROUP BY `comment_post_ID`
ORDER BY amount DESC 
LIMIT 0, 20
comment_post_ID  amount 
1776               2299
2184               1840
143                1759
1366               1145
2377                960
2456                512
2536                497
683                 486
1373                236
1402                200
1522                174
2458                161
1168                127
10473               121
647                 116
2357                114
2831                111
2420                110
741                  94

Now we could protect for these articles the comments with a registration or just close the comment form. Both solutions are not ideal.

# Find where the most spam comes from

SELECT   `comment_author_IP`, COUNT(*) AS amount 
FROM     `wp_comments`
WHERE    `comment_approved` = 'spam'
GROUP BY `comment_author_IP` 
HAVING    amount > 10
ORDER BY  amount DESC
LIMIT     0, 30
comment_author_IP   amount 
173.242.120.58      450
198.200.37.51       386
198.200.37.59       287
192.74.240.170      268
109.163.236.87      218
192.74.230.131      181
212.59.28.172       157
198.200.37.83       153
91.236.74.117       148
212.59.28.221       147
142.0.138.77        140
142.0.136.9         117
192.74.228.242      109
142.4.117.43         91
137.175.1.235        88
142.4.97.173         82
142.4.117.162        80
198.200.33.140       80
192.74.228.161       73
193.105.210.217      63
142.4.96.66          63
91.231.40.28         55
193.105.210.216      54
142.4.96.74          54
192.74.228.164       51
192.162.19.193       48
80.93.213.249        48
192.74.231.156       46
142.0.136.12         46
91.231.40.27         46

There is so much spam from some IP addresses that we can lock them out safely. This is works in a .htaccess, for example, like this:

# IP block list
order allow,deny
deny from 173.242.120.58
allow from all

Do you have any useful WordPress SQL queries you use?

I’d love to hear from you! Comment below with some useful WordPress SQL queries you use to update, optimize and manage your site.

Comments

  1. Kerim Gürsoy March 16, 2015

    Hi Ben,

    thank you for your nice SQL tutorial 🙂

    Currently I’m trying to solve a WordPress SQL issue.

    I have imported over 4.000 posts from Typo3. And now I want to delete all image tags in the posts. The images are too old and not useful.

    So, the problem is that every image tag has a different source, different title, alt, style attributes etc.

    Do you know a good SQL query for this issue?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

All comments are held for moderation and only published when on topic and not rude. You'll even get little stars if you do an extra good job.

You may write comments in Markdown. This is the best way to post any code, inline like `<div>this</div>` or multiline blocks within triple backtick fences (```) with double new lines before and after.

Want to tell me something privately, like pointing out a typo or stuff like that? Contact Me.

icon-search icon-link