Scrivio Interview library
ConceptIntermediate8 min read · updated 12 November 2026

Explain how NULL behaves in =, <>, IN, NOT IN, COUNT(col), COUNT(*), GROUP BY and unique constraints in PostgreSQL. Which of these surprise developers most?

In PostgreSQL, = and <> with a NULL give NULL (UNKNOWN), so we test with IS NULL or IS DISTINCT FROM. IN returns UNKNOWN instead of FALSE when the value is missing and the list has a NULL, and NOT IN with any NULL returns no rows. COUNT(col) skips NULLs while COUNT(*) counts rows, GROUP BY puts all NULLs in one group, and unique constraints allow many NULLs unless we declare UNIQUE NULLS NOT DISTINCT (PostgreSQL 15 and later). The ones that surprise developers most are NOT IN, the unique constraint, and in Java, ResultSet.getInt returning 0 for NULL.

Why this question is asked

NULL is the source of a whole family of bugs that pass review and tests and only appear with real data: reports that miss rows, duplicates that a unique constraint was supposed to prevent, and balances that show 0 when the value was unknown. Interviewers ask about it because each operator treats NULL a little differently, and a developer who knows the rules can predict these bugs instead of debugging them. In this answer, we will recap what NULL means, then go through comparisons, IN and NOT IN, counting, grouping, unique constraints and the JDBC mapping, with the result of each line shown.

1A Quick Recap: NULL Means Unknown

NULL is not a value like 0 or an empty string. It marks a value that is missing or unknown. Because of that, SQL does not use plain true and false logic. A condition can be TRUE, FALSE or UNKNOWN, and any comparison involving NULL gives UNKNOWN, since we cannot know whether an unknown value equals something. A WHERE clause keeps only rows where the condition is TRUE, so UNKNOWN behaves like FALSE there, but it behaves differently inside NOT, inside CASE and in constraints, which is where the surprises come from.

2Comparisons: =, <> and IS DISTINCT FROM

Let us start with plain comparisons. PostgreSQL shows UNKNOWN as NULL in a result.

SQL
SELECT NULL = NULL; -- null, not true
SELECT 5 <> NULL; -- null
SELECT NULL IS NULL; -- true
SELECT 5 IS DISTINCT FROM NULL; -- true
SELECT NULL IS DISTINCT FROM NULL; -- false
SELECT * FROM users WHERE middle_name = NULL; -- always 0 rows
SELECT * FROM users WHERE middle_name IS NULL; -- the rows we wanted

Notice that even NULL = NULL is not true: two unknown values are not known to be equal. So we never write = NULL; we write IS NULL. IS DISTINCT FROM is a comparison that treats NULL as an ordinary value, two NULLs are not distinct and a NULL is distinct from 5, which is exactly what we need when comparing an old and a new value to detect a change, for example in an UPDATE ... WHERE old.col IS DISTINCT FROM new.col.

3IN and NOT IN

IN is a chain of = comparisons joined by OR, and NOT IN is a chain of <> comparisons joined by AND. A NULL in the list adds an UNKNOWN to the chain.

SQL
SELECT 2 IN (1, 2, NULL); -- true: one match is enough
SELECT 3 IN (1, 2, NULL); -- null, not false
SELECT 3 NOT IN (1, 2, NULL); -- null: no row can ever pass
SELECT 3 NOT IN (1, 2); -- true
SELECT * FROM customers WHERE id NOT IN (SELECT customer_id FROM orders);
-- 0 rows as soon as a single orders.customer_id is NULL

For IN, the effect is mild: in a WHERE clause the UNKNOWN still drops the row, just as FALSE would. For NOT IN it is severe, because a single NULL coming back from a subquery turns every row's condition into UNKNOWN, and the query silently returns nothing. This is the one that surprises developers most, because the data they look at often has no visible NULLs. NOT EXISTS is the safe alternative.

4Counting and Grouping

Aggregates ignore NULLs, with one exception, COUNT(*), which counts rows regardless of their contents. GROUP BY, on the other hand, treats all NULLs as equal and puts them into one group.

SQL
-- payments(amount): 10, 20, NULL, NULL
SELECT COUNT(*) FROM payments; -- 4
SELECT COUNT(amount) FROM payments; -- 2
SELECT SUM(amount) FROM payments; -- 30
SELECT AVG(amount) FROM payments; -- 15, not 7.5: the NULLs are not counted as zero
SELECT SUM(amount) FROM payments WHERE false; -- null, not 0, on an empty set
-- orders(region): 'EU', 'EU', NULL, NULL, 'US'
SELECT region, COUNT(*) FROM orders GROUP BY region;
-- EU | 2
-- US | 1
-- null | 2 -- both NULLs form one group
How NULL behaves
OperationWith NULLSurprise level
a = NULL, a <> NULLUNKNOWN; use IS NULL / IS DISTINCT FROMMedium
x IN (..., NULL)UNKNOWN instead of FALSE when not foundLow
x NOT IN (..., NULL)Never TRUE: query returns no rowsHigh
COUNT(col) vs COUNT(*)COUNT(col) skips NULLs; COUNT(*) counts rowsMedium
SUM, AVGIgnore NULLs; SUM of no rows is NULLMedium
GROUP BY, DISTINCTAll NULLs form one groupLow
UNIQUE constraintMany NULLs allowed unless NULLS NOT DISTINCTHigh
JDBC getIntReturns 0 for NULLHigh

The AVG line is worth dwelling on. If NULL meant 'not paid yet' and the business wanted to count it as 0, the average is wrong by a factor of two, and COALESCE(amount, 0) is needed. SUM over no rows returns NULL, which in Java code often becomes a NullPointerException or a missing total, so reports usually wrap it in COALESCE(SUM(amount), 0). The GROUP BY behaviour is the opposite of = : for grouping, DISTINCT and UNION, SQL treats NULLs as not distinct from each other.

5Unique Constraints and NULLS NOT DISTINCT

A unique constraint promises no two rows have equal values. Since NULL is not equal to NULL, two NULLs do not violate it, so by default a unique column accepts any number of NULLs. That is usually right for an optional column like a tax id, but it surprises people with multi-column constraints, where one NULL column makes the whole key 'not equal' to everything.

SQL
CREATE TABLE prices (product_id int, region text, price numeric, UNIQUE (product_id, region));
INSERT INTO prices VALUES (1, NULL, 10);
INSERT INTO prices VALUES (1, NULL, 12); -- accepted: now two 'default' prices for product 1
-- PostgreSQL 15 and later
CREATE TABLE prices2 (product_id int, region text, price numeric,
UNIQUE NULLS NOT DISTINCT (product_id, region));
INSERT INTO prices2 VALUES (1, NULL, 10);
INSERT INTO prices2 VALUES (1, NULL, 12); -- ERROR: duplicate key value violates unique constraint

Here region NULL meant 'the default price', and the team expected one per product. UNIQUE NULLS NOT DISTINCT tells PostgreSQL to treat NULLs as equal for this constraint. On older versions, the usual workaround is a partial unique index, CREATE UNIQUE INDEX ON prices (product_id) WHERE region IS NULL, or a non-NULL sentinel value.

6NULL in Java: JDBC and Mapping

The last trap is on the Java side. ResultSet.getInt returns a primitive int, which cannot be null, so for a NULL column it returns 0. The only way to tell the difference afterwards is to call wasNull().

Java
ResultSet rs = stmt.executeQuery("SELECT discount FROM orders WHERE id = 12"); // discount is NULL
rs.next();
int d = rs.getInt("discount"); // 0
boolean missing = rs.wasNull(); // true
Integer d2 = rs.getObject("discount", Integer.class); // null
// In an entity, a primitive field hides the NULL as 0 as well
@Column(name = "discount") private Integer discount; // use the wrapper type for a nullable column

So a 'no discount recorded' becomes 'discount of 0', which is a different business fact and very hard to notice. Using getObject with a wrapper type, or wrapper fields in JPA entities and records for nullable columns, keeps the NULL visible as null in Java. Spring's JdbcTemplate row mappers have the same issue when they call getInt, so the rule applies there too.

7Follow-up questions

Which of these surprise developers most?

In my experience, three. NOT IN with a subquery that returns a NULL, because the query returns nothing and nobody suspects the NULL. Unique constraints accepting duplicate rows when one key column is NULL, because people expect the constraint to protect the business rule. And getInt returning 0, because the wrong value looks perfectly plausible. All three are silent: no error, just wrong data.

How does ORDER BY treat NULLs in PostgreSQL?

PostgreSQL treats NULL as larger than any value, so NULLs come last in ascending order and first in descending order. We can control it with NULLS FIRST or NULLS LAST. This matters for pagination and top-N queries: ORDER BY last_login DESC puts accounts that never logged in at the top, which is rarely what the page wants. An index used for such a query must match the NULLS ordering to be used for the sort.

Is it better to avoid NULL completely?

No, but it should be a decision. A column should be NOT NULL unless 'unknown' or 'not applicable' is a real state, and then the meaning of NULL should be documented. Replacing NULL with sentinel values like 0 or an empty string just moves the problem, since code then has to know the sentinel. Fewer nullable columns, each with a clear meaning, is the practical goal.

8Conclusion

In this answer, we saw that NULL means unknown and that comparisons with it give UNKNOWN, so we use IS NULL and IS DISTINCT FROM; that IN can return UNKNOWN and NOT IN with any NULL returns no rows; that COUNT(col), SUM and AVG skip NULLs while COUNT(*) counts rows; that GROUP BY puts NULLs in one group; that unique constraints allow many NULLs unless declared NULLS NOT DISTINCT in PostgreSQL 15 and later; and that JDBC getInt turns NULL into 0 unless we check wasNull or use getObject.

What to say in the interviewAbout 100 seconds aloud

Open with

The key idea is that NULL means unknown, so SQL uses three-valued logic. Any comparison with NULL, equals or not equals, gives unknown, even NULL = NULL. So I test with IS NULL, and when I compare two values that may be NULL, for example to detect a change, I use IS DISTINCT FROM.

Then, if they want more

IN with a NULL in the list returns unknown instead of false when the value is not found, which is usually harmless in WHERE. NOT IN is the dangerous one: one NULL from the subquery makes the condition unknown for every row, so the query returns nothing. I use NOT EXISTS instead.

For aggregates, COUNT of a column skips NULLs while COUNT star counts rows, SUM and AVG ignore NULLs, so an average is over known values only, and SUM over no rows is NULL, not zero. GROUP BY does the opposite of equality and puts all NULLs in one group.

Unique constraints allow many NULLs by default, which bites with composite keys, like two default prices for the same product with region NULL. PostgreSQL 15 added UNIQUE NULLS NOT DISTINCT for that; before, I would use a partial unique index.

And on the Java side, ResultSet getInt returns 0 for NULL, so I use getObject with Integer, or check wasNull, and wrapper types in entities. The ones that surprise people most are NOT IN, the unique constraint and the silent zero from JDBC.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 15
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Explain how NULL behaves in =, <>, IN, NOT IN, COUNT(col), COUNT(*), GROUP BY and unique...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/2258cbfbea/