Domain 4 /

How do you aggregate, and what does NULL do?

By the endWrite GROUP BY and HAVING queries, and predict what NULL values, empty inputs and integer division do to an aggregate.

An aggregate turns many rows into one value

An aggregate function reads a set of rows and returns one value: count, sum, avg (the average), min or max. GROUP BY splits the rows into groups, and the query returns one row for each group.

NULL values and whole numbers cause most of the errors. NULL marks a value that is missing. Most aggregates skip it, so a count or an average can use fewer rows than you expect. Dividing one whole number by another drops the fraction.

The queries use core Structured Query Language (SQL) and give the same result in SQLite and PostgreSQL. A bare column, described below, is where the two differ. The encounters table below stores los_days as an INTEGER column, and a NULL cell is an SQL NULL.

encounters: eight inpatient stays
encounter_idunitpayerlos_days
101MEDMedicare4
102MEDNULL6
103MEDMedicaid2
104SURGMedicare3
105SURGCommercial5
106SURGNULLNULL
107ICUMedicare7
108ICUNULL9

Units: MED is medicine, SURG is surgery, ICU is the intensive care unit. los_days is the length of stay (LOS) in days. Three stays have no payer on file yet. Encounter 106 is still in the hospital, so it has no LOS.

An aggregate query runs in a fixed order

  1. 1

    FROM

    Reads the input rows from the tables named.

  2. 2

    WHERE

    Keeps only the rows for which the condition is true. A row whose condition is false or NULL is dropped before any group is formed.

  3. 3

    GROUP BY

    Puts rows with the same values in the grouping columns into one group. Rows whose grouping value is NULL form one group together.

  4. 4

    HAVING

    Tests each group once and discards the groups that fail. It can test an aggregate such as count(*).

  5. 5

    SELECT list

    Computes each result column once per group. An aggregate is computed over all the rows in the group.

  6. 6

    ORDER BY

    Sorts the result rows. Without it, the order of the rows is undefined.

What each aggregate does with NULL

count(*)

Counts every row in the group, NULLs included.

count(column)

Counts the rows where the column is not NULL.

count(DISTINCT column)

Counts the different non-NULL values in the column.

sum(column)

Adds the non-NULL values. With no non-NULL values to add, it returns NULL, not 0.

avg(column)

Averages the non-NULL values, so it divides by the count of non-NULL values, not by the count of rows. It returns a decimal value even when every input is a whole number.

min(column) and max(column)

Return the smallest or largest non-NULL value. They return NULL only when the group has no non-NULL values.

Counting rows is not counting values

Stays, stays with a LOS, total days and average LOS by unit
SELECT unit,
       count(*)        AS stays,
       count(los_days) AS stays_with_los,
       sum(los_days)   AS total_days,
       avg(los_days)   AS avg_los
FROM encounters
GROUP BY unit
ORDER BY unit;
Result of the query by unit
unitstaysstays_with_lostotal_daysavg_los
ICU22168.0
MED33124.0
SURG3284.0

SURG has 3 stays but only 2 with a LOS. Its average divides 8 days by those 2 stays, which gives 4.0.

Every result column must be grouped or aggregated

Each group returns exactly one row, so each result column needs one value per group. A column listed in GROUP BY has one value in its group. Put every other column inside an aggregate function.

A column that is neither grouped nor aggregated is called a bare column. SQLite accepts one and fills it from one row of the group, usually an arbitrary row you cannot predict. With a single min() or max() in the query, SQLite takes the bare column from a row holding that minimum or maximum, but ties still make the choice arbitrary. PostgreSQL rejects a bare column, with one exception: it accepts a column of a table whose primary key is in GROUP BY, because the key fixes that column's value. Leave them out of every query you write: group by the column, or wrap it in an aggregate.

WHERE filters rows, HAVING filters groups

Put a test on single rows in WHERE and a test on an aggregate in HAVING.

WHERE

  • Runs before grouping
  • Tests one row at a time
  • Decides which rows reach the aggregates
  • Drops a row whose test is false or NULL

HAVING

  • Runs after grouping
  • Tests one group at a time
  • Can test an aggregate, such as count(*) >= 2
  • Drops a group whose test is false or NULL

WHERE and HAVING in one query

Units with at least two stays of 4 days or more
SELECT unit,
       count(*) AS long_stays
FROM encounters
WHERE los_days >= 4
GROUP BY unit
HAVING count(*) >= 2
ORDER BY unit;
Result of the WHERE and HAVING query
unitlong_stays
ICU2
MED2

WHERE keeps encounters 101, 102, 105, 107 and 108. Encounter 106 drops out because a NULL LOS compared with 4 gives NULL, not true. The groups then hold ICU 2, MED 2 and SURG 1, and HAVING discards SURG.

Aggregating no rows gives NULL, not zero

An aggregate query without GROUP BY returns exactly one row, even when no input rows are left, unless a HAVING clause removes that row. In that row, count(*) is 0 and sum() is NULL. The SQL standard requires sum() to return NULL here, and SQLite and PostgreSQL both do.

The encounters table has no PEDS (pediatrics) stays, so the query below returns one row: 0 stays, a NULL total and 0 in the last column. coalesce() returns its first argument that is not NULL, so it turns the empty sum into 0. Use it when a report must show zero instead of a blank.

With GROUP BY, the same filter returns no rows at all. Each group makes one row, and an empty input makes no groups.

Counting and summing stays on a unit that has none
SELECT count(*)                  AS stays,
       sum(los_days)             AS total_days,
       coalesce(sum(los_days), 0) AS total_or_zero
FROM encounters
WHERE unit = 'PEDS';

Integer division drops the fraction

Share of stays with a payer on file, three ways
SELECT count(payer) / count(*)         AS share_int,
       100 * count(payer) / count(*)   AS pct_int,
       100.0 * count(payer) / count(*) AS pct
FROM encounters;

Worked example

Why the share comes out as 0

An analyst wants the percentage of stays in the encounters table that have a payer on file. Both counts are whole numbers. When both operands of a division are integers, SQLite and PostgreSQL return an integer and drop the fraction, truncating toward zero. Work out each column of the query above.

  1. 1

    The counts

    count(payer) skips the three NULL payers and returns 5. count(*) returns 8.

  2. 2

    share_int

    5 ÷ 8 is 0.625 as a fraction, but integer division drops the .625 and returns 0.

  3. 3

    pct_int

    The operators run left to right. 100 × 5 = 500, then 500 ÷ 8 = 62.5, truncated to 62. Multiplying first helps, but the half is still lost.

  4. 4

    pct

    100.0 is not an integer, so 100.0 × 5 = 500.0 and the division keeps its fraction: 500.0 ÷ 8 = 62.5.

Result: The query returns 0, 62 and 62.5. Make one operand a decimal before dividing, for example by multiplying by 1.0 or 100.0, whenever a rate or share should keep its fraction.

NOT IN with a NULL in the list returns nothing

x NOT IN (list) is true only when x is unequal to every value in the list. Comparing x with NULL gives NULL, not true or false. So when x is not found and the list contains a NULL, NOT IN gives NULL, and WHERE drops the row. Every row is dropped, and the query returns no rows. A row whose own value is NULL is dropped too, because NOT IN gives NULL for a NULL on the left.

In the first query below, the subquery returns the SURG payers: Medicare, Commercial and NULL. Because of that NULL, the query returns no rows. The second query removes the NULL inside the subquery. It returns one row, encounter 103 with Medicaid. Encounters 102, 106 and 108 have a NULL payer of their own, so they are still left out.

A NOT IN subquery with a NULL, and the corrected query
-- Payers never seen on the surgical unit (returns no rows)
SELECT encounter_id, payer
FROM encounters
WHERE payer NOT IN (SELECT payer FROM encounters WHERE unit = 'SURG');

-- The same question with the NULL removed from the subquery
SELECT encounter_id, payer
FROM encounters
WHERE payer NOT IN (SELECT payer FROM encounters
                    WHERE unit = 'SURG' AND payer IS NOT NULL);

Try it

Find the two errors

A quality report computes, for each unit, the percentage of discharges readmitted within 30 days. The readmitted column holds 1 for yes, 0 for no, and NULL while follow-up is still open. The report divides the sum of readmitted by count(*), then multiplies the result by 100. Every unit shows 0%, although some units had readmissions. What went wrong, and how do you fix it?

Hint: Look at the order of the arithmetic and at what the denominator counts.

02 / Questions

Answer 9 questions

Check 1 of 9scenario · easy

An emergency department (ED) analyst runs the query in the exhibit on the ed_visits table. Two visits have no triage level recorded. What does the query return?

Query run on ed_visits
SELECT count(*)            AS visits,
       count(triage_level) AS triaged
FROM ed_visits;
ed_visits
visit_idtriage_levelwait_minutes
1235
2NULL50
3320
415
5NULL40
6415
Check 2 of 9scenario · easy

A dashboard query totals the inpatient days on the intensive care unit (ICU). The encounters table in the exhibit has no ICU stays this week. What does the query return?

Query run on encounters
SELECT count(*)      AS stays,
       sum(los_days) AS total_days
FROM encounters
WHERE unit = 'ICU';
encounters
encounter_idunitlos_days
201MED3
202MED5
203SURG2
204SURGNULL
205MED4
Check 3 of 9scenario · easy

A care transitions analyst averages the days from discharge to the first follow-up visit. Two patients in the exhibit have not had a follow-up visit yet, so their value is NULL. What value does the query return?

Query run on discharges
SELECT avg(days_to_followup) AS avg_days
FROM discharges;
discharges
discharge_iddays_to_followup
3013
302NULL
3036
304NULL
Check 4 of 9scenario · medium

A revenue cycle analyst groups the claims in the exhibit by payer. Two claims have no payer recorded. What does the result show for those two claims?

Query run on claims
SELECT payer,
       count(*)     AS claims,
       count(payer) AS with_payer
FROM claims
GROUP BY payer;
claims
claim_idpayer
401Medicare
402NULL
403Medicaid
404NULL
405Medicare
406Commercial
Check 5 of 9scenario · medium

A utilization reviewer wants the units with at least two stays of 5 days or more. She runs the query in the exhibit on the encounters table. Which rows does it return?

Query run on encounters
SELECT unit,
       count(*) AS long_stays
FROM encounters
WHERE los_days >= 5
GROUP BY unit
HAVING count(*) >= 2
ORDER BY unit;
encounters
encounter_idunitlos_days
501MED2
502MED5
503MED6
504SURG4
505SURG8
506SURGNULL
507ICU9
508ICU3
Check 6 of 9scenario · medium

A quality analyst computes a 30-day readmission percentage from the discharges in the exhibit. readmitted is 1 for a readmission, 0 for none, and NULL while follow-up is still open. What value does readmit_pct hold?

Query run on discharges
SELECT 100 * sum(readmitted) / count(*) AS readmit_pct
FROM discharges;
discharges
discharge_idreadmitted
6011
6020
6030
6041
6050
606NULL
Check 7 of 9scenario · hard

A care manager wants the discharged patients who have had no follow-up visit. One walk-in visit in followup_visits was never matched to a patient, so its patient_id is NULL. What does the query in the exhibit return?

Query run on discharges and followup_visits
SELECT patient_id
FROM discharges
WHERE patient_id NOT IN (SELECT patient_id FROM followup_visits)
ORDER BY patient_id;
discharges
discharge_idpatient_id
711P01
712P02
713P03
714P04
715P05
followup_visits
visit_idpatient_id
701P01
702P03
703NULL
704P04
Check 8 of 9scenario · hard

A bed manager lists the units that used fewer than 10 inpatient days. Both surgical stays in the exhibit are still open, so their length of stay (LOS) is NULL. Which rows does the query return, shown as unit, stays and total_days?

Query run on encounters
SELECT unit,
       count(*)      AS stays,
       sum(los_days) AS total_days
FROM encounters
GROUP BY unit
HAVING sum(los_days) < 10
ORDER BY unit;
encounters
encounter_idunitlos_days
801MED4
802MED3
803SURGNULL
804SURGNULL
805ICU6
806ICU5
807PEDS2
Check 9 of 9scenario · hard

An analyst wrote the query in the exhibit in SQLite to show, for each unit, the longest length of stay (LOS) and the attending physician on that stay. It must now run unchanged in PostgreSQL. Which statement is correct?

Query written in SQLite
SELECT unit,
       attending_id,
       max(los_days) AS longest_stay
FROM encounters
GROUP BY unit
ORDER BY unit;
encounters
encounter_idunitattending_idlos_days
901MEDD114
902MEDD129
903MEDD112
904SURGD215
905SURGD223

03 / Recall

Answer without looking back

Say what count(*) and count(column) each count, what sum returns over no rows, what 7 / 2 returns when both numbers are integers, and what a NOT IN subquery returns when the subquery yields a NULL.

Primary reading

Read the relevant section

Built-in Aggregate Functions (SQLite) · 3. Descriptions of built-in aggregate functions: avg(X), count(X), count(*), max(X), min(X), sum(X) ↗
Sources used in this lesson
  1. Built-in Aggregate Functions (SQLite), 3. Descriptions of built-in aggregate functions: count(X), count(*) ↗SQLite Consortium (sqlite.org)
  2. SELECT (SQLite SQL language documentation), 2.5. Bare columns in an aggregate query ↗SQLite Consortium (sqlite.org)
  3. SQL Language Expressions (SQLite), 2. Operators, and Parse-Affecting Attributes ↗SQLite Consortium (sqlite.org)
  4. Built-In Scalar SQL Functions (SQLite), coalesce(X,Y,...) ↗SQLite Consortium (sqlite.org)
  5. NULL Handling in SQLite Versus Other Database Engines, NULL handling results table (Adding anything to null gives null) ↗SQLite Consortium (sqlite.org)
  6. PostgreSQL 19 Documentation, 9.22 Aggregate Functions, 9.22. Aggregate Functions, note after Table 9.63 ↗The PostgreSQL Global Development Group
  7. PostgreSQL 19 Documentation, 7.2 Table Expressions, 7.2.3. The GROUP BY and HAVING Clauses ↗The PostgreSQL Global Development Group
  8. PostgreSQL 19 Documentation, 9.3 Mathematical Functions and Operators, 9.3, Table 9.4. Mathematical Operators: division ↗The PostgreSQL Global Development Group
  9. PostgreSQL 19 Documentation, 9.25 Subquery Expressions, 9.25.3. NOT IN ↗The PostgreSQL Global Development Group
  10. PostgreSQL 19 Documentation, 9.2 Comparison Functions and Operators, 9.2. Comparison Functions and Operators ↗The PostgreSQL Global Development Group
  11. PostgreSQL 19 Documentation, 9.19 Conditional Expressions, 9.19.2. COALESCE ↗The PostgreSQL Global Development Group
Glossary terms used in this lesson
Medicare
A national program the federal government administers, made up of Part A (Hospital Insurance), Part B (Medical Insurance), Part C (Medicare Advantage) and Part D (Prescription Drug Benefit).
Medicaid
A network of statewide programs that the federal and state governments fund. Each state administers its own program within broad federal guidelines, and each sets its eligibility standards, the type, amount, duration and scope of services, and payment rates.
SQLStructured Query Language
The standard database access language whose basis is the relational data model.
NULL
The null value represents an unknown value. Ordinary comparison operators yield null when either input is null, so a missing value is tested with IS NULL or IS NOT NULL.
GROUP BY
A clause that groups together the rows of a table that have the same values in all the columns listed, combining each set into one group row that represents all rows in the group.
HAVING
A clause used, much like a WHERE clause, to eliminate groups from the result of a grouped query. Its expressions can refer to grouped expressions and to aggregate functions.
DISTINCT
A key word written directly after SELECT that removes duplicate rows from the result. Two rows are distinct if they differ in at least one column value.
ORDER BY
A clause that sorts a query's output, ascending (ASC, the default) or descending (DESC). Without sorting, rows return in an unspecified order. NULLS FIRST or NULLS LAST sets where nulls appear.
coalesce
A function that returns a copy of its first non-NULL argument, or NULL if all its arguments are NULL.
integer division
Division of one integer by another. In SQLite an integer divide yields an integer result, truncated toward zero.
bare column
In an aggregate query, a result column holding a column name that is neither inside an aggregate function nor in the GROUP BY clause. SQLite takes its value from one of the group's input rows, usually one you cannot predict.
primary key
A candidate key that the database designer selects as the identifying mechanism for a table. It must uniquely identify the rows and must not be null.
LOSLength of stay
In HCUP databases, the discharge date minus the admission date. Same-day stays are therefore coded 0, and leave days are not subtracted.