• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Dev Tips / MySQL Query for Multiple Strings with LIKE

MySQL Query for Multiple Strings with LIKE

Last updated on April 24, 2020 by Sal Ferrarello

When doing a query for multiple strings, you can combine them with some caveats.

The short version is

 SELECT ID, post_title, post_content FROM `wp_posts` WHERE `post_content` LIKE '%your%post%';

searches for
anything your anything post anything

So our database row matches when the post_content has a match within it to the regular expression /your.*post/.

Example MySQL LIKE

In my database table, I have a column called post_content and for one row the value of that column is.

<!-- wp:paragraph -->
<p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p>
<!-- /wp:paragraph -->

The query

SELECT ID, post_title, post_content FROM `wp_posts` WHERE `post_content` LIKE '%your first post%';

returns this row in our database because your first post appears as a substring in the content.

Separating the Strings with %

By adding % between each string, we can check that each string exists.

The query

SELECT ID, post_title, post_content FROM `wp_posts` WHERE `post_content` LIKE '%your%post%';

returns our row in the database because
your first post” appears in the content (even though they don’t appear together, i.e. your post does not appear).

Hat Tip to Tom McFarlin

Thanks for Tom McFarlin, who mentions this in the context of his article Search Post Metadata in the WordPress Admin Area.

Updated

Thanks to dz for the corrections provided in the comments. This article has been updated based on these corrections.

Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit
Warning! This is a draft, not a finalized post. See full draft disclosure.

Filed Under: Dev Tips, Draft, Programming Tagged With: MySQL

Reader Interactions

Comments

  1. dz says

    April 23, 2020 at 5:59 pm

    `post_content` LIKE ‘%your%post%’ means
    1. any text
    2. ‘your’
    3. any text
    4. ‘post’
    5. any text
    will not match ‘test posting for yours’ as would
    `post_content` LIKE ‘%your%’ AND `post_content` LIKE ‘%post%’

    Reply

Leave a Reply Cancel reply

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

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in