Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL like search substring starts with

I have many books in my MySQL database. And I am looking for the specific book headers. For example, I know how to find every header begins with the word "dan":

SELECT * FROM books WHERE header LIKE 'dan%';

But how to find a word (substring) inside the header that begins with the certain phrase?

Thanks in advance.

like image 466
Damian Pavlica Avatar asked Aug 09 '14 09:08

Damian Pavlica


People also ask

Does SQL substring start at 0 or 1?

Note that the first character in the input_string is 1, not zero. length is a positive integer that specifies the number of characters of the substring to be returned. The SUBSTRING() function raises an error if the length is negative.

What is starts with in SQL?

%STARTSWITH (SQL) Matches a value with a substring specifying initial characters.


Video Answer


2 Answers

Here's a quick and dirty trick: A word begins with dan can either be at the beginning of a header or after a space, so:

SELECT * FROM books WHERE header LIKE 'dan%' OR header like '% dan%';
like image 129
Mureinik Avatar answered Oct 13 '22 04:10

Mureinik


A slight simplification is the following logic, which puts a space at the beginning of the header:

SELECT *
FROM books
WHERE ' ' || header LIKE ' dan%';

The only issue is that concatenating the string depends on the database and the question doesn't mention the database. So it might also be:

WHERE ' ' + header LIKE ' dan%';

or

WHERE CONCAT(' ', header) LIKE ' dan%';
like image 35
Gordon Linoff Avatar answered Oct 13 '22 03:10

Gordon Linoff