29

I'm fairly new to SQL and I was trying to get a full list of products that match a user input of a productID. Something like:

SELECT ProductID, ProductName FROM Products WHERE ProductID LIKE '%15%'

I would like it to list out all the matching products such as: 15, 150, 2154, etc

Unfortunately I'm running into problems because the productID field is an INT and not a string. Is there some relatively simple way around this?

1
  • 1
    If the "correct" answer is to convert/cast the value to text then the table should be altered to convert the column to text permanently. This is intuitive because you shouldn't need to perform mathematics on product identifiers.
    – onedaywhen
    Dec 8, 2011 at 8:32

2 Answers 2

41

You can CAST the field to a string:

 ... WHERE CAST(ProductID as CHAR) LIKE '%15%'

this is very bad for performance, as mySQL can't make use of any indexes it's created for the INT column. But then, LIKE is always slow, even when done on a varchar field: There's no way to have an index that speeds up a LIKE query.

It might be worth having a second varchar column that mirrors the int column's values and doing the LIKE on that one - you'd have to benchmark to find out whether it'll do any good.

9
  • Is using CAST faster than using CONVERT?
    – Maxx
    Dec 7, 2011 at 21:07
  • 2
    @Maxx they're synonyms of the same function, so there is no difference.
    – Pekka
    Dec 7, 2011 at 21:07
  • {"The expression contains undefined function call CAST()."} is what I'm seeing :(
    – Maxx
    Dec 7, 2011 at 21:24
  • @Maxx SELECT ProductID, ProductName FROM Products WHERE CAST(ProductID as CHAR) LIKE '%15%' should work.
    – Pekka
    Dec 7, 2011 at 21:26
  • 2
    SQL Server Manager? So is this on SQL Server or MySQL? Also, post your C# code.
    – ean5533
    Dec 7, 2011 at 21:29
8

You can convert int to string using CONVERT(ProductID, CHAR(16)) AS ProductID and then use LIKE. So in your case it would be

SELECT ProductID, ProductName FROM Products
WHERE CONVERT(ProductID, CHAR(16)) LIKE '%15%'

You should remember that the query will make a full table scan without any support from indices. As a result it will be really expensive and time consuming.

2
  • {"The expression contains undefined function call CHAR()."} is what I'm seeing.
    – Maxx
    Dec 7, 2011 at 21:19
  • Which MySQL version are you using?
    – Jan
    Dec 7, 2011 at 21:26

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.