Part 03 / Stage 1
Types, NULL and functions
Goal: Work with real values correctly — pick the right type for money and time, truly understand NULL, and use the built-in functions for text, numbers and dates that every report leans on. Time: ~1.5 hours
What you will learn
- The core types: integers,
numeric, text, booleans, dates and times,interval,uuid - Choosing well: why money is
numericand event times aretimestamptz - NULL and three-valued logic:
IS NULL, and why= NULLnever matches - The NULL-safe toolkit:
COALESCE,NULLIF,IS DISTINCT FROM - String functions:
lower,trim,substring,replace,||and friends - Numeric functions:
round,ceil,floor,abs,mod - Dates and times:
now(),date_trunc,extract,age, interval arithmetic - Casting with
CASTand:: CASEexpressions for bucketing values
Topics in this part
Practice
SQL workbench — write and run queries here
Press Run and PostgreSQL loads right in your browser (a one-time download of about 16 MB; after that it works offline). It comes seeded with shopdb, and statements share one session per page — like a psql window. Reset data rebuilds shopdb. Your queries never leave this page. Lessons were captured on PostgreSQL 17; the in-browser server is PostgreSQL 19 (via PGlite), so the rare output detail can differ.
Try each one yourself first, in psql against shopdb. Then check the solution.
Exercise 1: Prove the money rule
What to do: In one SELECT, show 0.1 + 0.2 as a float8 (cast the sum to text so you see every digit), whether it equals 0.3 as float8, and whether it equals 0.3 as numeric.
Sample output:
float_sum | float_equal | numeric_equal
---------------------+-------------+---------------
0.30000000000000004 | f | t
(1 row)
💡 Hint: (0.1::float8 + 0.2::float8)::text, then the two comparisons.
Show the solution to Exercise 1
-- Exercise 1: Prove the money rule
-- Binary floats cannot represent 0.1 or 0.2 exactly; numeric can.
SELECT (0.1::float8 + 0.2::float8)::text AS float_sum,
0.1::float8 + 0.2::float8 = 0.3 AS float_equal,
0.1::numeric + 0.2::numeric = 0.3 AS numeric_equal;
Exercise 2: The NULL hunt
What to do: First count the customers matched by WHERE city = NULL (predict it before you run it!). Then write the test that actually finds the customer with no city, showing name and email.
Sample output:
equals_null_matches
---------------------
0
(1 row)
first_name | email
------------+------------------
Sara | [email protected]
(1 row)
💡 Hint: = NULL is unknown for every row; IS NULL is the real test.
Show the solution to Exercise 2
-- Exercise 2: The NULL hunt
-- = NULL is unknown for every row, so it matches nothing.
SELECT count(*) AS equals_null_matches FROM customers WHERE city = NULL;
-- IS NULL is the real test:
SELECT first_name, email FROM customers WHERE city IS NULL;
Exercise 3: Divide without dying
Scenario: For the Kitchen category you want each product's price per unit in stock — but Coffee Maker's stock is 0, and dividing by zero kills the whole query. What to do: Show name, price, stock and the per-unit figure, with the zero handled so the query survives and the Coffee Maker's figure is honestly "unknown".
Sample output:
name | price | stock | price_per_unit_in_stock
--------------+--------+-------+-------------------------
Chef Knife | 80.00 | 30 | 2.67
Coffee Maker | 120.00 | 0 |
(2 rows)
💡 Hint: price / NULLIF(stock, 0), rounded to 2.
Show the solution to Exercise 3
-- Exercise 3: Divide without dying
-- Coffee Maker has stock 0. Plain division would error the whole query;
-- NULLIF(stock, 0) turns the 0 into NULL so the result is honestly unknown.
SELECT name, price, stock,
round(price / NULLIF(stock, 0), 2) AS price_per_unit_in_stock
FROM products
WHERE category_id = 6
ORDER BY name;
Exercise 4: Email domains
What to do: List every distinct email domain our customers use.
Sample output:
domain
-------------
example.com
(1 row)
💡 Hint: split_part(email, '@', 2) with DISTINCT.
Show the solution to Exercise 4
-- Exercise 4: Email domains
SELECT DISTINCT split_part(email, '@', 2) AS domain
FROM customers
ORDER BY domain;
Exercise 5: Calendar arithmetic
What to do: Two queries. First: what is Jan 31 2025 plus one month, and Dec 31 2025 plus two months? Predict both before running. Second: for orders 1 and 9, show the order date with its year and month extracted.
Sample output:
clamped | into_next_year
---------------------+---------------------
2025-02-28 00:00:00 | 2026-02-28 00:00:00
(1 row)
order_id | order_date | year | month
----------+------------+------+-------
1 | 2025-01-10 | 2025 | 1
9 | 2025-04-20 | 2025 | 4
(2 rows)
💡 Hint: + INTERVAL '1 month' clamps to real month ends; extract(year FROM ...).
Show the solution to Exercise 5
-- Exercise 5: Calendar arithmetic
SELECT DATE '2025-01-31' + INTERVAL '1 month' AS clamped,
DATE '2025-12-31' + INTERVAL '2 months' AS into_next_year;
SELECT order_id, order_date,
extract(year FROM order_date) AS year,
extract(month FROM order_date) AS month
FROM orders WHERE order_id IN (1, 9);
Exercise 6: Stock health board
What to do: Label every product out of stock (0), low (under 20) or healthy, sorted so the most urgent appear first.
Sample output:
name | stock | stock_status
--------------------+-------+--------------
Coffee Maker | 0 | out of stock
Laptop Air 13 | 8 | low
Desk Lamp | 12 | low
Laptop Pro 14 | 15 | low
Phone X | 25 | healthy
Chef Knife | 30 | healthy
Phone Lite | 40 | healthy
Postgres Deep Dive | 60 | healthy
SQL for Beginners | 100 | healthy
USB-C Cable | 200 | healthy
(10 rows)
💡 Hint: CASE checks top-down — put stock = 0 before stock < 20.
Show the solution to Exercise 6
-- Exercise 6: Stock health board
SELECT name, stock,
CASE
WHEN stock = 0 THEN 'out of stock'
WHEN stock < 20 THEN 'low'
ELSE 'healthy'
END AS stock_status
FROM products
ORDER BY stock, name;
Exercise 7: The customer clean-up report
Scenario: The marketing team wants one tidy customer sheet, "as of 1 June 2025".
What to do: For every customer show: full name in title case, lowercase email, city with Unknown for missing, signup month (as a date), and how many days they had been signed up by 2025-06-01. Oldest signup first.
Sample output:
full_name | email | city | signup_month | days_signed_up_by_june
--------------+--------------------+---------+--------------+------------------------
Asha Verma | [email protected] | Pune | 2025-01-01 | 147
Ravi Kumar | [email protected] | Delhi | 2025-01-01 | 132
Meera Iyer | [email protected] | Chennai | 2025-02-01 | 110
John Smith | [email protected] | London | 2025-02-01 | 93
Sara Khan | [email protected] | Unknown | 2025-03-01 | 78
Vikram Singh | [email protected] | Pune | 2025-04-01 | 60
(6 rows)
💡 Hint: initcap, lower, COALESCE, date_trunc(...)::date, and date subtraction gives whole days.
Show the solution to Exercise 7
-- Exercise 7: The customer clean-up report (the part's mini-project)
SELECT initcap(first_name || ' ' || last_name) AS full_name,
lower(email) AS email,
COALESCE(city, 'Unknown') AS city,
date_trunc('month', signup_date)::date AS signup_month,
DATE '2025-06-01' - signup_date AS days_signed_up_by_june
FROM customers
ORDER BY signup_date;
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
Prices in real / double precision |
Silent rounding errors in money | numeric(p, s) — always |
timestamp for event times |
Ambiguous moments across time zones | timestamptz |
= NULL in a filter |
Matches nothing, silently | IS NULL |
Treating NULL as 0 or '' |
Rows vanish from both sides of a comparison | COALESCE a fallback, or IS DISTINCT FROM |
varchar(255) everywhere "to be safe" |
Arbitrary limits that error at the worst moment | Postgres default is text |
| Dividing integers for a percentage | 0 — truncation | 100.0 * part / NULLIF(whole, 0) |
Quick recap
- Types are enforced promises:
integer/bigintfor counts and ids,numericfor money,textfor text,date/timestamptzfor time,intervalfor durations. - NULL is unknown: it infects expressions, fails every
=, and needsIS NULL. - The NULL-safe kit has three tools:
COALESCEsupplies a fallback,NULLIFguards a value, andIS DISTINCT FROMcompares honestly. - For strings you have
||,lower,trim,substring,split_partandinitcap; for numbers,round,ceil,floorandmod. - For time,
date_truncgroups moments,extractpulls out fields, and interval arithmetic clamps months to real calendar dates. ::casts and validates in one move;CASEsorts values into buckets, and the first matching branch wins.
Checklist
Before Part 4, make sure you can:
- Say why money columns are
numericand event-time columns aretimestamptz. - Explain NULL to a friend in one sentence, without the words zero or empty.
- Replace a NULL with a fallback, and compare two nullable columns honestly.
- Build a full name, a lowercase email and an email domain with string functions.
- Compute a safe percentage with
100.0 * part / NULLIF(whole, 0). - Bucket values with CASE and predict what an unmatched row gets.
Read more: the official data types chapter and functions reference.