Skip to content
Advertisement

How to select titles that are like the first n characters of a string?

Here’s an example

There are titles of some animes:

|_title_|
|My hero Academia|
|My hero Academia Season 2|
|My hero Academia Season 3|
|My hero Academia Season 4|

And I’d like to select those titles, that contain the first 10 character of the first record, so “My Hero Academia” in this example

It’s important that it must be the first N characters, like 10,15,20. So SELECT title FROM tablename WHERE title LIKE "%My hero Academia%" is not the solution I’m looking for.

Also: this is just an example,there are many other titles too, and I don’t always know what the first 10 characters are. So I also can’t simply put the first 10 characters of “My hero academia” in the WHERE title LIKE clause.

I mean something like this:

SELECT title FROM table_name
WHERE title LIKE the first 10 characters of a given string

Is there a way to do that with SQL?

Advertisement

Answer

for filter a string for a partial fixed value you can use like operator like 'yourstring%' eg:

    SELECT title 
    FROM your_table  
    WHERE title LIKE 'thefirst10%'  

or use a string fuction like substr or left

    SELECT title 
    FROM your_table  
    WHERE left(title,10) = 'thefirst10'  

    SELECT title 
    FROM your_table  
    WHERE substr(title,1,10) = 'thefirst10'  
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement