Lesson 4 of 29Querying basics
Choosing Column Types
Pick integer, money, text, time, UUID and enum types that stay correct for years, and see how SQLite's loose typing differs from Postgres.
A column type is the cheapest decision you make when you create a table and the most expensive one to change later. Pick integer for an id and, years later, inserts start failing at 2,147,483,647 while the fix needs a table rewrite. Store prices as float and the finance team finds a total that is off by a cent. Store times without a time zone and every report is wrong for half your users. This lesson goes through the types you will actually choose at work, what each one stores underneath, and the traps that turn into incidents.
Why types matter more than they look
A type does four jobs at once. It rejects bad data (Postgres refuses 'next Tuesday' in a date column). It decides what operations mean: '10' < '9' is true for text and false for numbers. It sets storage and index size, which is memory and cache hits on a big table. And it is hard to change: changing a column's type on a large Postgres table usually rewrites every row while holding a lock that blocks reads and writes.
That last point is why seniors care. On day one, any type works because the table is empty. The type has to be right for the table you will have in three years, with a hundred million rows and a dozen services reading it.
Integers and identity columns
Postgres has three integer types:
| Type | Bytes | Largest value |
|---|---|---|
smallint | 2 | 32,767 |
integer | 4 | 2,147,483,647 (about 2.1 billion) |
bigint | 8 | about 9.2 × 10^18 |
Two billion sounds like a lot until you count events, log lines or order items. A table that takes 1,000 inserts a second fills an integer id in under 25 days. Teams have had long outages from exactly this: the sequence hits the ceiling, every insert fails, and widening the column means rewriting the table. Use bigint for every surrogate id. The extra 4 bytes per row is not worth arguing about.
Remember the foreign keys too. If orders.id is bigint, then order_items.order_id must be bigint as well. A classic half-fix widens the primary key and forgets the columns that point at it.
For auto-incrementing ids, modern Postgres uses an identity column:
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers (id),
status text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);You will still see serial and bigserial in older code and tutorials. They are legacy shorthand that creates a separate sequence and a default. Identity columns are the SQL standard, keep the sequence tied to the column, and GENERATED ALWAYS refuses a hand-written id unless you say OVERRIDING SYSTEM VALUE. That stops a script from inserting id = 5 and causing a duplicate-key error later when the sequence reaches 5. Use GENERATED BY DEFAULT only when you need to load rows with existing ids, such as during a data migration.
Ids also have gaps. A rolled-back insert still consumes a sequence value, so never use ids to count rows or to assume "order 1001 came right after order 1000".
Money: exact numbers only
Floating-point types (real, double precision, MySQL FLOAT) store binary fractions. Most decimal amounts, like 0.10, have no exact binary form, so tiny errors appear and add up. Run this:
Press Run (⌘ Enter) to see what happens.Ten payments of 10p do not add up to exactly one pound in floating point. The equality check fails, so a reconciliation job that compares totals flags a mismatch that does not exist, or worse, hides one that does.
You have two correct options:
numeric(p, s), an exact decimal.numeric(12, 2)holds up to 9,999,999,999.99. Arithmetic is exact, but slower than integers, which rarely matters.- Integer minor units (cents, pence), in a
bigint. Fast, exact, and the format most payment APIs use. The course dataset does this:products.price_centsandorder_items.unit_price_cents.
Either way, store the currency in its own column if you ever handle more than one, because not every currency has two decimal places. Avoid the Postgres money type: its formatting depends on a server locale setting, and it is awkward to work with from application code.
Text
In Postgres, use text. varchar(n) and text are stored the same way and perform the same. The only difference is the length limit, and a limit you might change is easier as a constraint:
ALTER TABLE customers
ADD CONSTRAINT name_length CHECK (char_length(name) BETWEEN 1 AND 200);Changing a CHECK is a quick metadata change plus a validation scan. Avoid char(n): it pads values with spaces, which causes strange comparison bugs.
Two text traps come up at work. First, MySQL's utf8 is not full UTF-8. It is an alias for utf8mb3, which stores at most 3 bytes per character and cannot hold emoji or some rarer scripts. Use utf8mb4, which is the default in MySQL 8. Second, case. 'Ada@Example.com' and 'ada@example.com' are different text, so a plain UNIQUE on email lets the same person sign up twice. In Postgres, either store emails lower-cased and enforce it with a check, or put the unique index on an expression, CREATE UNIQUE INDEX ON customers (lower(email)), and query with lower(email) = lower($1) so the index is used.
Dates and times
This is the area with the most real bugs. Postgres gives you:
timestamptz(timestamp with time zone). Despite the name, it does not store a time zone. It converts the input to a UTC instant and stores that, then converts back to the session'sTimeZonesetting when you read it. It is the right type for "when did this happen".timestamp(without time zone). A wall-clock reading with no zone.2025-06-01 09:00could be any of 24 different instants. Avoid it for events.datefor calendar days (a birthday, an invoice date), andintervalfor durations (interval '30 days').
SET TIME ZONE 'Europe/London';
SELECT timestamptz '2025-06-01 09:00+02'; -- 2025-06-01 08:00:00+01
SET TIME ZONE 'America/New_York';
SELECT timestamptz '2025-06-01 09:00+02'; -- 2025-06-01 03:00:00-04Same stored instant, two displays. Your API should send ISO-8601 strings with an offset (or Z for UTC) and let the client format them for the user.
The client sends a time with an offset. Without one, Postgres assumes the session's TimeZone, which is a common source of silent shifts.
Two details seniors know. now() returns the start of the current transaction, so every row inserted in one transaction gets the same timestamp; clock_timestamp() returns the actual time and changes during a statement. And for future local events, like "the meeting is at 09:00 in Paris every Monday", a UTC instant is not enough, because daylight-saving rules can change before the date arrives. Store the local time and the zone name (Europe/Paris) and compute the instant when you need it.
SQLite has no date or time type at all. You store ISO-8601 text ('2025-06-01 09:00') or a Unix epoch integer, and use functions to do the maths. ISO text sorts correctly as long as every value has the same format with zero padding:
Press Run (⌘ Enter) to see what happens.'2025-6-5' compares as greater than '2025-06-20' because text is compared character by character, and '6' beats '0'. One bad import with unpadded dates breaks every range query. In Postgres the type system would have rejected or normalised the value.
Booleans, UUIDs, enums and arrays
boolean exists in Postgres and accepts true/false. MySQL's BOOLEAN is an alias for TINYINT(1), and SQLite stores 0 and 1. Prefer NOT NULL booleans: a nullable boolean has three states, and someone will forget the third.
uuid is a 16-byte identifier you can generate anywhere, including on the client, without asking the database. That helps with merging data from several systems and with not exposing how many orders you have. The version matters:
- UUIDv4 is random. New keys land at random places in the primary-key index.
- UUIDv7 starts with a millisecond timestamp, so new keys sort after old ones. Postgres 18 has a built-in
uuidv7()function.
A primary-key index is kept sorted. Here are the first 4 hex digits of four UUIDv7 keys. They grow over time.
The trade-off is that a UUIDv7 reveals roughly when the row was created. Many teams use bigint ids internally and expose a separate random UUID in URLs.
Enums (CREATE TYPE order_status AS ENUM (...)) are compact and readable, but awkward to evolve. You can add a value or rename one, but you cannot remove one or reorder them without recreating the type. Most teams prefer a CHECK (status IN (...)) constraint, as the course's orders table uses, or a small lookup table with a foreign key when statuses carry extra data such as a label or a sort order.
Arrays (text[]) are handy for a short list you only read whole, like tags on a post. Once you need to join on the elements, count them or enforce a foreign key, use a separate table. jsonb is the same story at a larger scale, and it gets its own lesson later in the course.
SQLite's type affinity and STRICT tables
Postgres enforces the declared type. SQLite, by default, does not. A column's declared type only gives it an affinity: a preference. SQLite converts a value when the conversion is lossless and otherwise stores whatever you gave it.
Press Run (⌘ Enter) to see what happens.In the loose table, '42' became the integer 42, 4.0 became 4, and 'abc' and 4.5 were kept as text and real in an INTEGER column. A STRICT table (SQLite 3.37 and later) behaves much more like Postgres: it still converts '42' losslessly, but it rejects 'abc'. Use STRICT for any new SQLite schema, such as a mobile app or a local tool.
Casting and integer division
You convert types with standard CAST(x AS type). Postgres also has the shorthand x::type, which you will see constantly in Postgres code but which SQLite and MySQL do not support.
SELECT CAST('2025-06-01' AS date), '42'::bigint, created_at::date FROM orders;Postgres is strict about mixing types. WHERE text_column = 5 fails with "operator does not exist: text = integer", and CAST('12abc' AS integer) is an error. SQLite quietly returns 12 for that cast. Strict is better: the error appears in development, not as wrong numbers in a report.
The trap that catches everyone in both Postgres and SQLite is integer division. Dividing two integers gives an integer, rounded towards zero:
Press Run (⌘ Enter) to see what happens.Four shipped orders out of ten gives a share of 0, not 0.4. Multiplying by 100.0 first makes the expression a decimal. MySQL is the odd one out: its / always returns a decimal, and DIV does integer division.
What does this print?
from shopdb import connect
db = connect()
row = db.execute("SELECT 7 / 2, 7 / 2.0, CAST(7 AS REAL) / 2").fetchone()
print(row)SQLite, loose (non-STRICT) table. What does this print?
from shopdb import connect
db = connect()
db.executescript("CREATE TABLE t (n INTEGER); INSERT INTO t VALUES ('7'), ('seven');")
print(db.execute("SELECT group_concat(typeof(n)) FROM t").fetchone()[0])total column to an invoices table in Postgres. Which type is the safest choice?Match each value to the Postgres type you would choose.
on_hold value from an order status that is stored as a Postgres ENUM. What is true?- identity column
- A standard auto-incrementing column,
GENERATED ALWAYS AS IDENTITY. Replaces the legacyserialshorthand in Postgres. - numeric
- An exact decimal type with a set precision and scale, such as
numeric(12, 2). The safe choice for money. - timestamptz
- A Postgres timestamp stored as a UTC instant and shown in the session's time zone. The default for any event time.
- UUIDv7
- A UUID that starts with a timestamp, so new values sort after old ones and index inserts stay local. Built into Postgres 18 as
uuidv7(). - type affinity
- SQLite's preference for a column's type. It converts values when lossless and otherwise stores them as given.
- STRICT table
- A SQLite table (3.37+) that enforces declared column types and rejects values that cannot be converted.
- integer division
- Dividing two integers gives an integer rounded towards zero, so
7 / 2is 3 in Postgres and SQLite.