---
schema_version: "1"
id: 99fa68845257d38caf9e2e4a336109ddf5cb7ef3ad7b5a9935075b1c450336c9
title: GROUP BY
collection: developer
version: current
locale: en-us
portal_url: https://docs.salesforce.com/developer/current/en-us/platform/salesforce-soql-sosl/guides/soql-sosl/sforce-api-calls-soql-select-groupby.md
canonical_url: https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select-groupby.html
source_site: developer.salesforce.com
content_type: documentation
content_hash: ab3c68c424c4b4e26d8694c4e24fe4c6cd25204012a0a3970bdece6e8e2f5df8
products:
  - SOQL and SOSL Reference
  - Platform Developer Content
---

# GROUP BY

You can use the `GROUP BY` option in a SOQL query to avoid iterating through individual query results. That is, you specify a group of records instead of processing many individual records.

You can use `GROUP BY` with [aggregate functions](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select-agg-functions.md), such as `SUM()` or `MAX()`, to summarize the data and enable you to roll up query results rather than having to process the individual records in your code.

```soql
[GROUP BY fieldGroupByList]
```

fieldGroupByList specifies a list of one or more fields, separated by commas, that you want to group by. If the list of fields in a `SELECT` clause includes an aggregate function, you must include all non-aggregated fields in the `GROUP BY` clause.

For example, to determine how many leads are associated with each `LeadSource` value without using `GROUP BY`, you could run the following query:

<!-- otherprops: set_clipboard -->

```soql
SELECT LeadSource FROM Lead
```

You would then write some code to iterate through the query results and increment counters for each `LeadSource` value. You can use `GROUP BY` to get the same results without the need to write any extra code. For example:

<!-- otherprops: set_clipboard -->

```soql
SELECT LeadSource, COUNT(Name)
FROM Lead
GROUP BY LeadSource
```

You can use a `GROUP BY` clause without an aggregated function to query all the distinct values, including `null`, for an object. The following query returns the distinct set of values stored in the `LeadSource` field.

<!-- otherprops: set_clipboard -->

```soql
SELECT LeadSource
FROM Lead
GROUP BY LeadSource
```
