Skip to content
Visual explainer 3h to learn 4 steps

NULLs, expressions & built-in functions

Handle NULLs correctly and transform strings, numbers and dates in queries.

By Invicly Tech, , in SQL & PostgreSQL. About 9 minutes to read.

Topic 3 of 30

In short

NULL means "unknown or missing", not zero or empty text. Any comparison with NULL is unknown, so you need IS NULL and COALESCE. CASE and built-in functions transform strings, numbers and dates inside queries.

Explained simply

NULL is a placeholder for "we do not know". A customer with no phone number on file has NULL in the phone column. It is not zero, not an empty string, and not the word null. It is the absence of a value.

Because NULL means unknown, any maths or comparison with it is also unknown. If you do not know someone's age, you cannot say whether they are older than 30. So age > 30 is neither true nor false for them, and WHERE quietly drops that row.

Functions are small tools you can use inside a query, like lower() to make text lower case or round() to tidy numbers. They work on each row and give back a new value. The original data in the table never changes.

CASE is the SQL version of if/else. It lets you turn raw values into labels, like turning an order total into "small", "medium" or "large". Combined with functions, it means you can shape data exactly how a report needs it.

Press Play on a diagram to walk through it one step at a time.

CompareHandling NULL: wrong vs right
Looks right, is wrong
  • WHERE phone = NULL matches nothing
  • price + NULL gives NULL
  • NOT IN (subquery with NULL) returns nothing
  • COUNT(phone) skips NULLs silently
Correct approach
  • WHERE phone IS NULL
  • price + COALESCE(fee, 0)
  • Use NOT EXISTS instead
  • COUNT(*) to count all rows
MapWhat happens when a NULL meets...
NULL value
  • Comparison (=, <, <>)
    • Result is unknown
    • Row dropped by WHERE
  • Arithmetic or ||
    • Result is NULL
  • Aggregate (SUM, AVG, COUNT(col))
    • NULL is skipped
    • COUNT(*) still counts the row
  • COALESCE / IS NULL
    • Handled safely
  • ORDER BY
    • Sorted last in ASC by default

In depth

Three-valued logic in practice

SQL conditions have three possible results: true, false and unknown. WHERE keeps only true. This creates some traps.

WHERE status <> 'cancelled' skips rows where status is NULL, because NULL <> 'cancelled' is unknown. If you want those rows too, write WHERE status IS DISTINCT FROM 'cancelled'. IS DISTINCT FROM treats NULL like a normal value, so two NULLs count as equal and NULL vs 'x' counts as different.

AND and OR follow common sense where they can. false AND unknown is false, because one false is enough. true OR unknown is true. Only when the answer truly depends on the missing value does the result stay unknown.

  • WHERE keeps only true rows
  • IS NULL / IS NOT NULL to test for missing
  • IS DISTINCT FROM: NULL-safe not-equal
  • false AND unknown = false; true OR unknown = true
CompareAND and OR with unknown
AND
  • true AND unknown = unknown
  • false AND unknown = false
  • unknown AND unknown = unknown
OR
  • true OR unknown = true
  • false OR unknown = unknown
  • unknown OR unknown = unknown

Aggregates and NULL

Aggregate functions skip NULLs. COUNT(*) counts rows, but COUNT(phone) counts only rows where phone is not NULL. AVG(rating) divides by the number of non-NULL ratings, not the number of rows. SUM over only NULLs returns NULL, not 0.

That is usually what you want, but be deliberate. If a missing rating should count as zero, write AVG(COALESCE(rating, 0)). If you want 0 instead of NULL for an empty sum, wrap it: COALESCE(SUM(amount), 0).

MapAggregates over ratings 4, NULL, 2
ratings: 4, NULL, 2
  • COUNT(*)
    • 3 (every row)
  • COUNT(rating)
    • 2 (NULL skipped)
  • AVG(rating)
    • 3 = (4 + 2) / 2
  • AVG(COALESCE(rating, 0))
    • 2 = (4 + 0 + 2) / 3

Text, number and date toolkit

Text: lower(), upper(), trim(), length(), left(s, n), replace(s, 'a', 'b'), and || to join strings. concat() also joins but treats NULL as empty, while || returns NULL if any part is NULL.

Numbers: round(x, 2), ceil(), floor(), abs(). Watch out for integer division: 7 / 2 is 3. Write 7 / 2.0 or cast with 7::numeric / 2 to get 3.5.

Dates: now() is the current timestamp, current_date is today. date_trunc('week', ts) rounds down to the start of the week. extract(year FROM ts) pulls out a part. age(ts) gives a readable interval, and to_char(ts, 'YYYY-MM-DD') formats it as text.

Writing CASE well

CASE checks its WHEN branches from top to bottom and returns the first match. Put the most specific conditions first. If no branch matches and there is no ELSE, the result is NULL, so always add an ELSE unless NULL is what you want.

CASE can go anywhere an expression can: in SELECT to make labels, in ORDER BY to sort in a custom order, and inside aggregates to count conditionally, as in SUM(CASE WHEN paid THEN amount ELSE 0 END). Postgres also offers COUNT(*) FILTER (WHERE paid), which is shorter for that last case.

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Handle NULL with IS NULL and COALESCE~45m
  2. 2
    Write CASE expressions~45m
  3. 3
    Use string and number functions~45m
  4. 4
    Work with dates and intervals~45m

Key points

  • NULL = NULL is not true; it is NULL (unknown).
  • COALESCE(a, b, c) returns the first non-NULL argument.
  • CASE WHEN ... THEN ... ELSE ... END is SQL's if/else.
  • Useful functions: lower(), length(), round(), now(), date_trunc().
  • Date arithmetic uses intervals: now() - interval '7 days'.

Key terms

Tap a card to flip it. 0/5 known

Examples

sql
SELECT
  name,
  COALESCE(phone, 'no phone') AS phone,
  upper(left(name, 1)) AS initial,
  CASE
    WHEN total >= 1000 THEN 'gold'
    WHEN total >= 100  THEN 'silver'
    ELSE 'bronze'
  END AS tier,
  date_trunc('month', created_at) AS signup_month
FROM customers
WHERE deleted_at IS NULL
  AND created_at > now() - interval '30 days';

A contact list that never shows blanks

Marketing wants one contact line per customer. Step 1: prefer mobile, fall back to landline, then to a fixed message, using COALESCE with three arguments. Step 2: build a display name with initcap and trim so messy input looks tidy. Step 3: label customers by how long ago they signed up with CASE, newest rule first.

sql
SELECT
  initcap(trim(first_name)) || ' ' || initcap(trim(last_name)) AS display_name,
  COALESCE(mobile, landline, 'no number') AS contact,
  CASE
    WHEN created_at > now() - interval '30 days' THEN 'new'
    WHEN created_at > now() - interval '1 year'  THEN 'regular'
    ELSE 'long-time'
  END AS segment
FROM customers;

Why the average rating looked too high

A product has 4 reviews: 5, 4, NULL, NULL (two people left no rating). AVG(rating) returns 4.5 because it ignores the NULLs and divides 9 by 2. COUNT(*) is 4 but COUNT(rating) is 2. If the business decides an empty rating means "no opinion", 4.5 is right. If it should count as zero, AVG(COALESCE(rating, 0)) gives 9 / 4 = 2.25. The query is not wrong either way; the rule just has to be chosen on purpose.

sql
SELECT COUNT(*)                  AS reviews,
       COUNT(rating)             AS rated,
       AVG(rating)               AS avg_of_rated,
       AVG(COALESCE(rating, 0))  AS avg_null_as_zero
FROM reviews
WHERE product_id = 42;

Quick reference

  • Test for missing values with IS NULL / IS NOT NULL, never = NULL
  • COALESCE(a, b, 'default') returns the first non-NULL value
  • NULLIF(x, 0) turns 0 into NULL: handy to avoid division by zero
  • a IS DISTINCT FROM b: not-equal that treats NULLs as comparable values
  • 7 / 2 = 3 (integer division); 7 / 2.0 = 3.5
  • date_trunc('month', ts), extract(dow FROM ts), now() - interval '7 days'
  • COUNT(*) FILTER (WHERE cond) counts only matching rows

Common mistakes

  • Writing = NULL or != NULL, which never matches any row.
  • Assuming AVG(col) counts NULL rows as zero; it ignores them.
  • Storing empty strings and NULLs for the same meaning.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A table has 10 rows; 3 have NULL in bonus. What does COUNT(bonus) return?

Question 2

2Which condition keeps rows where status is NULL as well as rows with other statuses, but not 'cancelled'?

Question 3

3What is the result of SELECT 'Hi ' || NULL;?

Question 4

4A CASE expression has no ELSE and no branch matches. What is returned?

Question 5

5How do you safely compute revenue / visits when visits can be 0?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    From employees(name, bonus), show each name and the bonus, showing 0 where bonus is missing.

  2. Exercise 2medium

    From orders(id, total, created_at), show for each month of this year the number of orders and how many were over 100.

  3. Exercise 3hard

    Sort tickets(id, priority) so 'urgent' comes first, then 'high', then 'normal', and tickets with no priority come last.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use NULL or an empty string for missing text?
Pick one meaning and stick to it. Most teams use NULL for "unknown" and reserve empty strings for "known to be empty", and add a CHECK constraint if they want to forbid one of them.
Why does NOT IN return no rows sometimes?
If the list or subquery contains a NULL, every NOT IN check becomes unknown, so nothing passes. Use NOT EXISTS, or filter NULLs out of the subquery.
What is the difference between now() and current_date?
now() is the current date and time with time zone. current_date is just today's date, with no time part.

Go deeper

ShareXLinkedInWhatsApp