0

I want to write a query to select from a table all rows that have the word "piggy" more than 3 times in a column called Description.

I know the query to select rows with the word "piggy" in a column called Description would be:

SELECT * FROM table WHERE Description LIKE "%piggy%"

so what do i need to do in order to select only if the word "piggy" occurs more than 3 times.

2 Answers 2

3

Maris' answer is nice and easy (except I believe you wanted MORE than 3 times) but these can be customized more easily:

SELECT * FROM table WHERE DESCRIPTION LIKE CONCAT('%', REPEAT('piggy%', 4))

SELECT * FROM table WHERE Description != SUBSTRING_INDEX(Description, 'piggy', 4)

SUBSTRING_INDEX here returns the portion of the string to the left of the 4th occurrence of 'piggy' or the whole string if it doesn't match that many times (so the query throws away rows that match the whole string). Then if you change how many occurences you want, just change the number(s).

Of course, ALL of these options will be really slow if you have anything more than a few rows in your table.

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

Comments

0
SELECT * FROM table WHERE Description LIKE "%piggy%piggy%piggy%"

seems to be easiest way.

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.