CREATE TABLE: types that preserve meaning
Chapter 9 — “Blueprints”
QUERY dims the report feeds and spreads something across the table that you haven't seen before: no rows, no numbers, only lines. A thin, glowing framework of five Kotomarket tables shows their columns, types, and relationships. A blueprint for an entire world.
QUERY: You already have permission to change rows. Now you move up a level: you get to design the archive itself, rather than simply record facts in it. A schema carries its author's handwriting. Read it carefully, because that handwriting will show up in every query that follows.

CREATE TABLE: drawing a new table
Until now, you've worked with ready-made Kotomarket tables: selecting rows, joining tables, calculating , and updating data. Now you're at the drafting table yourself, deciding which tables exist, which columns they contain, and what values those columns can store.
These commands belong to — Data Definition Language. While SELECT, INSERT, UPDATE, and DELETE work with rows, DDL works with structure: tables, columns, types, indexes, and .
The minimal form looks like this:
CREATE TABLE table_name (
column1 DATA_TYPE,
column2 DATA_TYPE,
column3 DATA_TYPE
);
For example, let's create a simple coupon table:
CREATE TABLE coupons (
id INT,
code VARCHAR(20),
discount_pct INT,
active BOOLEAN
);
We haven't simply listed column names. We've defined a contract:
id INT: the column should contain whole numbers;code VARCHAR(20): the coupon code is a string up to 20 characters long;discount_pct INT: the discount is stored as a whole-number percentage;active BOOLEAN: the coupon is either active or inactive.
A data type isn't cosmetic. It tells the database what can go into a column, how to store it, and how to compare, sort, add, and filter its values.
Common types you'll need at the start
In PostgreSQL, you'll often see types like these:
CREATE TABLE products_draft (
id INT,
name VARCHAR(100),
description TEXT,
price NUMERIC(10,2),
available_from DATE,
created_at TIMESTAMP,
is_active BOOLEAN
);
Here's what they mean:
INT: a whole number, such as an ID, quantity, discount percentage, or inventory count;NUMERIC(10,2)/DECIMAL(10,2): an exact decimal number, such as a price, order total, or commission;VARCHAR(n): a string with a length limit, such as a code, email, or short name;TEXT: a string with no predefined length limit, such as a product description, comment, or note;DATE: a date without a time, such as a birthday, registration date, or promotion start date;TIMESTAMP: a date and time without a time zone, such as a local timestamp;BOOLEAN: a logical value, eithertrueorfalse.
In the Kotomarket blueprints, a product price shouldn't be text because prices need to be added, compared, and sorted as numbers. An order date shouldn't be a string because you need to build reports by day, month, and week.
A poor choice of type turns future queries into a fight with the archive:
-- Bad: the price is stored as text
price VARCHAR(20)
-- Good: the price is stored as an exact number
price NUMERIC(10,2)
If a price is stored as a string, the database doesn't know that it's money. You'll have to cast the value again and again, and sorting can produce surprises: '10.00' as text comes before '2.00' because the database compares characters rather than numbers.
A good schema makes future queries simpler. A bad schema forces every query to work around an old mistake.
Store money in DECIMAL/NUMERIC, not FLOAT/REAL.
FLOAT stores fractional values approximately. A value like 0.1 can't be represented exactly in binary, so tiny errors appear in calculations. They're almost invisible in one row, but across thousands of payments, a report can differ from the accounting totals by a few cents.
Money needs an exact type:
price NUMERIC(10,2)
An archive that's off by a cent can no longer be trusted.
Money: why FLOAT loses cents
A classic interview question: why shouldn't you store money in FLOAT?
Because FLOAT, REAL, and DOUBLE PRECISION are floating-point types. They're fast and useful for scientific calculations, measurements, coordinates, and probabilities, but they store many decimal fractions approximately.
Look at a simple example:
SELECT
0.1::float8 + 0.2::float8 AS float_result,
0.1::numeric + 0.2::numeric AS numeric_result;
Here's the idea:
float_result → may be extremely close to 0.3, but not exactly 0.3
numeric_result → exactly 0.3
Why does this happen? The decimal fraction 0.1 becomes an infinite fraction in binary. The database has to store an approximation. Add one approximation to another, then another, and the error can become visible in a large report.
This causes problems in two common situations.
First, totals:
SELECT SUM(amount)
FROM payments;
If amount is stored as FLOAT, the result may not match the accounting total you expect.
Second, comparisons:
SELECT *
FROM payments
WHERE amount = 0.3;
A row may appear to contain 0.3, while the stored value is actually slightly larger or smaller. That's why comparisons with = are often unreliable for FLOAT.
For money, there are usually two good options:
-- Option 1: an exact decimal number
amount NUMERIC(10,2)
-- Option 2: a whole number of minor currency units
amount_cents BIGINT
NUMERIC(10,2) is easy to read: 12.51.
BIGINT in cents is convenient in payment systems: 1251.
Both avoid the approximation problem you get with FLOAT.
TEXT vs VARCHAR(n): barely a debate in PostgreSQL
In PostgreSQL, TEXT, VARCHAR, and VARCHAR(n) are very similar in storage and performance. The main difference with VARCHAR(n) is that the database checks the length when you write a value.
CREATE TABLE customers (
name TEXT,
email VARCHAR(120)
);
In this example:
name TEXT: the name can be any reasonable length;email VARCHAR(120): the email must not be longer than 120 characters.
In PostgreSQL, VARCHAR(120) usually isn't faster than TEXT. It adds a rather than an optimization.
So a common PostgreSQL rule is:
- if length is a real business rule, use
VARCHAR(n)orCHECK; - if there is no strict limit,
TEXTis a good choice.
For example, you can express the limit explicitly:
CREATE TABLE customers (
email TEXT CHECK (length(email) <= 120)
);
This can sometimes be clearer because the rule appears as a separate constraint and can be discussed directly as part of the business logic.
This is specific to PostgreSQL. In other DBMSs, string types may differ more in their limits, storage, indexing, and behavior. In an interview, clarify the context: “In PostgreSQL, the difference is minimal; in other databases, you need to check the specific system.”
TIMESTAMP vs TIMESTAMPTZ: whose time is it?
TIMESTAMP and TIMESTAMPTZ may look similar, but they answer different questions.
TIMESTAMP is a date and time without a time zone. It stores a value like a reading on a wall clock:
2026-06-24 09:00:00
By itself, that value doesn't tell you where 9:00 a.m. is: Nha Trang, Montevideo, Moscow, or a server running in .
TIMESTAMPTZ is a date and time with time-zone awareness. In PostgreSQL, it stores a moment in time and displays it in the current session's time zone.
For real-world events, TIMESTAMPTZ is usually the right choice:
CREATE TABLE order_events (
id INT,
order_id INT,
happened_at TIMESTAMPTZ
);
Why? Because the event “order paid” happened at one specific moment. The user might have been in Vietnam, the server in Europe, and the analyst in Uruguay, but the moment of payment must remain the same.
A practical rule:
-- An event happened in the real world
paid_at TIMESTAMPTZ
-- A local schedule not tied to a specific moment
opens_at TIMESTAMP
For orders, payments, logins, deliveries, app events, and audit records, TIMESTAMPTZ is usually the better choice.
For a local schedule such as “the store opens at 09:00 local time,” TIMESTAMP may work. If you don't need the date, a separate type such as TIME may be enough.
QUERY marks a thin timeline on the blueprint:
QUERY: Remember:
TIMESTAMPanswers “what did the clock say?”, whileTIMESTAMPTZanswers “what moment was this in the world?” For an event archive, the second question usually matters more.
payments table. For the amount column, which stores dollar amounts with cents, choose a type that represents money exactly. The insert and final query are already in the starter code: at the end, it returns total (the sum of amount) and is_exact (whether that sum is exactly $1.00).Interview question
Interview question: A payments table stores amounts as FLOAT, and the monthly report differs from the accounting records by a few cents. Why did this happen, and how would you fix it?
Strong answer: FLOAT is an approximate binary type. It can't always represent decimal fractions such as 0.1 exactly, so errors can accumulate when you add thousands of rows. For money, use an exact type such as NUMERIC(10,2) / DECIMAL(10,2), or store the amount as a whole number of minor currency units, for example cents in a BIGINT.
You can strengthen the answer by mentioning that comparisons with = are also unreliable for FLOAT, because a value may be “almost 0.3” rather than exactly 0.3. When migrating old data, explicitly round the amounts and compare control totals before and after the .
Another common question: What's the difference between TEXT and VARCHAR(n) in PostgreSQL?
Strong answer: In PostgreSQL, the difference in performance and storage is usually insignificant. VARCHAR(n) adds a maximum-length check during inserts or updates. If the length limit is a real business rule, you can express it with VARCHAR(n) or CHECK. If there is no such rule, TEXT is a perfectly good choice. In other databases, the differences may matter more, so clarify which database you're discussing.
Quick self-check: What's the better choice for the time when an order was paid?
paid_at TIMESTAMPTZ
A payment is an event that happened at a specific moment in time. The server, user, and analyst should all interpret that moment consistently even when they're in different time zones.
paid_at that stores the actual moment in time rather than the local clock reading. Then the final query in the starter code will return id and city in the order the payments actually happened.Primary keys, required fields, and default values
A column's type determines what kind of data it can hold. But imagine a table that stores customer support notes. Each note needs a unique ID, the author must be specified, and it would be nice to record the creation time automatically. You can handle all three when you create the table by adding rules after the column types.
PRIMARY KEY defines a . Every row must have a unique value for this key, and NULL is not allowed. A primary key makes it easy to find a specific row. For example, a warehouse table could use a text code instead of a numeric ID:
CREATE TABLE warehouses (
code TEXT PRIMARY KEY,
city TEXT
);
More often, though, rows get numeric IDs. If you assign them manually, sooner or later someone will forget what the last ID was. PostgreSQL can generate the next number for you:
id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY
You'll often see id SERIAL PRIMARY KEY in older database schemas. It's an earlier way to generate the next number automatically whenever a row is inserted. So don't be surprised if you come across it in someone else's database.
NOT NULL makes a value required. For example, you shouldn't be able to save a note without an author or any text. If a required column contains NULL during an insert, PostgreSQL returns an error.
DEFAULT supplies a predefined value when you leave a column out of an insert. Say a support agent is writing a note about a customer. Why should they have to enter the time manually every time? The database can record the current time for them:
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
Let's put these rules together in one table. Each note in our support log will have its own ID, a required author and note text, and a creation time that PostgreSQL fills in automatically:
CREATE TABLE support_notes (
id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
author TEXT NOT NULL,
note TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO support_notes (author, note)
VALUES ('Мира', 'Клиент просит перенести доставку');
Look at the INSERT: we provided only the author and the note text. We didn't mention id or created_at at all, but PostgreSQL fills in both. The first row gets the ID 1, and created_at gets the current time. Try leaving author out of the insert, and you'll get null value in column "author" of relation "support_notes" violates not-null constraint. The database refuses to save a note without a required field.
QUERY: The
INSERTspecifies just two columns, but the finished row has four. PostgreSQL added the ID and timestamp on its own. Pretty handy when you have lots of notes! In the next lesson, we'll teach the database to enforce unique values, check references to other tables, and reject rows that fail validation rules.
price if it stores a product price in Kotomarket?- Event Log with Auto-Generated IDsEASY
- Idempotency Keys for Safe RetriesEASY
- Order Reconciliation Log for a Payment IncidentMEDIUM
CREATE TABLE coupons ( id INT, code VARCHAR(20),
discount_pct INT,
active BOOLEAN
);
INSERT INTO coupons (id, code, discount_pct, active) VALUES
(1, 'WELCOME10', 10, true),
(2, 'SPRING20', 20, false);
SELECT id, code, discount_pct, active
FROM coupons
ORDER BY id;