Skip to main content

Aggregate Functions

Aggregate functions turn many row values into one summary value.

They are essential for reporting, dashboards, and quick data health checks.

Core Concepts​

FunctionPurposeExample
COUNT()Count rows/valuesCOUNT(*)
SUM()Total numeric valuesSUM(amount)
AVG()Mean numeric valueAVG(score)
MIN()Smallest valueMIN(price)
MAX()Largest valueMAX(price)
-- One result row for the whole input set.
SELECT
COUNT(*) AS row_count,
SUM(amount) AS total_amount,
AVG(amount) AS avg_amount
FROM payments_agg;
row_counttotal_amountavg_amount
e.g. 5e.g. 430.00e.g. 86.0

Code Examples​

-- Setup sample data for this module.
CREATE TABLE payments_agg (
payment_id INTEGER PRIMARY KEY,
category TEXT NOT NULL,
amount REAL NOT NULL
);

INSERT INTO payments_agg (category, amount)
VALUES
('tools', 120.00),
('tools', 80.00),
('cloud', 60.00),
('cloud', 70.00),
('tools', 100.00);
Expected output
Table created and five rows inserted for aggregation practice.
-- Quick multi-metric summary.
SELECT
COUNT(*) AS row_count,
MIN(amount) AS smallest,
MAX(amount) AS largest
FROM payments_agg;
row_countsmallestlargest
560.0120.0

SQLite-Specific Nuances​

SQLite Nuance

SQLite aggregate behavior follows standard SQL, but numeric conversion can be influenced by SQLite's dynamic typing rules.

Use clear numeric columns for predictable totals and averages.

Common Pitfalls / Best Practices​

Pitfall

Mixing grouped and non-grouped columns incorrectly, leading to confusing or non-portable results.

Best Practice

When using GROUP BY, aggregate every column that is not part of the grouping key.

Quick Challenge​

Return a single row with total number of payments and total amount from payments_agg.

View Solution
SELECT
COUNT(*) AS payment_count,
SUM(amount) AS total_amount
FROM payments_agg;
payment_counttotal_amount
5430.0