Drupal - How do you build up a LIKE condition in a db_select() query?

After digging through Drupal Documentation found a solution in db_like API documentation page and SelectQuery:condition handler doc page..

For example

$result = db_select('field_data_field_name', 'f')->fields('f', array(
    'entity_id',
    'field_name_value'
))
->condition('entity_type', 'user')
->condition('bundle', 'user')
->condition('deleted', 0)
->condition('field_name_value', '%' . db_like($last_item) . '%', 'LIKE')
->distinct()
->range(0, 10)
->execute();

Condition to use for like query is

->condition('field_name_value', '%' . db_like($last_item) . '%', 'LIKE')

You can also use Drupal\Core\Database\Database when creating "LIKE" query. This is Drupal 8 alternate syntax since db_select() is deprecated.

$database = Database::getConnection();
$query = $database->select('TABLE NAME', 'u')
    ->fields('u', array('column1','column2'));
$query->condition('column1', '%'.$database->escapeLike($search_phrase) . '%', 'LIKE');

Or add multiples with OR query.

$DB_OR = $query->orConditionGroup()
  // find match anywhere in field
  ->condition('column1', '%' . $database->escapeLike($search_phrase) . '%', 'LIKE')

  // find match starting at beginning
  ->condition('column2', $database->escapeLike($search_phrase) . '%', 'LIKE');

  // find match at end of field
  ->condition('column1', '%' . $database->escapeLike($search_phrase), 'LIKE')
$query->condition($DB_OR); // Add OR object as condition
$result = $query->execute();

Tags:

Database