# Explain the difference between GROUP BY, GROUP BY ROLLUP, and GROUP BY CUBE in SOQL.

**Topic:** Soql · **Difficulty:** Hard · **Asked at:** Deloitte, PwC, Salesforce · **Tags:** soql, aggregate, group-by, rollup, cube

Read it on the site: https://www.forcechallenges.com/interview-questions/explain-the-difference-between-group-by-group-by-rollup-and-group-by-cube-in-soql

## Answer

- `GROUP BY` groups rows by field values and gives one row per group.
- `GROUP BY ROLLUP(f1, f2)` adds subtotal rows for each level plus a grand total. Use `GROUPING(field)` to detect subtotal rows.
- `GROUP BY CUBE(f1, f2)` adds subtotals for **all combinations** of the fields (more rows than ROLLUP).

```soql
SELECT LeadSource, Rating, COUNT(Id) FROM Lead GROUP BY ROLLUP(LeadSource, Rating)
SELECT Type, BillingCountry, COUNT(Id) FROM Account GROUP BY CUBE(Type, BillingCountry)
```

---
Source: ForceChallenges · last updated 2026-10-21
