GROUP BY
Introduction
GROUP BY puts rows that hold the same value into one group and gives back one row for each group. An aggregate function such as COUNT or SUM works out one value from each group's rows.
Here you will:
- group rows by one column and by several
- count, add up and average each group, and find its smallest and largest value
- see what
NULLdoes in a group and in an aggregate - see which columns a grouped
SELECTcan show, on SQLite and on PostgreSQL - filter rows with
WHEREbefore they are grouped
What is GROUP BY?
Rows whose GROUP BY columns hold the same values go into the same group, and each group becomes one row of the result.
Eight Payments
Here are eight rows of the payments table, as it stores them. rowid is the number SQLite gives each row of a table, and BETWEEN 233 AND 240 takes eight of them:
SELECT payment_type, payment_value
FROM olist_order_payments_dataset
WHERE rowid BETWEEN 233 AND 240;There are 4 payment types: credit_card 4 times, boleto 2 times, voucher and debit_card once each.
Grouped by Payment Type
SELECT payment_type,
AVG(payment_value) AS avg_value,
COUNT(*) AS n
FROM olist_order_payments_dataset
WHERE rowid BETWEEN 233 AND 240
GROUP BY payment_type;Four groups, so four rows, each with its payment_type, the average of its rows' values and how many rows it holds: the 4 credit_card payments average 343.57.

Basic Syntax
SELECT column_to_group_by,
AGGREGATE_FUNCTION(column)
FROM table_name
GROUP BY column_to_group_by;
Watch Rows Fold into Groups
Pick a table and a GROUP BY, then read the rows one at a time or all at once. Each row's key cells light; when its key is new, a box opens for its group, and a copy of the row rides the rail into its box. As the copy lands, the box's aggregates take it in. AVG is worked out once every row is in, as SQLite does it: the total over the count.

Aggregate Functions
An aggregate function works out one value from many rows.
Common Aggregate Functions
| Function | Purpose | Example |
|---|---|---|
COUNT(*) | Count the rows | How many orders? |
COUNT(column) | Count the values that are not NULL | How many reviews have a comment? |
SUM(column) | Add the values up | Total paid |
AVG(column) | Average the values | Average payment |
MIN(column) | The smallest value | Cheapest item |
MAX(column) | The largest value | Most expensive item |
Without GROUP BY
With no GROUP BY, the whole table is one group, and the result is one row:
SELECT COUNT(*) AS total_customers
FROM olist_customers_dataset;SELECT AVG(price) AS avg_price
FROM olist_order_items_dataset;AVG comes back as a long decimal: 120.6537390146471. In SQLite's words, "The result of avg() is always a floating point value whenever there is at least one non-NULL input even if all inputs are integers." ROUND keeps two decimals, as shown under SUM and AVG below.
With GROUP BY
SELECT customer_state, COUNT(*) AS customers_in_state
FROM olist_customers_dataset
GROUP BY customer_state;One row for each of the 27 states. SQLite returned them from AC to TO; PostgreSQL 17, given the same 99,441 state values, grouped them by hashing and returned SC first. Without ORDER BY no order is promised: "If a SELECT statement that returns more than one row does not have an ORDER BY clause, the order in which the rows are returned is undefined."
COUNT Function
COUNT comes in three forms.
COUNT(*) vs COUNT(column)
| Syntax | What It Counts |
|---|---|
COUNT(*) | Every row of the group |
COUNT(column) | The rows where the column is not NULL |
COUNT(DISTINCT column) | The different values that are not NULL |
SQLite's documentation: "The count(X) function returns a count of the number of times that X is not NULL in a group. The count() function (with no arguments) returns the total number of rows in the group."*
Example: COUNT(*)
SELECT order_status, COUNT(*) AS order_count
FROM olist_orders_dataset
GROUP BY order_status;delivered has 96,478 of the 99,441 orders.
Example: COUNT(column)
SELECT review_score,
COUNT(*) AS reviews,
COUNT(review_comment_message) AS reviews_with_comments
FROM olist_order_reviews_dataset
GROUP BY review_score;Of the 11,858 reviews with a score of 1, 9,179 have a comment: COUNT(review_comment_message) leaves out the reviews whose comment is NULL.
Example: COUNT(DISTINCT)
SELECT customer_state, COUNT(DISTINCT customer_city) AS unique_cities
FROM olist_customers_dataset
GROUP BY customer_state;SP has 629 different cities.
SUM and AVG Functions
SUM adds a group's values up; AVG divides that total by how many values there are.
SUM Example
SELECT payment_type, SUM(payment_value) AS total_value
FROM olist_order_payments_dataset
GROUP BY payment_type;Credit card payments add up to 12542084.19.
AVG Example
SELECT p.product_category_name, AVG(i.price) AS avg_price
FROM olist_order_items_dataset AS i
JOIN olist_products_dataset AS p ON i.product_id = p.product_id
GROUP BY p.product_category_name;The first row's category is NULL: the items whose product has no category form one group of their own, as SQLite's documentation says: "For the purposes of grouping rows, NULL values are considered equal."
Combining SUM and AVG
SELECT payment_type,
COUNT(*) AS payment_count,
SUM(payment_value) AS total_value,
AVG(payment_value) AS avg_value
FROM olist_order_payments_dataset
GROUP BY payment_type;Two Decimals
SELECT payment_type,
COUNT(*) AS payment_count,
ROUND(AVG(payment_value), 2) AS avg_value
FROM olist_order_payments_dataset
GROUP BY payment_type;ROUND(AVG(payment_value), 2) gives credit_card 163.32 where AVG alone gives 163.3190206393645. PostgreSQL's AVG of whole numbers is a numeric with many decimals: the average of 1 and 2 prints as 1.5000000000000000 there.
MIN and MAX Functions
MIN finds a group's smallest value, MAX its largest.
Example: Price Range
SELECT seller_id, MIN(price) AS lowest_price, MAX(price) AS highest_price
FROM olist_order_items_dataset
GROUP BY seller_id;A seller who sold at a single price has the same lowest and highest: the first row's seller, at 895.
Example: Date Range
In this dataset every order has a customer_id of its own: 99,441 orders, 99,441 customer_id values. The person behind them is customer_unique_id (96,096 of them), so a person's first and last orders come from grouping by it:
SELECT c.customer_unique_id,
COUNT(*) AS orders,
MIN(o.order_purchase_timestamp) AS first_order,
MAX(o.order_purchase_timestamp) AS last_order
FROM olist_orders_dataset AS o
JOIN olist_customers_dataset AS c ON o.customer_id = c.customer_id
GROUP BY c.customer_unique_id
ORDER BY orders DESC
LIMIT 10;The busiest customer placed 17 orders, from 2017-05-15 23:30:03 to 2018-08-20 19:14:26. Grouped by customer_id, all 99,441 groups would hold one order each, and its first and last order would be the same.
Combining Multiple Aggregates
SELECT order_id,
COUNT(*) AS item_count,
SUM(price) AS total_price,
MIN(price) AS cheapest_item,
MAX(price) AS most_expensive_item,
AVG(price) AS avg_item_price
FROM olist_order_items_dataset
GROUP BY order_id;An order of one item has the same cheapest, most expensive and average price; the first order of two items here holds two at 49.9, 99.8 in all.
The SELECT and GROUP BY Rule
A grouped query gives one row for each group, so each column of its SELECT should have one value for each group: a column it groups by, or an aggregate.
A Query Both Engines Run
SELECT customer_state, COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state;A Column Neither Grouped nor Aggregated
SELECT customer_state, customer_city, COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state;PostgreSQL refuses this query: its error says that customer_city must appear in the GROUP BY clause or be used in an aggregate function. SQLite runs it and gives each state the city of one of its rows: SP shows franca, one of its 629 cities. SQLite does not say which row: "Otherwise, it is evaluated against a single arbitrarily chosen row from within the group." Its documentation calls such a column a bare column, and "The usual case is that all column names in an aggregate query are either arguments to aggregate functions or else appear in the GROUP BY clause."
SQLite names the row in one case: "If there is exactly one min() or max() aggregate in the query, then all bare columns in the result set take values from an input row which also contains the minimum or maximum."
SELECT customer_state, customer_city,
MAX(customer_zip_code_prefix) AS highest_zip
FROM olist_customers_dataset
GROUP BY customer_state
ORDER BY customer_state
LIMIT 3;Each state shows the city of a row that holds its highest zip code prefix: AC, cruzeiro do sul, 69980.
Two Fixes
Group by the column too, so each state and city is a group:
SELECT customer_state, customer_city, COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state, customer_city;Or aggregate it, so each state gets one value:
SELECT customer_state, COUNT(DISTINCT customer_city) AS city_count
FROM olist_customers_dataset
GROUP BY customer_state;Grouping by Multiple Columns
GROUP BY can take several columns: each different combination of their values is a group.
Syntax
GROUP BY column1, column2, column3
Example: State and City
SELECT customer_state, customer_city, COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state, customer_city
ORDER BY customer_state, customer_count DESC;How It Works
With GROUP BY customer_state, customer_city:
- (
SP,sao paulo) is one group, 15,540 rows - (
SP,campinas) is another, 1,444 rows - (
RJ,rio de janeiro) is another, 6,882 rows
Practical Example
SELECT payment_type,
payment_installments,
COUNT(*) AS payment_count,
AVG(payment_value) AS avg_value
FROM olist_order_payments_dataset
GROUP BY payment_type, payment_installments
ORDER BY payment_type, payment_installments;boleto, debit_card and voucher each make one group here, all paid in one installment; credit_card makes 24, from 0 to 24 installments.
GROUP BY with WHERE
WHERE filters rows before they are grouped.
The Order of the Steps
FROMtakes the tableWHEREkeeps the rows its condition is true forGROUP BYgroups the rows that are leftSELECTworks out each group's columns and aggregates
Example
SELECT customer_state, COUNT(*) AS customer_count
FROM olist_customers_dataset
WHERE customer_city IN ('sao paulo', 'rio de janeiro', 'brasilia')
GROUP BY customer_state
ORDER BY customer_count DESC;Only the rows of those three cities are grouped: SP keeps 15,540 of its 41,746 rows.
Another Example
The average price of each seller's items priced over 50:
SELECT seller_id, COUNT(*) AS item_count, AVG(price) AS avg_price
FROM olist_order_items_dataset
WHERE price > 50
GROUP BY seller_id
ORDER BY avg_price DESC;The first seller sold one item over 50, at 6729.
Practice
Each exercise runs on the course's tables: press Run to see its rows.
Exercise 1: Basic COUNT with GROUP BY
Count the customers in each state:
-- Count customers per state
SELECT
customer_state,
COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state
ORDER BY customer_count DESC
LIMIT 10;SP leads with 41,746.
Exercise 2: SUM with GROUP BY
Total payment value for each payment type:
-- Total payment value by payment type
SELECT
payment_type,
SUM(payment_value) AS total_value,
COUNT(*) AS payment_count
FROM olist_order_payments_dataset
GROUP BY payment_type
ORDER BY total_value DESC;credit_card comes first, with 12542084.19.
Exercise 3: AVG, MIN, MAX
Price figures for each seller:
-- Price statistics per seller
SELECT
seller_id,
COUNT(*) AS items_sold,
AVG(price) AS avg_price,
MIN(price) AS min_price,
MAX(price) AS max_price
FROM olist_order_items_dataset
GROUP BY seller_id
ORDER BY items_sold DESC
LIMIT 10;The busiest seller sold 2,033 items, priced from 16 to 249.
Exercise 4: Multiple Column GROUP BY
Count the customers in each state and city:
-- Customer count by state and city
SELECT
customer_state,
customer_city,
COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state, customer_city
ORDER BY customer_count DESC
LIMIT 15;(SP, sao paulo) leads with 15,540.
Exercise 5: GROUP BY with WHERE Filter
Count the orders with a delivery date, by status:
-- Order count by status (only where delivery date exists)
SELECT
order_status,
COUNT(*) AS order_count
FROM olist_orders_dataset
WHERE order_delivered_customer_date IS NOT NULL
GROUP BY order_status
ORDER BY order_count DESC;96,470 delivered orders and 6 canceled ones have a delivery date.
Exercise 6: COUNT DISTINCT
Count the items and the different products in each order:
-- Unique products per order
SELECT
order_id,
COUNT(*) AS total_items,
COUNT(DISTINCT product_id) AS unique_products
FROM olist_order_items_dataset
GROUP BY order_id
ORDER BY total_items DESC
LIMIT 10;The first order holds 21 items of 3 products.
Common Use Cases
1. Top N Analysis
SELECT customer_state, COUNT(*) AS customers
FROM olist_customers_dataset
GROUP BY customer_state
ORDER BY customers DESC
LIMIT 5;2. Time-Based Aggregation
SELECT strftime('%Y-%m', order_purchase_timestamp) AS order_month,
COUNT(*) AS order_count
FROM olist_orders_dataset
GROUP BY strftime('%Y-%m', order_purchase_timestamp)
ORDER BY order_month;There is no 2016-11 row: no order was placed that month, and GROUP BY makes a group only for a value that some row holds.
3. Distribution Analysis
SELECT review_score,
COUNT(*) AS review_count,
ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM olist_order_reviews_dataset), 2)
AS percentage
FROM olist_order_reviews_dataset
GROUP BY review_score
ORDER BY review_score;4. Summary Statistics
SELECT order_status,
COUNT(*) AS order_count,
SUM(CASE WHEN order_delivered_customer_date IS NOT NULL THEN 1 ELSE 0 END)
AS delivered_count
FROM olist_orders_dataset
GROUP BY order_status;6 canceled orders have a delivery date.
Summary
Key Takeaways
GROUP BYputs rows that share values in one group, one result row eachCOUNT,SUM,AVG,MINandMAXwork out one value from each group's rowsCOUNT(*)counts rows;COUNT(column)leaves outNULLs, and allNULLkeys form one group- Several columns make finer groups, one for each combination
WHEREfilters rows before they are grouped- A column neither grouped nor aggregated is refused by PostgreSQL; SQLite takes it from one row of the group
- Without
ORDER BYthe groups come back in no promised order
Quick Reference
-- Basic GROUP BY
SELECT column, COUNT(*)
FROM table_name
GROUP BY column;
-- Several aggregates
SELECT column, COUNT(*), SUM(val), AVG(val)
FROM table_name
GROUP BY column;
-- Several grouping columns
SELECT col1, col2, COUNT(*)
FROM table_name
GROUP BY col1, col2;
-- With a WHERE filter, in a set order
SELECT column, COUNT(*)
FROM table_name
WHERE condition
GROUP BY column
ORDER BY column;
What's Next?
HAVING filters the groups once they are formed, where WHERE filters rows before.