WordPress MySQL Queries Cheatsheet

Written by
Published
Updated
Typical Read
8 minutes
Find your next web developer job
Drupal Web Developer at On Fire Media (San Antonio, TX)

Quickly optimize your WordPress site, delete spam comments, pingbacks, revisions, unused tags, change the default admin username and more with these MySQL queries.

WP can quickly become cluttered & outdated as time goes on. Post & page revisions, spam comments, outdated URLs & more can make your database & site troublesome to deal with — these queries will help clean things up.

WordPress is the most popular CMS around and for good reason. It allows anybody to build and maintain websites with ease. As time goes on, you may need to transfer a WordPress site to another URL, clean up your database to boost performance, or update some things that aren’t so easily done in the admin dashboard. That’s where this list of WordPress MySQL queries comes in handy.

Important: Before you proceed, backup your database before running any manual MySQL queries.

WordPress MySQL Queries Cheatsheet

If you don’t have terminal access, one of the easiest ways to run MySQL queries is through phpMyAdmin. Some hosts don’t provide this, but don’t fret — there’s a plugin that can help you out. The WordPress SQL Executioner gives you to ability execute MySQL queries through the admin dashboard.

# 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:

[code]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’;[/code]

# 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:

[code]UPDATE wp_posts SET guid = REPLACE (guid, ‘http://www.oldsiteurl.com’, ‘http://www.newsiteurl.com’);[/code]

# 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:

[code]UPDATE wp_posts SET post_content = REPLACE (post_content, ‘http://www.oldsiteurl.com’, ‘http://www.newsiteurl.com’);[/code]

# 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:

[code]UPDATE wp_posts SET post_content = REPLACE (post_content, ‘src="https://www.oldsiteurl.com"’, ‘src="https://yourcdn.newsiteurl.com"’);[/code]

# 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:

[code]UPDATE wp_postmeta SET meta_value = REPLACE (meta_value, ‘http://www.oldsiteurl.com’, ‘http://www.newsiteurl.com’);[/code]

# 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:

[code]UPDATE wp_users SET user_login = ‘Your New Username’ WHERE user_login = ‘Admin’;[/code]

# 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:

[code]UPDATE wp_users SET user_pass = MD5( ‘new_password’ ) WHERE user_login = ‘your-username’;[/code]

# 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:

[code]UPDATE wp_posts SET post_author = ‘new-author-id’ WHERE post_author = ‘old-author-id’;[/code]

# 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:

[code]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'[/code]

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.

[code]DELETE FROM wp_postmeta WHERE meta_key = ‘your-meta-key’;[/code]

# 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.

[code]SELECT DISTINCT comment_author_email FROM wp_comments;[/code]

# 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.

[code]DELETE FROM wp_comments WHERE comment_type = ‘pingback’;[/code]

# 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.

[code]DELETE FROM wp_comments WHERE comment_approved = ‘spam’;[/code]

  • 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.

[code]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;[/code]

# 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.

[code]SELECT `comment_approved`, COUNT(*) as amount
FROM `wp_comments`
GROUP BY `comment_approved`
ORDER BY amount DESC
LIMIT 0, 30[/code]

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:

[code]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[/code]

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

[code]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[/code]

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.

Did you find WordPress MySQL Queries Cheatsheet useful? Get articles in your inbox.

…and don’t worry, I hate spam as much as you. Expect to hear from me at most once a week.

Share on facebook
Share on twitter
Share on linkedin
Share on reddit
Share on facebook

Stay updated.

Get a weekly email with the latest trends in web development & SEO.

Write a guest post.

Have an interesting article or idea? Become a guest blogger & pitch me your concept today.

2 comments on “WordPress MySQL Queries Cheatsheet”.

Mark Foo

# Feb 12, 2020

Ben you rock! This is amazing and well laid out. Question, howabout replacing a URL in a post to another URL? For some reason the simple wp_post post_content one isn’t working for me.

I also need to change the Author URL as well.

Kerim Gürsoy

# Mar 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?

Join the conversation.

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

All comments posted on 'WordPress MySQL Queries Cheatsheet' are held for moderation and only published when on topic and not rude. Get a gold star if you actually read & follow these rules.

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.