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_id
unit
payer
los_days
101
MED
Medicare
4
102
MED
NULL
6
103
MED
Medicaid
2
104
SURG
Medicare
3
105
SURG
Commercial
5
106
SURG
NULL
NULL
107
ICU
Medicare
7
108
ICU
NULL
9
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
FROM
Reads the input rows from the tables named.
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
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
HAVING
Tests each group once and discards the groups that fail. It can test an aggregate such as count(*).
5
SELECT list
Computes each result column once per group. An aggregate is computed over all the rows in the group.
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
unit
stays
stays_with_los
total_days
avg_los
ICU
2
2
16
8.0
MED
3
3
12
4.0
SURG
3
2
8
4.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
unit
long_stays
ICU
2
MED
2
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
The counts
count(payer) skips the three NULL payers and returns 5. count(*) returns 8.
2
share_int
5 ÷ 8 is 0.625 as a fraction, but integer division drops the .625 and returns 0.
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
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.
First, the division runs before the multiplication. Both operands are integers, so the share truncates to 0, and 0 × 100 is still 0. Multiply by 100.0 before dividing, so the division keeps its fraction. Second, count(*) also counts the discharges whose follow-up is still open, which pulls the rate down. If the rate should cover only discharges with a known outcome, divide by count(readmitted), which skips the NULLs.
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_id
triage_level
wait_minutes
1
2
35
2
NULL
50
3
3
20
4
1
5
5
NULL
40
6
4
15
The query has no WHERE and no GROUP BY, so it returns one row computed over all six rows of ed_visits. count(*) counts every row, NULLs included, and returns 6. count(triage_level) counts only the rows where triage_level is not NULL. Visits 2 and 5 have none, so it returns 4. Six triaged visits counts the two NULLs, as if count(triage_level) counted rows the way count(*) does. Four visits makes count(*) skip the rows that hold a NULL, but count(*) never skips a row. A NULL for triaged assumes one missing value makes the whole aggregate NULL; count skips NULL values and still returns a number.
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_id
unit
los_days
201
MED
3
202
MED
5
203
SURG
2
204
SURG
NULL
205
MED
4
WHERE keeps only the rows whose unit is ICU, and there are none. The query has aggregates but no GROUP BY, so it still returns exactly one row, even with no input rows. In that row, count(*) counts zero rows and returns 0. sum(los_days) has no non-NULL values to add, so it returns NULL; the Structured Query Language (SQL) standard requires this, and SQLite and PostgreSQL both follow it. A total of 0 is the tempting answer, but sum of no rows is NULL, not zero; coalesce(sum(los_days), 0) would show 0. No rows would be right with a GROUP BY, which makes one row per group and has no groups here, or with a HAVING clause that removes the single row; this query has neither. A NULL count treats count like sum, but count returns 0 when there are no rows.
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_id
days_to_followup
301
3
302
NULL
303
6
304
NULL
avg() averages only the non-NULL values in the group. Discharges 301 and 303 have values, so the average is (3 + 6) ÷ 2 = 4.5. The result is a decimal value even though every input is a whole number. 2.25 counts the two NULLs as zeros and divides 9 by all 4 rows; avg divides by the count of non-NULL values, not by the count of rows. 4 assumes the average of an integer column is truncated like integer division, but avg keeps the fraction. NULL assumes one missing value makes the average NULL; avg returns NULL only when there are no non-NULL values at all.
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_id
payer
401
Medicare
402
NULL
403
Medicaid
404
NULL
405
Medicare
406
Commercial
GROUP BY puts rows with the same payer into one group, and for grouping, NULL values count as equal. Claims 402 and 404 therefore form one group whose payer is NULL. The SELECT list is then computed for that group. count(*) counts both rows and returns 2. count(payer) counts the rows where payer is not NULL, and there are none, so it returns 0. The result has four rows: Commercial, Medicaid, Medicare and NULL. A with_payer of 2 counts the NULLs, which count(column) never does. Two separate NULL rows would treat each NULL as a different value, but grouping treats NULLs as equal. Leaving the NULL rows out confuses GROUP BY with a WHERE test on payer; GROUP BY keeps every row that reaches it.
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_id
unit
los_days
501
MED
2
502
MED
5
503
MED
6
504
SURG
4
505
SURG
8
506
SURG
NULL
507
ICU
9
508
ICU
3
FROM reads the eight stays. WHERE then keeps only the rows whose length of stay (LOS) is 5 days or more: 502, 503, 505 and 507. Stay 506 drops out, because a NULL LOS compared with 5 gives NULL, and WHERE keeps only rows whose test is true. GROUP BY forms MED with 2 rows, SURG with 1 and ICU with 1. HAVING tests each group and keeps only MED. The result is one row, MED 2. ICU 1, MED 2 and SURG 1 tests HAVING against every stay on the unit, before WHERE has removed the short ones, which is not the order the clauses run in. MED 2 and SURG 2 lets the NULL LOS pass the WHERE test. ICU 2, MED 3 and SURG 3 ignores WHERE and counts every stay.
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_id
readmitted
601
1
602
0
603
0
604
1
605
0
606
NULL
The query has no GROUP BY, so it returns one row for all six discharges. sum(readmitted) adds the non-NULL values: 1 + 0 + 0 + 1 + 0 = 2. count(*) counts all 6 rows, including the open one. Multiplication and division have the same precedence and run left to right, so 100 × 2 = 200 comes first, then 200 ÷ 6. Both operands are integers, so the division truncates toward zero and returns 33. 33.3 expects the fraction to be kept, which needs a decimal operand such as 100.0. 40 divides by the 5 discharges with a known outcome, which is what count(readmitted) would count, not count(*). 0 divides 2 by 6 first, which truncates to 0 before the multiplication, but the query multiplies first.
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_id
patient_id
711
P01
712
P02
713
P03
714
P04
715
P05
followup_visits
visit_id
patient_id
701
P01
702
P03
703
NULL
704
P04
The subquery returns P01, P03, NULL and P04. WHERE then tests each discharge with NOT IN. For P01, P03 and P04 a match is found, so NOT IN is false. For P02 and P05 no match is found, but the list holds a NULL. Comparing P02 with NULL gives NULL, so NOT IN gives NULL, not true. WHERE keeps only rows whose test is true, so every row is dropped and the query returns no rows. P02 and P05 is what the care manager wanted, and it is what the query returns once the subquery adds WHERE patient_id IS NOT NULL. Without that filter, the NULL does not drop out the way it does in an aggregate. Returning all five patients treats the comparison with NULL as true. The query is valid, and a NULL in the subquery result is not an error.
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_id
unit
los_days
801
MED
4
802
MED
3
803
SURG
NULL
804
SURG
NULL
805
ICU
6
806
ICU
5
807
PEDS
2
GROUP BY makes four groups. Before HAVING they hold ICU 2 stays and 11 days, MED 2 and 7, PEDS 1 and 2, and SURG 2 and NULL. SURG's total is NULL because sum() has no non-NULL values to add. HAVING then tests each group. ICU fails, because 11 is not less than 10. For SURG, NULL < 10 gives NULL, and HAVING, like WHERE, keeps only a group whose test is true, so SURG is discarded. ORDER BY returns MED, then PEDS. SURG 2 0 treats the sum of the NULLs as 0, which would pass the test; sum returns NULL here, and only coalesce would turn it into 0. SURG 2 NULL keeps a group whose test is NULL, as if HAVING discarded only groups whose test is false. SURG 0 NULL also has count(*) skip the NULL rows, but count(*) counts every row in the group.
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_id
unit
attending_id
los_days
901
MED
D11
4
902
MED
D12
9
903
MED
D11
2
904
SURG
D21
5
905
SURG
D22
3
The query groups by unit, so each unit returns one row. unit has one value per group, and max(los_days) is an aggregate, but attending_id is neither grouped nor aggregated. That makes it a bare column. SQLite allows bare columns as its own extension; with exactly one max() in the query, it takes attending_id from a row that holds the maximum, D12 for MED and D21 for SURG here. PostgreSQL rejects attending_id here: it is neither grouped nor aggregated, and the query groups by unit, not by a primary key that would fix its value. Calling the query portable mistakes SQLite's max() rule for standard behavior. One row per attending would need attending_id in GROUP BY; selecting a column does not add it to the groups. Selecting max() next to a grouped column such as unit is valid in both engines.
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.
count(*) counts every row; count(column) counts only the rows where the column is not NULL. sum over no rows returns NULL, not 0; coalesce can turn it into 0. 7 / 2 with two integers returns 3, because integer division truncates toward zero; multiply by 1.0 first to get 3.5. A NOT IN test against a list that holds a NULL is never true, so the query returns no rows.
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.
Website analytics
With your permission, Polyseminar measures page views and site performance with Cloudflare Web Analytics, and records which site or page brought you here, so we know where buyers come from. You can change this later in the footer. Privacy notice.