The SQL LIKE operator matches text against a pattern. The two main wildcards are % for zero or more characters and _ for exactly one character.
SELECT id, name, class, mark
FROM student
WHERE name LIKE '%John%';
This returns rows where John appears anywhere in the name value.
| id | name | class | mark |
|---|---|---|---|
| 1 | John Deo | Four | 75 |
| 5 | John Mike | Four | 60 |
| 6 | Alex John | Four | 55 |
SELECT column_list
FROM table_name
WHERE column_name LIKE pattern;
LIKE is normally used with text columns inside a WHERE clause.
The percent wildcard can match any number of characters, including zero characters.
SELECT id, name, class, mark
FROM student
WHERE name LIKE 'John%';
This matches values beginning with John, such as John Deo and John Mike.
SELECT id, name, class, mark
FROM student
WHERE name LIKE '%John';
This matches values ending with John, such as Alex John.
SELECT id, name, class, mark
FROM student
WHERE name LIKE '%John%';
SELECT id, name, class, mark
FROM student
WHERE name LIKE 'A%n';
One matching sample record is Alex John.
| Pattern | Meaning |
|---|---|
'John%' | Starts with John |
'%John' | Ends with John |
'%John%' | Contains John anywhere |
'A%n' | Starts with A and ends with n |
The underscore wildcard matches one character. Two underscores match exactly two characters.
If an account number contains five characters and must end with 044:
SELECT *
FROM account_master
WHERE acc_no LIKE '__044';
The first two positions can contain any single characters, but exactly two positions must appear before 044.
To find names starting with C but not having h as the second character:
SELECT id, name
FROM student
WHERE name LIKE 'C%'
AND name NOT LIKE 'Ch%';
NOT LIKE keeps rows that do not match the pattern.
SELECT id, name, class, mark
FROM student
WHERE name NOT LIKE '%John%';
This excludes names containing John.
Combine LIKE expressions with AND or OR.
SELECT id, name
FROM student
WHERE name LIKE '%a%'
AND name LIKE '%e%';
SELECT id, name
FROM student
WHERE name LIKE '%Alex%'
OR name LIKE '%Deo%';
To match a keyword in either of two text columns:
SELECT *
FROM table_name
WHERE column1 LIKE '%keyword%'
OR column2 LIKE '%keyword%';
Use AND instead of OR when the keyword must match both conditions.
LIKE is not inherently always case-insensitive or always case-sensitive. In MySQL, the result depends mainly on the collation used by the compared expression.
With a typical case-insensitive collation, these may match the same text:
SELECT id, name
FROM student
WHERE name LIKE '%john%';
For a binary comparison in MySQL, one option is:
SELECT id, name
FROM student
WHERE name LIKE BINARY '%John%';
Because % and _ are wildcards, a search for those literal characters needs an escape convention.
For example, using ! as the escape character:
SELECT id, description
FROM product
WHERE description LIKE '%!%%' ESCAPE '!';
Here !% means a literal percent sign rather than the multi-character wildcard.
LIKE can also compare a fixed string against a pattern built from a column value.
SELECT id, name
FROM student
WHERE 'Our best student is Mr John Deo of 5th Class'
LIKE CONCAT('%', name, '%');
Only rows whose name value appears inside the supplied text will match.
CONCAT to join strings in a query
When the search text comes from a form, keep the SQL prepared and place the wildcard characters in the bound value.
<?php
require 'config.php';
$keyword=trim(
$_GET['keyword'] ?? ''
);
$pattern='%'.$keyword.'%';
$stmt=$dbo->prepare(
"SELECT id,name,class,mark
FROM student
WHERE name LIKE :pattern
ORDER BY id"
);
$stmt->bindValue(
':pattern',
$pattern,
PDO::PARAM_STR
);
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
echo htmlspecialchars(
(string)$row['name'],
ENT_QUOTES,
'Windows-1252'
).'<br>';
}
Prepared statements protect the SQL value. If users must search for literal % or _, escape those wildcard characters according to the search behavior your application intends.
The same SQL pattern can be used from Python. Add the wildcard characters to the parameter value rather than building the user input directly into the SQL string.
import mysql.connector
db_connection = mysql.connector.connect(
host='localhost',
user='root',
password='your_password',
database='your_database'
)
keyword = 'John'
pattern = f'%{keyword}%'
query = """SELECT id, name, class, mark
FROM student
WHERE name LIKE %s
ORDER BY id"""
cursor = db_connection.cursor()
cursor.execute(query, (pattern,))
for row in cursor:
print(row)
cursor.close()
db_connection.close()
See the Python MySQL tutorial for the database-connection side. This SQL page remains focused on how the LIKE pattern itself works.
Pattern shape affects how easily an index can help a LIKE search.
LIKE 'John%' has a fixed beginning and can be more index-friendly.LIKE '%John' starts with a wildcard.LIKE '%John%' starts with a wildcard and often requires more scanning on large datasets.For large text-search applications, LIKE may not be the best search technology. The right choice depends on whether you need simple prefix/substring matching, regular expressions, or full-text search.
| Method | Best suited for |
|---|---|
LIKE | Simple wildcard patterns using % and _ |
REGEXP | More complex pattern rules |
LOCATE() | Finding the position of a substring |
LIKE 'John' has no wildcard and behaves like an exact pattern match. Use John%, %John, or %John% when partial matching is intended.
% can match any number of characters. _ matches exactly one character.
MySQL case behavior depends on collation and the expressions being compared.
Use prepared statements. Put wildcard characters into the parameter value rather than constructing unsafe SQL text from form input.
Queries such as LIKE '%term%' can become expensive on large datasets. Check the execution plan and consider another search approach where appropriate.
LIKE is intentionally simpler. REGEXP is useful when the required pattern cannot be expressed clearly with only % and _.
The percent wildcard matches zero or more characters.
The underscore wildcard matches exactly one character.
Use a pattern such as LIKE '%John%' to match John at the beginning, middle or end of the value.
Case sensitivity depends mainly on the collation used for the comparison. Many common MySQL collations are case-insensitive, but this should not be assumed for every column or expression.
Use NOT LIKE, for example WHERE name NOT LIKE '%John%'.
Prepare the SQL statement and bind the pattern as a value. Add the percent or underscore wildcards to the parameter value according to the search behavior you need.
A leading wildcard can make index use less effective, so the database may need to scan more data. Actual performance depends on the table, indexes, collation and query plan.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| navid | 11-05-2009 |
| I wonder if I can use '%' as below for LIKE command: declare X nvarchar declare Y nvarcahr select * from dbo.~ where(X '%' like Y)-- <-this line is mentioned | |
| manoj | 06-06-2009 |
| hey all I am using like command for accesing name as alphabetics I have written for that as select * from tbl)country where country like " Textbox1.text " but it is not working properly please guide me | |
| Alex | 08-06-2009 |
| ### to manoj SELECT * FROM TABLE_NAME WHERE country like '%HERE_GOES_MASK%' In that query, you should replace the TABLE_NAME with the name of the table you query data from. Also, HERE_GOES_MASK should be changed to the string you want to find | |
| Noel | 04-07-2009 |
| @manoj - This is how your command should be: "Select * from tblcountry where country like '%" Textbox1.Text "%'" OR you could also remove the "%" before the Textbox1.Text or remove it after, it will depend on your usage. Hope this helps. | |
| kichu | 16-07-2009 |
| How will i get names of all those people who have the string 'in' in their names? | |
| Penny | 27-08-2009 |
| I need to find a specific literal in an Oracle table column which is described as a "long" datatype. How do I do this, since "like" command can't be used on "long" type columns (can't use "long" column in a where clause of a select statement)? I get the error message:"inconsistent datatypes: expected NUMBER got LONG". Please help! | |
| Indranil | 12-11-2009 |
| I want to selet more than one row at a time ...I think query should be... SELECT * FROM TABLENAME WHERE FIELDNAME LIKE 'A%' But it selecting only the first one ...I 'm working in MSAccess...with Core JAVA-Swing Can u please help me SIR.......... | |
| Deepak | 03-12-2009 |
| To Kichu.. select * from Table_Name where first_name like '%in%' | |
| Nar | 03-12-2009 |
| Question PHP/SQL: I have an EXEC that take all my contact list from my Database and put them into a variable. Now I want to select all contact starting with "A" as the last name. And show them into my contact list. I want to do it with all letters "A" , "B" , "C" ... Something like Iphone Contact list , all familly name are in alphatical order. So, can I select and show all name starting by a specific letter? how? thx for answerying | |
| Regalla Naresh Reddy | 21-12-2009 |
| Hi...! The information is useful. I need somehelp. I want to get the information like SELECT * FROM employee WHERE name LIKE '%ram' where '%ram' is the value of other table which is similar to the value in the current table. Means i need to retrieve the information from the current table based up on the value of other table. Can you help how to acheive this .....? | |
| smo | 21-12-2009 |
| select t1.field1,t1.field2,t2.field1.t2.field2 from t1,t2 where t1.keyfield=t2.keyfield and t2.name like '%Ram' Here t1 and t2 and two tables and linked by a keyfeild ( t1.keyfield=t2.keyfield) | |
| Perwez Akhter | 07-01-2010 |
| Dear all, Hi! Can I run two like in single command line. If Yes Tell me how | |
| Shah Viral | 13-01-2010 |
| Hello EveryOne i want to find the Partucular Person name, WHen i write Down in TextBox .. Thanks | |
| smo | 13-01-2010 |
| You can run two like commands by using AND or OR combinations. | |
| Designer | 21-01-2010 |
| how can i use like query to search for two words (statement) not only when word example : select # from table_name where column like'% hello world%' | |
| a13 | 26-01-2010 |
| "SELECT * FROM video WHERE category LIKE '%'."$_GET['category']".'%' ORDER BY video_id DESC LIMIT ...... I have no idea where is the problem but it seems that this sql can not work with this statement because the webpage is not loading after this statement can someone tell me where is the problem I know that get[category] is funny or animal | |
| smo | 26-01-2010 |
| Try by printing the SQL to see what the value of category you are getting. You can also print the error message to see what has gone wrong. | |
| Kingsonprisonic | 30-01-2010 |
| Like not working in vb 6.... please help code: Me.Data1.RecordSource = "select * from phone where name LIKE '% " Me.Text1.Text "%'" Me.Data1.Refresh all >,<,>=,<=,and,or,between etc works correctly but like not working..... what can i do? | |
| manohar | 04-02-2010 |
| I want to check 4th digit of the account no is zero using sql query | |
| Dimitree | 24-02-2010 |
| I like to search a general one suppose not the Exact one for that what query is use for Eg SELECT * FROM [reg1] WHERE ([Name] LIKE '%' @Name '%' ) This will display the name what u search in database I need the query for one are more search wht is that | |
| sf09 | 03-03-2010 |
| what if i would like to find person's name which contain 2 words only? | |
| Chandrasekaran | 09-03-2010 |
| Hi, I am having the table with the column First Name. Where ever the first name contains 'is' I just wanted to remove these word in that record. | |
| Richard | 16-04-2010 |
| HI all, I have 3 tables (A,B,C)and 2 querys in the first query I join two tables (A | |
| praveen | 29-04-2010 |
| hi, thanks for the submission of this since this has helped me a lot... i was confused with the usage of % and _. but now its clear for me... thanks again... hope i will be more benefitted in future from here | |
| Mahendran | 22-07-2010 |
| @ sf09 try combination of builtin functions like select name from tableName where len(name) - len(replace(name,, ')) = 1 this will work for you | |
| chinelo | 26-07-2010 |
| hi, pls how do i write a query that should give me a result for all last_names that start with J, A and M? | |
| Prince | 29-08-2010 |
| Hi, can you please tell me how to retrieve names that are starting from either A or B from names table? | |
| ABHISHEK | 04-09-2010 |
| i want a query which will in output give the name of those employees whose last name ends with e and the query should be written without usibg the like statement | |
| linganathan | 18-10-2010 |
| i want a query , how to find 3rd highest earner in a table | |
| Bhargav | 01-11-2010 |
| hai... i am trying to execute below stored procedure. i will take two arguments as a parameters. ALTER PROCEDURE S_ListVendor ( @searchFieldValue varchar(128), @searchInField varchar(120) ) AS SELECT * FROM S_Vendor where @searchInField like @searchFieldValue; its not executed so plz.. help me Thank you | |
| praveen | 04-11-2010 |
| I want to print one field that should not start with the digits. How can i write that logic using the NOT LIKE keyword. or is there any otehr comand can we use. pls answer this question. | |
| srikar vandanapu | 10-11-2010 |
| how to get the zero record table name in a database | |
| sujitha | 29-12-2010 |
| I am trying to match first four digits(text)of a column values in a table with another table values(text). Pls write an sql query... | |
| Keyur | 13-09-2011 |
| I want the list of studebts wgose ids are even...lik 2,4,6...pls help | |
| deepak | 28-09-2011 |
| hello all, i want the name of the employees whose name starts with j or k or l or m...............what should be the query........plz help...... | |
| Alishah | 19-04-2012 |
| Hello Every0ne: I Want To See The Third Letter In Name ..... In MySql Whos Could I ? | |
| Zain | 08-06-2012 |
| have a column named Name.I want to make a query where i just enter initials of any name and i get the full name.Plz solve my problem. | |
| shamim | 14-07-2012 |
| Very simple and helpful.I have been benefited from here massively.Thanks a lot. | |
| Ruchi | 10-08-2012 |
| hiiii what if i would like to find the data of a person having _ as 2nd letter in his name ex.s_sharma............... using wild cards | |
| smo1234 | 16-08-2012 |
| Use locate command | |
| somasundaram | 31-08-2012 |
| Hi, If I have the second table like Student.Table but the First part of name or Second Part of name in the name field, Now guide how to compare both the table, My database is a huge one near about 1million record. | |
| Kirk | 31-08-2012 |
| I am trying to find a string at the end of a field using %XYZ as my search criteria. How do I condition the LIKE operator not to consider trailing blanks? I saw some information on the strip BIF but am not familiar with it (novice using SQL). | |
| MadhaviLatha | 28-11-2012 |
| Hi, I was create table with 3 columns and insert data, by using SELECT QUERY i get all the 3rd column data, from that i want particular column data. what can i do for that. if any body knows plz update. Thanks in advance. | |
| sandy | 11-03-2013 |
| Hi, I was created one company based webapplication in that case i want to apply any one company that result wil be updated in my database and one vacancy will be reduced in my jsp page how can i do what query wil be use it please help me | |
| midhun sudhakar | 04-04-2013 |
| how will i delete records whose name starts with a or j | |
| mikez | 16-04-2013 |
| how can i get a data from a table where it should be match with its username. something like this table: table 1 (username,password,name) all i want is when i type the username in a textbox and click a command button, the password will be on the other textbox that correspond to the username. please write the php source code. thanks alot | |
| nitish | 21-08-2013 |
| please refer a book in which all simple and useful sql queries are given, as u write in ur tutorials, and thanx its very beneficial | |
| NIraj | 25-09-2013 |
| what is the code of to fetch data from mysql table according to alphabet | |
| Abinash | 22-11-2013 |
| How to display the names that end with a particular letter in sql? | |
| Veerbhadra Singh | 24-01-2014 |
| Please tell me how to find a particular one employer salary in mysql table. for example find second employer salary. | |
| bapu bardoli vada | 20-02-2014 |
| my problem is i dont understand in sql statement with jquery & ajax... what am i do?? plz help me>>???? | |
| bapu bardoli vada | 20-02-2014 |
| thanks for solved my problem...i realy thankyu for ur advice..and now i m doing every thing in sql n jquery..because u r amazing...!!!! | |
| SRK | 11-04-2014 |
| question:: to display employees whose names are containing 'A' at 2nd occurrence without using wild characters | |
| nivedita | 01-07-2014 |
| How to employee name with third letter L in the name without using like operator | |
| root | 14-09-2014 |
| search name with third letter. where name like '__L%'; | |
| Hyder Ali | 04-02-2015 |
| Hi i want to get the details the first letter starts with space how to write the query in mysql | |
| smo | 06-02-2015 |
| SELECT * FROM student WHERE name NOT LIKE ' %' note that there is a space followed by % inside the quote | |
| vamsi | 17-03-2015 |
| SELECT * FROM student WHERE name LIKE '%John%' how to get same answer in above qry with out using LIKE keyword | |
| smo | 31-05-2015 |
| Try using <a href=sql_locate.php>LOCATE query</a> | |
| SK NASIRUDDIN | 02-07-2015 |
| how to get answer "list the name from student whose name start with 'J' or end with 'N'. | |
| smo1234 | 04-07-2015 |
| SELECT name FROM student where name LIKE 'J%' OR name LIKE '%N' | |
| mano | 07-10-2015 |
| Find all courses from the Section table that start with the character, “C”, but do not have “h”, as the second character. | |
| Prashant K | 07-10-2015 |
| Kindly let me know the syntax for the below question Select Name of the person from the tables where Name should contains letter 'a' and 'e' ? | |
| Prashant K | 07-10-2015 |
| Kindly let me know the syntax for the below question. Select Name from tables where Name should contains letter "a" and "e". Please note the provided letters are just an example. | |
| smo1234 | 08-10-2015 |
| It is added to the tutorial | |
| sasikala | 10-10-2015 |
| I need the list of names from a student relation which ends with a particular character say 'a' or a pattern say 'ram' . you give an explanation above but it is not working when i try it in sql. Give me explanation regarding it. | |
| kevin | 29-02-2016 |
| I need a list of tickets, which contains 3 matching number, e.g say the ticket is 12,13,56,49,20,30 any ticket that contains any of the number should be listed in regardless of the order eg 45, 20, 36,34,56,49 can be one of the ticket listed as it contains 49,56 and 20 | |
| gaurav | 27-10-2017 |
| I have a, b, c, D, e, f alphabet . I use this query = select * from table where Colume like ='a%' ; While(....) Echo "coum(0)"; So what I do then my one php select ... Like query query work For all alphabet Mens I click a then just a alphabet data fetch not other then I click I then just I data fetch please give me answer please solve my problem fast | |
| smo1234 | 30-10-2017 |
| Your Query part is ok. You need to pass the alphabet to the query through a variable. There are several ways to do it. You can keep hyperlinks with variable passing the alphabet to the page. <a href=your_page.php?var_alpha=a>a</a>, <a href=your_page.php?var_alpha=b>b</a> ... Now read the variable and pass it to query. You can use drop down list box and on select reload the page with variable. Take care of injection attack here. | |
| Lakshmi priya | 27-01-2019 |
| Is the output of '%E%' and 'E%' is same?? | |
| smo1234 | 27-01-2019 |
| No , '%E%' means it will match presence of E any where. 'E%' means it will match E at the starting of the string. | |
| Dion James Smith | 09-02-2019 |
| Hey there ! I want a command line that finds all names whose name containing the first character 'N' and the fourth character 'o' and the rest may be of any character. Please help ! | |
| smo1234 | 12-02-2019 |
| SELECT * from table_name WHERE column_name like 'N___o%' | |
27-04-2021 | |
| create table tb(luckynumber varchar(20)); insert into tb (luckynumber)values('1,2,3'); insert into tb (luckynumber)values('2,5,8'); i want DISPLAY all row matching 2 but cant use like & REGEEXP | |
29-04-2021 | |
| SELECT * FROM tb WHERE luckynumber LIKE '%2%' This will return all rows where 2 is there in any position inside luckynumber. | |
09-10-2021 | |
| Please Help Me , I Need To Search Data From DB , i Need To Search Character by Character and Finally Make a single word... | |