# SOQL Builder

`ts-force` provides a built-in "query builder" that allows generation of SOQL queries via structured data.

There are several advantages of using the SOQL builder over hardcode or templated strings:

* type-safe\*
* reusable
* composable
* consistent

Checkout the [Query Playground](https://stackblitz.com/edit/ts-force-query-playground) to see it in action!

{% hint style="warning" %}
Builder is not fully "type-safe"... It's still possible to generate invalid queries!
{% endhint %}

## Example

```typescript
let qry = buildQuery(Account, fields => ({
    select: [
      fields.select('name'),
      ...fields.parent('owner').select('name', 'phone'),
      fields.subQuery('contacts', subFields => {
        return {
          select: [
            subFields.parent('createdBy').select('managerId'),
            subFields.select('phone')
          ],
          where: [
            { field: subFields.select('otherCity'), op: 'LIKE', val: '%YORK' },
            'OR',
            { field: subFields.select('mailingCity'), op: 'LIKE', val: '%YORK' }
          ]
        }
      })
    ],
    where: [
      { field: fields.select('name'), op: '=', val: 'Acme' }
    ],
    orderBy: { field: fields.select('rating'), order: 'DESC' },
    limit: 5,
    offset: 5
});
```

**Outputs**

```sql
SELECT Name, Owner.Name, Owner.Phone,
 (
    SELECT CreatedBy.ManagerId, Phone 
      FROM Contacts 
      WHERE OtherCity LIKE '%YORK' OR MailingCity LIKE '%YORK'
 )
FROM Account
WHERE Name = 'Acme'
ORDER BY Rating DESC
LIMIT 5 OFFSET 5
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ts-force.gitbook.io/ts-force/guides/query-builder.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
