PostgreSQL NULL Values
Overview
NULL represents "unknown" or "no value" - it is not equal to an empty string or zero. Handling NULL values correctly in PostgreSQL is crucial for data integrity and query accuracy.
NULL Characteristics
Basic Properties
- NULL is not equal to any value, including NULL itself
- Any operation with NULL results in NULL
- NULL represents "unknown" in boolean operations
Detecting NULL Values
IS NULL and IS NOT NULL
NULL in Operations
Arithmetic Operations
String Concatenation
Boolean Operations
Functions for Handling NULL
COALESCE Function
Returns the first non-NULL value:
NULLIF Function
Returns NULL if two values are equal:
NVL Function (via COALESCE)
NULL and Aggregate Functions
Aggregates Ignore NULL
Including NULL in Aggregates
NULL and Sorting
Default Sort Behavior
Controlling NULL Sort Position
NULL and DISTINCT
NULL and Indexes
B-tree Index
Partial Index Optimization
NULL and Constraints
NOT NULL Constraint
UNIQUE Constraint and NULL
CHECK Constraint and NULL
Practical Examples
Handling Optional Fields
Conditional Replacement
Safe Numeric Calculations
Best Practices
- Use IS NULL: Never use
= NULLfor comparisons - Use COALESCE: Provide default values to prevent NULL propagation
- Watch aggregates: Understand how aggregate functions handle NULL
- Document: Record which columns allow NULL and their business meaning
- Default values: Consider using DEFAULT instead of allowing NULL