How to use LIKE in WHERE clause to get first 5 characters of variable?

Viewed 454

I have a variable varchar that always takes in 10 digits. How can I use the LIKE operator to find/use only the first 5 digits of the variable?

my query:

variable IN VARCHAR2

SELECT * FROM items WHERE name LIKE SUBSTRING(variable, 1, 5)
3 Answers
... WHERE name LIKE '12345%' 

will match any string that starts 12345. the '%' is a wildcard. You can also use the wildcard to match anywhere in the string: ... WHERE name LIKE '%12345%' will match a string with 12345 anywhere within it.

Edit for completeness: WHERE name LIKE '%12345' will match any string that ends with those five characters.

Try this:

SELECT * FROM items WHERE name LIKE (SUBSTRING(variable, 1, 5) + '%')

I guess you can use LEFT() like this:

SELECT * FROM items WHERE LEFT(name,5)=LEFT(variable,5);

Or if you you want to use LIKE with a wildcard, you can do this:

SELECT * FROM items WHERE name LIKE CONCAT(LEFT(variable,5),'%')

A few more example in the Demo fiddle

Edit: The above solution is for MySQL/MariaDB because earlier the tag of this question have MySQL but it's also my fault for not recognizing OP description of the datatype VARCHAR2. I might as well just post a suggestion related to the rdbms.

So, my first suggestion there using LEFT() however Oracle don't have that function, therefore:

SELECT * FROM items WHERE SUBSTR(name,1,5)=SUBSTR(variable,1,5);

or using concatenation operator

SELECT * FROM items WHERE name LIKE SUBSTR(variable,1,5)||'%'

Demo fiddle

Related