Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I use WHERE with table field on right side of LIKE?

I have a SQL table that contains prefixes of strings that I would like to match against longer strings. Suppose the column containing the prefix is called prefix.

I now want to do a simple search for all rows that prefix a longer string. My first thought is to use a query that is something like this:

SELECT prefix FROM Prefixes WHERE 'long string' LIKE prefix%

The point in question is how I get the WHERE clause right. How can I tell SQL to use the value in column prefix as a prefix for my argument 'long string'?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And can I also tell SQL to not only use the column ‘prefix’ as a prefix for 'long string', but instead check whether 'long string' contains prefix anywhere within itself?

Something like this:

SELECT prefix FROM Prefixes WHERE 'long string' LIKE %prefix%

If vendor-specific things play a role here, I am using JDBC to run the queries and my database is either H2 or PostgreSQL.

>Solution :

Use concatenation to generate the string that contains the value of the column prefix with the wildcard(s):

SELECT prefix FROM Prefixes WHERE 'long string' LIKE prefix || '%'

If you want to check whether ‘long string’ contains prefix anywhere within itself:

SELECT prefix FROM Prefixes WHERE 'long string' LIKE '%' || prefix || '%'

You could also use the function CONCAT():

SELECT prefix FROM Prefixes WHERE 'long string' LIKE CONCAT(prefix, '%')

or:

SELECT prefix FROM Prefixes WHERE 'long string' LIKE CONCAT('%', prefix, '%')

See a simplified demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading