Sub topic 2
Picking data types for books, authors, and dates
This chapter assumes you can write basic SELECT, INSERT, UPDATE, and DELETE statements. It also assumes you have a PostgreSQL 12 or newer instance and a client such as psql. Constraints and keys get their own chapters. Here the focus is on what each column stores and why.
Why the type is your first constraint
A column's data type decides which values PostgreSQL accepts, how much space they use, how they sort and compare, and which operators work on them. A wrong type rarely fails loudly. It usually works until you hit an edge case such as a leading zero, a time zone shift, or a value that no longer fits.
For the book tracker, the questions to ask of each column are:
- What kind of value is it: text, a count, a calendar date, or an instant in time?
- Will I do arithmetic on it, or only compare and display it?
- What is the smallest type that is still safe for the largest realistic value?
placeholderUse the diagram below as a decision guide for the choices in this chapter.
Text: text, varchar, and char
PostgreSQL has three character types, and they differ less than you might expect.
| Type | Behavior | Use in this schema |
|---|---|---|
| `text` | Variable length, no limit | Titles, author names |
| `varchar(n)` | Variable length, rejects values longer than `n` | Rarely needed |
| `char(n)` | Fixed length, pads shorter values with spaces | ISBN-13, which is always 13 characters |
In PostgreSQL, text and varchar(n) are stored the same way and perform the same. A length limit buys you validation, not speed. For titles and names, a limit like varchar(100) mostly causes trouble later, because real titles are long and names vary. Use text, and add a CHECK on length if you have a real business rule.
char(n) is the type to be careful with. It pads values to n characters, and trailing spaces are ignored in comparisons. You can see the padding directly:
SELECT octet_length('abc'::char(5)) AS stored_bytes,
octet_length('abc'::text) AS text_bytes,
'abc'::char(5) = 'abc'::char(5) AS padded_equal;The first column returns 5 and the second returns 3. The ISBN-13 column uses char(13) because the length is fixed by the standard. Values with the wrong length are rejected on insert, and anything shorter would be padded rather than rejected. That is why the schema pairs the type with a CHECK on the pattern. If you prefer to avoid padding altogether, text with a CHECK (isbn13 ~ '^[0-9]{13}$') behaves the same and has no surprises.
Never store an ISBN as a number
An ISBN looks numeric, but it is an identifier. You never add two ISBNs together, and the digits carry meaning. Two problems appear if you use an integer type:
- Leading zeros disappear. Many ISBN-10 values start with 0.
- An ISBN-10 can end in the letter X as its check digit.
SELECT '0306406152'::bigint AS stored_as_number,
'0306406152'::text AS stored_as_text;The first column returns 306406152, which is a different identifier. Even for ISBN-13, which has no letters, a numeric type has no benefit. The rule of thumb: if you would never do arithmetic on it, it is not a number.
Numbers: choosing the smallest safe integer
PostgreSQL integer types differ by range.
| Type | Bytes | Range |
|---|---|---|
| `smallint` | 2 | -32,768 to 32,767 |
| `integer` | 4 | about ±2.1 billion |
| `bigint` | 8 | about ±9.2 × 10^18 |
The schema uses:
published_year smallint, because years stay far below 32,767.page_count integer, because a page count fits easily andsmallintwould leave little margin for omnibus editions or reference works.bigintfor identity keys, covered in the next chapter.rating smallint, because a 1 to 5 scale needs almost nothing.
Out-of-range values fail instead of wrapping around:
SELECT 40000::smallint;
-- ERROR: smallint out of rangeThis is a good property. The error shows up at insert time and not as silently corrupted data. Saving two bytes per row will not matter in a personal reading log, so choose the type that describes the data, not the one that saves space. Use numeric only when you need exact decimal values such as prices. Do not use real or double precision for those, because they are binary floating-point types and cannot represent many decimal fractions exactly.
Dates and times
PostgreSQL separates calendar days from instants in time.
| Type | Stores | Example use |
|---|---|---|
| `date` | A calendar day, no time | `started_on`, `finished_on` |
| `timestamp` | Date and time with no time zone | Rarely the right choice |
| `timestamptz` | An exact instant, shown in the session time zone | `created_at` audit columns |
You started a book on a day, not at a moment, so date fits. It also avoids a classic bug. If you stored finished_on as a timestamp, a book finished at 11 pm in one time zone could land on the next day in another, and a query that groups by day would put it in the wrong bucket.
Despite its name, timestamptz does not store a time zone. It stores a UTC instant and converts to the session's TimeZone setting for display. Use it whenever the question is "when exactly did this happen", such as a row's creation time. Plain timestamp has no such anchor, so the same value means different instants for different readers.
date values support useful arithmetic:
SELECT date '2024-03-01' - date '2024-02-01' AS days_between,
date '2024-03-01' + 14 AS two_weeks_later,
date '2024-01-31' + interval '1 month' AS month_later;Subtracting two dates gives an integer number of days (29, because 2024 is a leap year). Adding an integer to a date gives a date. Adding an interval gives a timestamp, and PostgreSQL clamps month ends, so January 31 plus one month is February 29.
Year only, or a full date?
Books often have only a known publication year, so published_year smallint is more honest than a date of January 1. A fake date implies precision you do not have. The trade-off is that you lose date arithmetic on the column. For publication data that is acceptable. If you later need partial dates, add a separate column rather than overloading one.
Names and the enum preview
Author names are stored in a single text column, name. Splitting into first and last name sounds tidy, but it breaks for mononyms, names with multiple family parts, and different naming orders. A single field plus a sort key, if you ever need one, is safer.
For reading status, the schema uses an enum type created with CREATE TYPE. An enum is a named, ordered list of allowed labels, so values outside the list are rejected. A later chapter builds it in full.
The schema so far
Putting the choices together gives the two core tables:
CREATE TABLE authors (
author_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE books (
book_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
isbn13 char(13) UNIQUE CHECK (isbn13 ~ '^[0-9]{13}$'),
published_year smallint CHECK (published_year BETWEEN 1400 AND 2100),
page_count integer CHECK (page_count > 0)
);Check what you created with psql's \d books, or query the catalog:
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = 'books'
ORDER BY ordinal_position;Common mistakes
- Using
varchar(255)out of habit. The limit comes from older databases. In PostgreSQL it has no performance benefit and only adds a way to fail. - Choosing
timestampfor a calendar day. You will end up writing::datecasts everywhere. - Storing identifiers as integers. Leading zeros and check digits will be lost or rejected.
- Using
floatfor money or exact decimals. Usenumeric.
Exercise
A teammate proposes storing finished_on as timestamp and isbn13 as bigint. Give one problem with each choice and name the type you would use instead.
Show answer
A timestamp for finished_on records a time of day you do not have, and a late-evening finish can fall on a different day when read in another time zone, which skews per-day or per-year grouping. Use date. A bigint ISBN is wrong because an identifier is not a number: it invites arithmetic nobody needs, and the equivalent ISBN-10 values would lose leading zeros and cannot hold the check digit X. Use char(13) with a pattern CHECK, or text with the same CHECK.
Exercise
What does SELECT 40000::smallint; do, and why is that behavior useful?
Show answer
It fails with "smallint out of range" because 40000 is above 32,767. Failing at insert time stops bad data from being saved silently, so the problem is caught immediately and not discovered later in the results.