Full answer
Each student sat a test twice, and the report shows the better score. Some students missed one sitting.
On SQLite, the scalar (multi-argument) form of max is used:
CREATE TABLE attempts (student TEXT, first_try INTEGER, second_try INTEGER);
INSERT INTO attempts VALUES ('Ana',70,85),('Ben',90,NULL),('Chen',NULL,60),('Dara',NULL,NULL);SELECT student, first_try, second_try, max(first_try, second_try) AS best
FROM attempts ORDER BY student;| student | first_try | second_try | best |
|---|---|---|---|
| Ana | 70 | 85 | 85 |
| Ben | 90 | NULL | NULL |
| Chen | NULL | 60 | NULL |
| Dara | NULL | NULL | NULL |
Ben missed the retest and Chen missed the first test. SQLite's max(a, b) returns NULL as soon as any argument is NULL, so both lost their score.
PostgreSQL's GREATEST skips NULLs:
SELECT student, GREATEST(first_try, second_try) AS best
FROM attempts ORDER BY student;| student | best |
|---|---|
| Ana | 85 |
| Ben | 90 |
| Chen | 60 |
| Dara | NULL |
MySQL's GREATEST behaves like SQLite here and returns NULL when any argument is NULL; that comes from MySQL documentation and was not run here.
A version that gives the PostgreSQL behaviour on any engine:
SELECT student,
CASE
WHEN first_try IS NULL THEN second_try
WHEN second_try IS NULL THEN first_try
WHEN first_try >= second_try THEN first_try
ELSE second_try
END AS best
FROM attempts ORDER BY student;| student | best |
|---|---|
| Ana | 85 |
| Ben | 90 |
| Chen | 60 |
| Dara | NULL |
The CASE checks NULL first, then compares. It returns NULL only when both scores are missing, which is the honest answer for Dara. Using COALESCE(first_try, 0) would also produce numbers, but it would turn "both missing" into a score of 0, which is a different statement.
CREATE TABLE attempts (student TEXT, first_try INTEGER, second_try INTEGER);
INSERT INTO attempts VALUES ('Ana',70,85),('Ben',90,NULL),('Chen',NULL,60),('Dara',NULL,NULL);
SELECT student, first_try, second_try, max(first_try, second_try) AS best
FROM attempts ORDER BY student;
SELECT student,
CASE
WHEN first_try IS NULL THEN second_try
WHEN second_try IS NULL THEN first_try
WHEN first_try >= second_try THEN first_try
ELSE second_try
END AS best
FROM attempts ORDER BY student;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- SQLite max(a, b) and MySQL GREATEST return NULL if any argument is NULL
- PostgreSQL GREATEST ignores NULLs
- A CASE with explicit IS NULL checks is portable
- COALESCE with 0 changes 'unknown' into 'zero'
Common mistakes
- Assuming GREATEST behaves the same on PostgreSQL and MySQL
- Using COALESCE(x, 0) where 0 is a meaningful value
Follow-ups
- How does this differ from the aggregate MAX(col)?
- How would you take the best of three nullable attempts?
Tips
- Mention that aggregate MAX ignores NULLs while scalar max may not