Brightlane's validation system counts characters in middle-name records. Some customers have no middle name on record, so the value is missing for those records.
Write a query to return the character count of the string 'Alexandra' and the character count of a missing value (a SQL NULL) in a single row.
Output:
- A single row with columns
name_length(the count for'Alexandra') andnull_length(the count for the missing value, which will itself be missing).
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
LENGTH('Alexandra') AS name_length,
LENGTH(NULL) AS null_length The shape
LENGTH(NULL) returns NULL, not 0. The query produces one row with two columns: name_length is the integer 9 for the nine characters in 'Alexandra', and null_length is NULL because the input is itself NULL. The result mirrors the universal rule for scalar functions in PostgreSQL: NULL in, NULL out.
Clause by clause
SELECT LENGTH('Alexandra') AS name_length, LENGTH(NULL) AS null_lengthcallsLENGTHtwice in the sameSELECTlist, once on a real string and once on NULL. The first call counts characters and returns9. The second call has no string to measure, so it returns NULL: there is no meaningful character count for a value that is absent. The two results are returned side by side in a single row.- There is no
FROMbecause both inputs are written into theSELECTlist directly. The function takes one input per call and returns one output per call, regardless of whether the input is a literal string or a literal NULL.
Why LENGTH(NULL) is not 0
NULL means the value is absent, not that the value is the empty string. LENGTH('') returns 0 because the empty string is a real value with zero characters; LENGTH(NULL) returns NULL because there is no string to count at all. The two are different inputs and the function correctly distinguishes them. Confusing the empty string with NULL is the root of an entire class of downstream bugs, and the difference between 0 and NULL in this column is the signal that catches it.
The trap
Every scalar string function in PostgreSQL follows this same rule. UPPER(NULL) is NULL. LOWER(NULL) is NULL. TRIM(NULL) is NULL. SUBSTRING(NULL, 1, 5) is NULL. The NULL propagates through whatever expression it lands in, including arithmetic, comparisons, and further string functions. A downstream aggregation that does not account for this will silently drop the missing rows or, worse, fold a NULL into a column where a 0 was expected and skew the report. When a column can be missing and the downstream consumer needs a definite value, the conversion has to be explicit, not assumed from the function's behavior.
You practiced LENGTH(...) returning missing for a missing input — the universal rule for scalar functions: NULL in, NULL out, propagating through every downstream operation.