Combine two columns in SQL for WHERE clause

I would start with something like this:

WHERE customers.first_name LIKE 'John%' AND customers.last_name LIKE 'Smith%'

This would return results like: John Smith, Johnny Smithy, Johnson Smithison, because the percentage sign is only at the end of the LIKE clause. Unlike '%John%' which could return results like: aaaaJohnaaaa, aaaSmithaaa.


try this:

SELECT * 
FROM customers 
WHERE concat(first_name,' ',last_name) like '%John Smith%';

reference:
MySQL string functions


Use the following:

WHERE CONCAT(customers.first_name, ' ', customers.last_name) LIKE '%John Smith%'

Note that in order for this to work as intended, first name and last name should be trimmed, i.e. they should not contain leading or trailing whitespaces. It's better to trim strings in PHP, before inserting to the database. But you can also incorporate trimming into your query like this:

WHERE CONCAT(TRIM(customers.first_name), ' ', TRIM(customers.last_name)) LIKE '%John Smith%'

Tags:

Mysql

Sql