0

I'm trying to select all rows that contain only specific alphanumeric characters in MySQL using:

SELECT * FROM table WHERE column LIKE '%abc%' OR column LIKE '%abd%' 
OR column LIKE '%ab%'

For instance:

abc1234 is ok

abd1234 is ok

abe1234 is not ok

abg4567 is not ok

ab1234 is ok

ac1234 is not ok

The problem is, it select all the "abe","abg". How to select abc1234, abd1234 and ab1234?

0

5 Answers 5

3

With this

OR column LIKE '%ab%'

As part of the WHERE clause, it's no surprise that abe and abg are selected.

Please permit me to also mention that queries LIKE '%something%' cannot make use of any indexes and are likely to be very slow on large tables. The fact that you have three of them in one query is only going to make it worse.

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

1 Comment

Just leave out the OR column LIKE '%ab%' part of the query of if you have a more specifc requirement or a better explaination please update the question.
2

Use the below Query which will also use indexes on column column

SELECT * FROM table WHERE column LIKE 'ab%' AND column not LIKE 'abe%' 
AND column not LIKE 'abg%'

The Reason the indexes will be used in this case is the query is not using wildcard in the beginning of the string literal

3 Comments

@user3613026 Happy to Help :)
@user3613026 you should then accept his answer as correct.
i used NOT RLIKE 'abe|abg' instead of NOT LIKE. much more simple
0

Remove the last part of your query, it is telling it to select abg and abe. You have told it to select all items beginning with anything and ending with anything providing ab is in the middle.

Comments

0

Because column LIKE '%ab%' will get "abe" or "abg" If you want number after "ab", this is your query:

SELECT * FROM table WHERE column LIKE '%abc%' OR column LIKE '%abd%' 
OR column LIKE '%ab0%' OR column LIKE '%ab1%' OR column LIKE '%ab2%' OR column LIKE '%ab3%' OR column LIKE '%ab4%' OR column LIKE '%ab5%' OR column LIKE '%ab6%' OR column LIKE '%ab7%' OR column LIKE '%ab8%' OR column LIKE '%ab9%'

1 Comment

can't be simplified? maybe like "%ab<numbers>%" or something like regex
0

Are you going to select column contain "abc" or "abd" or "ab" but not "abe"or "abg". For this case i don't think you can use LIKE. Try to use REGEXP. i think "ab[^g^e]?" should do the job for you.

SELECT name FROM table WHERE column REGEXP 'ab[^g^e]?';

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.