25

I have a column that contains strings as:

aaa_1
aaa_11

I need to query strings that ends with _1. I tried the following: select col from table where col like %_1; But the query gives me the strings that ends with _1 and _11. How can I correct this ?

3
  • 4
    %_1 won't give you %_11, though %_1% would. Commented Dec 13, 2012 at 21:11
  • like %_1 should return just the first, like %_1% should return both. What database are you using? Commented Dec 13, 2012 at 21:11
  • You may also do WHERE RIGHT(the_column, 2) = '_1' Commented Dec 13, 2012 at 21:12

7 Answers 7

43

Try this:

select col from table where col like '%\_1'

character _ is a jolly, like %, but it matches only a single character, so you have to escape it with \

See here: http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#operator_like

Sign up to request clarification or add additional context in comments.

2 Comments

wouldnt this also match something like a_1aaa
@dgarg there's a single wildchar % at the beginning of the string, so it would only match strings ending with _1, if you wanto to match a_1aaa you have to use like '%\_1%
29

You'll want to use something more substring related.

Try a where clause like:

SELECT col from table WHERE RIGHT(col, 2) = '_1'

2 Comments

This is the right solution if we want to ensure that _1 is only at the end of the col value
Which is exactly what the original question was? "I need to query strings that ends with _1". Right? That said, the solution by fthiella above is probably the better one, and likely more efficient.
1

Great answers!

My answer is an extension from the other posts.

In case you want to filter out data that is ending with specific character(s), use REGEXP operator.
Example : below query returns all strings where ending character(s) is/are vowel -

SELECT column_name
FROM table_name
WHERE column_name REGEXP ".*[a,e,i,o,u]{n}$"     -- n = number of vowels at the end

Comments

0

You should escape % and _ by adding backslash \ as they are wildcards in mysql:

http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html

String |     Description
\%     |     Matches one “%” character
\_     |     Matches one “_” character

Comments

0

Many of these will pick up things like %_12 or %_111121, etc. Make sure you test out various cases to be sure these SELECT statements are giving you the proper subset.

Comments

0
SELECT col FROM table WHERE col REGEXP '_1[[:>:]]'

Comments

0

You can make a quick use of this query to filter out strings ending with specific character(s).
The below query output will give all names ending with 'er'.

select column_name
from table
where column_name regexp '.*er$';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.