Sub topic 5
Data types and the meaning of NULL
This chapter assumes you can read a CREATE TABLE statement, know what a row and a column are, and have seen SELECT ... WHERE. It covers two linked ideas. Every column has a data type that limits what it can hold. Any column may also hold NULL, a marker that means "no value", which behaves differently from every ordinary value.
Why columns have types
A column's data type tells the database three things: which values are valid, how to store them, and which operations make sense on them. A type is the first integrity check a column gets. Inserting 'banana' into an INTEGER column fails, and adding two dates is rejected or means something specific, instead of silently producing nonsense.
Types also decide how comparison and sorting work. The text values '10' and '9' sort as '10' before '9', because text compares character by character. The integers 10 and 9 sort numerically. Choosing the wrong type gives wrong answers even when no error appears.
The common type families
Names and limits differ between PostgreSQL, MySQL, SQLite, and others, but the families are stable.
| Family | Typical types | Use for | Watch out for |
|---|---|---|---|
| Whole numbers | `SMALLINT`, `INTEGER`, `BIGINT` | Counts, identifiers, quantities | Overflow when the range is too small |
| Exact decimals | `DECIMAL(p, s)`, `NUMERIC(p, s)` | Money, anything that must add up exactly | Slower than floats. `p` is total digits and `s` is digits after the point |
| Approximate numbers | `REAL`, `DOUBLE PRECISION`, `FLOAT` | Measurements, scientific values | Binary rounding. `0.1 + 0.2` is not exactly `0.3` |
| Text | `CHAR(n)`, `VARCHAR(n)`, `TEXT` | Names, emails, descriptions | Length limits, trailing spaces, collation (sorting rules) |
| Dates and times | `DATE`, `TIME`, `TIMESTAMP`, `TIMESTAMP WITH TIME ZONE` | Events and schedules | Time zones, and string dates that sort wrongly |
| Boolean | `BOOLEAN` | Flags | MySQL stores it as a small integer. Some systems allow `NULL` as a third state |
The spine's orders table uses DECIMAL(10, 2) for total_amount. That allows up to 10 digits with 2 after the decimal point, so the largest value is 99,999,999.99. Money belongs in an exact type, because summing millions of approximate values accumulates rounding error that an exact decimal never does.
Store dates in a date type, not text. A DATE column rejects '2026-02-30', supports date arithmetic, and sorts chronologically. A text column accepts anything.
Dialect differences
SQLite is the main exception to strict typing. It uses type affinity: a column declared INTEGER prefers integers but will usually accept text that cannot be converted. A DECIMAL column in SQLite does not store exact decimals. If your target is SQLite, validate in constraints or the application. For PostgreSQL, strict typing is the default and an invalid value is an error.
What NULL means
NULL is not zero, not an empty string, and not the word "null". It marks the absence of a known value. A NULL in a column can mean several different things:
- The value exists but is not known yet, such as a customer's birth date that was never collected.
- The value does not apply, such as a
paid_ondate for an invoice that has not been paid. - The value was never supplied, so the column took its default of
NULL.
SQL does not distinguish these cases. If the difference matters, model it with another column, such as a status column.
An empty string '' is a real text value of length zero. 0 is a real number. Both are known values and both compare normally. Treating NULL, '', and 0 as interchangeable is a common source of bugs.
Setting up an example
The following statements run on PostgreSQL, MySQL, and SQLite. The table is self-contained and does not depend on the earlier chapters' tables.
CREATE TABLE invoices (
invoice_id INTEGER PRIMARY KEY,
customer_name VARCHAR(100) NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
issued_on DATE NOT NULL,
paid_on DATE,
discount DECIMAL(5, 2)
);
INSERT INTO invoices (invoice_id, customer_name, amount, issued_on, paid_on, discount)
VALUES
(1, 'Ada', 100.00, '2026-01-05', '2026-01-10', 10.00),
(2, 'Grace', 200.00, '2026-01-06', NULL, NULL),
(3, 'Linus', 50.00, '2026-01-07', NULL, 0.00);NOT NULL on a column forbids the marker. Columns declared without it, here paid_on and discount, accept it. The NOT NULL constraint is covered fully in the constraints chapter. Here it only shows that nullability is a per-column decision.
Invoice 2 has an unknown discount. Invoice 3 has a known discount of zero. Those are different facts, and the database keeps them apart.
Three-valued logic
Comparing anything to NULL does not give true or false. It gives UNKNOWN. If you do not know a value, you cannot say whether it equals 10. SQL therefore has three truth values, and WHERE keeps a row only when its condition is TRUE. Both FALSE and UNKNOWN discard the row.
The logical operators follow the same rule. UNKNOWN AND FALSE is FALSE, because one false operand settles an AND. UNKNOWN OR TRUE is TRUE, for the same reason. In every other combination with UNKNOWN, the result is UNKNOWN. NOT UNKNOWN is UNKNOWN.
Testing for NULL
Because = NULL yields UNKNOWN for every row, this query returns nothing:
SELECT invoice_id FROM invoices WHERE paid_on = NULL;Use the dedicated predicates instead:
SELECT invoice_id, customer_name
FROM invoices
WHERE paid_on IS NULL;
SELECT invoice_id, customer_name
FROM invoices
WHERE paid_on IS NOT NULL;The first query returns invoices 2 and 3. The second returns invoice 1. Together they cover every row, which is not true of = and <>.
The inequality trap
A condition like discount <> 10 looks like it should return every invoice without a 10.00 discount. It returns only invoice 3:
SELECT invoice_id, discount
FROM invoices
WHERE discount <> 10;Invoice 1 fails because its discount is 10. Invoice 2 has NULL <> 10, which is UNKNOWN, so it is discarded as well. If you want invoice 2 included, say so:
SELECT invoice_id, discount
FROM invoices
WHERE discount <> 10 OR discount IS NULL;Many dialects also offer a null-safe comparison, such as IS DISTINCT FROM in PostgreSQL and SQLite, or <=> in MySQL. These treat two NULLs as equal and a NULL and a value as different.
Replacing NULL in results
COALESCE returns its first argument that is not NULL. It is standard SQL and portable.
SELECT invoice_id,
amount - COALESCE(discount, 0) AS amount_due
FROM invoices
ORDER BY invoice_id;Without COALESCE, amount - discount would be NULL for invoice 2, because any arithmetic with NULL produces NULL. String concatenation behaves the same way in most systems. Use COALESCE where the substitution is a correct reading of the data. A missing discount really is zero here, but a missing birth date is not "1900-01-01".
NULL in aggregates and sorting
Aggregate functions skip NULL inputs, except COUNT(*), which counts rows.
SELECT COUNT(*) AS all_rows,
COUNT(discount) AS rows_with_discount,
AVG(discount) AS avg_known,
AVG(COALESCE(discount, 0)) AS avg_as_zero
FROM invoices;The results are 3, 2, 5.00, and about 3.33. AVG(discount) divides 10.00 by two known values. The second average divides 10.00 by three rows. Neither is wrong, but they answer different questions, so choose deliberately.
Other places where NULL matters:
ORDER BYplacesNULLs first or last depending on the database. PostgreSQL puts them last in ascending order, while MySQL and SQLite put them first. PostgreSQL and SQLite acceptNULLS FIRSTorNULLS LASTto make this explicit.GROUP BYputs allNULLs in one group, even though they are not equal to each other under=.UNIQUEcolumns usually allow severalNULLs, since no two unknowns are known to be equal. SQL Server is a notable exception.NOT INwith a list or subquery containingNULLreturns no rows.1 NOT IN (2, NULL)isUNKNOWN, because the value might equal the unknown element. UseNOT EXISTS, or filter theNULLs out of the subquery.
Deciding whether a column should allow NULL
A practical rule: make a column NOT NULL unless "no value" is a legitimate state in your domain. Every nullable column forces each query that reads it to handle three-valued logic. Primary keys can never be NULL, and a foreign key is nullable only when the relationship is optional. Use a NULL for paid_on because "not paid yet" is real. Do not use a NULL for a customer's name if every customer must have one, because the database can enforce that for you.
Avoid sentinel values like -1, 0, or 'N/A' as substitutes. They pass type checks, are counted by aggregates, and look like real data.
Exercise
Using the invoices table above, a colleague writes SELECT COUNT(*) FROM invoices WHERE paid_on <> '2026-01-10'; and expects the result 2, for the two unpaid invoices. What does the query return, why, and how would you change it to count the unpaid invoices?
Show answer
It returns 0. Invoice 1 has paidon equal to '2026-01-10', so the comparison is false. Invoices 2 and 3 have a NULL paidon, so the comparison is UNKNOWN, and WHERE discards rows that are not TRUE. To count the unpaid invoices, use SELECT COUNT(*) FROM invoices WHERE paid_on IS NULL; which returns 2.