Search code examples
sqlqsqlquerysql-query-store

How to use LIKE in SQL Query in where clause, but the value of LIKE will come from in other query?


How to use LIKE in SQL Query in where clause, but the value of LIKE will come from in other query? For example:

SELECT Code FROM TABLE1 where Code LIKE '(select top 1 Grade FROM TABLE2 WHERE Age>30)%'

Please anyone can help me


Solution

  • You must concatenate the result of the subquery with the char '%':

    SELECT Code FROM TABLE1 where Code LIKE (select top 1 Grade FROM TABLE2 WHERE Age>30) || '%'
    

    You may change the operator || with + if this is the concatenation operator of your database.
    Or with the function concat():

    SELECT Code FROM TABLE1 where Code LIKE concat((select top 1 Grade FROM TABLE2 WHERE Age>30), '%')
    

    Note that using top 1 without order by does not guarantee that the result will be what you would expect.