> For the complete documentation index, see [llms.txt](https://docs.objectiphy.net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.objectiphy.net/query-builder/running-a-query.md).

# Running a Query

### Executing queries

Any query can be executed by calling the `executeQuery` method on a repository. The return value will depend on the type of query - a select query will return one or more entities, but insert, update, and delete queries will return the number of database records that were affected by the query.

```php
$query = QueryBuilder::create()
    ->select('firstName', 'lastName')
    ->from(Contact::class)
    ->where('lastName', '=', 'Skywalker')
    ->buildSelectQuery();
    
$contacts = $repository->executeQuery($query);

// $contacts now contains a list of partially
// hydrated Contact objects for each matching
// contact.
```

```php
$query = QueryBuilder::create()
    ->delete(Contact::class)
    ->where('isPermanent', '=', false)
    ->buildDeleteQuery();
    
$affectedCount = $repository->executeQuery($query);

// $affectedCount now contains the count of how
// many records were deleted.
```

### Queries with find methods

In addition to `executeQuery`, you can pass a select query to any of the find methods on a repository (instead of an array of criteria). This allows you to do things like call `findValuesBy` and get an indexed array back instead of entities.

```php
$query = QueryBuilder::create()
    ->select('firstName')
    ->from(Contact::class)
    ->where('lastName', '=', 'Skywalker')
    ->buildSelectQuery();
    
$contacts = $repository->findValuesBy($query);

// $contacts now contains:
// ['Luke', 'Anakin']
```

Or get an associative array:

```php
$repository->setConfigOption(ConfigOptions::BIND_TO_ENTITIES, false);
$query = QueryBuilder::create()
    ->select('firstName', 'lastName')
    ->from(Contact::class)
    ->where('lastName', '=', 'Skywalker')
    ->buildSelectQuery();
    
$contacts = $repository->findBy($query);

// $contacts now contains:
// [
//    ['firstName' => 'Luke', 'lastName' => 'Skywalker'],
//    ['firstName' => 'Anakin', 'lastName' => 'Skywalker']
// ]
```
