Home » Tutorials » SQL » LIKE

LIKE

The SQL Operator LIKE is one of the most impressive parts of SQL. LIKE gives you the ability to search through a database for a particular value. When used in combination with SQL’s wildcards, you could potentially build a mediocre search engine. Of course, it would be wise to build an index first, but that’s more complicated stuff you don’t need to worry about just yet. LIKE is particularly useful for large content data types in SQL. Using like on numbers isn’t exactly a common practice.

SQL Wildcards

We really need to use wildcards for this tutorial, so let’s discuss the two common ones really quick

  • % – any characters and any length
  • _ – any characters, but only ONE character

We’ll see how to use these below, but basically you will just put them right before and/or after the value you are searching for.

Searching a Database Using SQL

Our table:

idcontent
1I am some sample content
2sam
2This isn’t the best default text
Example
SELECT * FROM table_name
WHERE content LIKE ‘%am%’
Result
idcontent
1I am some sample content
2sam

We were searching for am, and we didn’t care what came before or after it, which is why am had the wildcard, %, before and after it. You might have noticed that we didn’t have our equal operator. That’s because LIKE is an operator and it replaces the equals sign. While the record containing ‘sam’ didn’t have anything after it, SQL still matched it. This is because the SQL wildcard takes zero to unlimited characters. What if were were looking only for the names, Pam or Sam, but weren’t smart enough to use an OR? Simple:

Example
SELECT * FROM table_name
WHERE content LIKE ‘_am’
Result
idcontent
2sam

While this isn’t used very often, it is still useful to understand. The only difference in the two examples is that we removed the % wildcards and put a new wildcard, _, right in front of am. This wildcard just returns a match only if the entire record consists of 3 letters and the last 2 are am. Remember you can always put these wildcards before, after, or both around your search value and that it must be in quotes.



Link/cite this page

If you use any of the content on this page in your own work, please use the code below to cite this page as the source of the content.

  • Stewart, Suzy. "LIKE". After Hours Programming. Accessed on April 24, 2024. https://www.afterhoursprogramming.com/tutorial/sql/like/.

  • Stewart, Suzy. "LIKE". After Hours Programming, https://www.afterhoursprogramming.com/tutorial/sql/like/. Accessed 24 April, 2024.

  • Stewart, Suzy. LIKE. After Hours Programming. Retrieved from https://www.afterhoursprogramming.com/tutorial/sql/like/.



Leave a Comment

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