mhlester
mhlester

Reputation: 23251

Select rows which a string starts with

I have a string /path/to/project/subdirectory/ and need to find a row where path is /path/to/project/.

How can I find rows where my string starts with path?

It would be the opposite of:

SELECT * FROM projects WHERE path LIKE "/path/to/%"

Because I have too many characters, not too few.


Both of these return zero rows:

SELECT * FROM projects WHERE path LIKE "/path/to/project/subdirectory/%"
SELECT * FROM projects WHERE "/path/to/project/subdirectory/" LIKE (path+"%")

Upvotes: 2

Views: 3349

Answers (1)

Barmar
Barmar

Reputation: 782683

You were close with your second attempt, but MySQL uses CONCAT() to concatenate strings, not +.

SELECT *
FROM projects
WHERE "/path/to/project/subdirectory/" LIKE CONCAT(path, '%')

You can also use

WHERE LOCATE(path, "/path/to/project/subdirectory/") = 1

Upvotes: 3

Related Questions