Sunset Coffee's admin form sends Toast's price as '$5' (five dollars, typed with the dollar sign) into the price column, whose type is INTEGER and which holds whole cents. SQLite accepts it without an error. The next day, Toast sits at the top of the most-expensive list. Why that happens, and how to prevent it, comes in the SQLite section.
It all comes down to the data type: the kind of value a column may hold, whether a whole number, a decimal number, text, a time, or yes/no. Picture a tidy kitchen: eggs in the egg box, oil in a bottle, sugar in a jar. You could put all of it in one plastic bag, but the eggs would break and the sugar would spill. The right type makes the database reject the wrong value, store it compactly, and calculate correctly.
One table, one type per column
This is Sunset Coffee's products table written for PostgreSQL. Each column gets the type that fits its value best:
CREATE TABLE products (
id BIGINT PRIMARY KEY,
name VARCHAR(100) NOT NULL, -- product name
description TEXT, -- long description
country_code CHAR(2) NOT NULL, -- where the beans come from: 'CO', 'BR'
price DECIMAL(12, 2) NOT NULL, -- price, an exact number
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
VARCHAR(100): text with a length limit, here at most 100 characters. Good for names, emails, usernames.TEXT: long text with no limit worth thinking about. Good for a description or a blog article's body.CHAR(2): text that is always the same length, here 2 letters. Good for a country code.DECIMAL(12, 2): an exact decimal number, 12 digits in total with 2 after the decimal point. This is the type for money.BOOLEAN: onlyTRUEorFALSE, 1 byte in PostgreSQL. Good for an active/inactive status. AVARCHAR(10)holding'active'takes more room and can be mistyped.TIMESTAMPTZ: one exact moment in time. PostgreSQL stores it as UTC, then shows it in the connection's time zone, for example Singapore time (UTC+8). Good for a created-at time.BIGINT: an 8-byte whole number.INTEGER(4 bytes) goes up to about 2.1 billion,BIGINTgoes far beyond, so it's safe for the ID of a table that keeps growing.
Money: why not FLOAT
FLOAT, REAL and DOUBLE store a number in a binary form that is close, not exact. A number like 0.1 can't be written exactly in binary, just as 1/3 can't be written exactly as 0.333... Sunset Coffee has also started selling packaged products abroad, in dollars. This is what happens in the Lab when the price is stored as REAL:
CREATE TABLE export_items (id INTEGER PRIMARY KEY, name TEXT, price_usd REAL);
INSERT INTO export_items (name, price_usd) VALUES ('Milk Tea Sachet', 1.10), ('Palm Sugar 500 g', 2.20);
SELECT SUM(price_usd) AS total, SUM(price_usd) = 3.30 AS exact FROM export_items;
| total | exact |
|---|---|
| 3.3000000000000003 | 0 |
- The total of 1.10 + 2.20 is slightly off, just like
0.1 + 0.2, which gives0.30000000000000004. exactis0, meaning false: the cart total is not equal to 3.30. Imagine a "fully paid?" check that fails over a millionth of a cent.
There are two right ways. In MySQL and PostgreSQL, use DECIMAL(10, 2), which stores decimals exactly. Or store the smallest unit as a whole number: price_cents INTEGER holding 110 and 220 adds up to exactly 330, and = 330 is 1. That is how this track's products table stores every price: Milk Coffee's $4.50 is the whole number 450.
Text and time
- Choose
CHAR(n)only when the length is always the same,VARCHAR(n)when the length varies but has a sensible limit, andTEXTwhen the value can be very long. - Don't store numbers as text.
'9'sorts after'10', because text is compared character by character. - For time,
TIMESTAMPTZis safer than plainTIMESTAMP. ATIMESTAMPwithout a zone only stores the clock reading, so if the server moves from Singapore time to UTC, every time can read 8 hours off.
SQLite: types are only a suggestion
SQLite, the database the Lab and the Playground use, is much looser. A column type in SQLite is only a suggestion (it's called type affinity): it tries to turn the value into the column's type, and if that fails, it stores the value as it is.
CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price INTEGER);
INSERT INTO products (name, price) VALUES ('Milk Coffee', 450);
INSERT INTO products (name, price) VALUES ('Palm Sugar Milk Coffee', 550);
INSERT INTO products (name, price) VALUES ('Toast', '$5');
SELECT name, price, typeof(price) FROM products;
| name | price | typeof(price) |
|---|---|---|
| Milk Coffee | 450 | integer |
| Palm Sugar Milk Coffee | 550 | integer |
| Toast | $5 | text |
'$5' goes in without an error, as text. typeof() shows the type that was really stored. The text '500' (in quotes) is still turned into the number 500, but '$5' can't be, so it stays text. The result is quiet chaos:
ORDER BY price DESCputs Toast on top, as if it were the most expensive product, because SQLite always sorts text after numbers.SUM(price)gives1000: SQLite reads'$5'as the number 0.
Want SQLite as strict as other databases? Add STRICT at the end: CREATE TABLE ... ) STRICT;. Now the same INSERT is rejected: cannot store TEXT value in INTEGER column products.price. A STRICT table only accepts the types INT, INTEGER, REAL, TEXT, BLOB and ANY. SQLite has no exact DECIMAL either: a DECIMAL column still stores fractions as REAL, so in SQLite money is always stored as whole cents.
📌 MySQL, PostgreSQL and Laravel
MySQL and PostgreSQL reject a value that doesn't fit the type. This is PostgreSQL's answer to the same INSERT:
ERROR: invalid input syntax for type integer: "$5"
MySQL rejects it with an error too, because of strict mode, which has been on by default since version 5.7. If strict mode is switched off, MySQL stores 0 and only gives a warning. The VARCHAR(2) limit is enforced as well: PostgreSQL answers value too long for type character varying(2), while SQLite stores the longer text without complaint. TIMESTAMPTZ only exists in PostgreSQL; in MySQL use TIMESTAMP (stored as UTC) or DATETIME. BOOLEAN in MySQL is really TINYINT(1).
Those two time options in MySQL have different limits:
| MySQL type | When to pick it |
|---|---|
TIMESTAMP |
A moment close to now, for example created_at. MySQL converts it to UTC when storing it, then to the connection's time zone when reading it. Its range is only the years 1970 to 19 January 2038. Laravel's $table->timestamps() creates this kind of column. |
DATETIME |
A time outside that range, for example the end of a home loan in 2045. Its range is the years 1000 to 9999, but MySQL does not convert its time zone, so store it in UTC yourself. In Laravel: $table->dateTime('ends_at'), or $table->datetimes() for created_at and updated_at. |
In a Laravel migration: $table->string('name', 100), $table->text('description'), $table->char('country_code', 2), $table->decimal('price', 12, 2), $table->boolean('is_active'), $table->timestampTz('created_at').
⚠️ Money that drifts, types that get ignored
- FLOAT or REAL for money. The total drifts slightly and an
=comparison fails. UseDECIMAL, or a whole number of cents. - Turning dollars into cents with
CAST.CAST(4.35 * 100 AS INTEGER)gives434, not435, because4.35 * 100is stored as434.99999999999994andCASTdrops the fraction. Round first:CAST(ROUND(4.35 * 100) AS INTEGER). - Trusting SQLite to reject the wrong type. Without
STRICT, it stores whatever it gets. Check withtypeof(). - In the exercise, return the type name exactly: upper case, without a length, for example
"VARCHAR", not"varchar(100)".
TL;DR: Pick the type by the value: VARCHAR(n) for names, TEXT for long writing, CHAR(n) for a fixed-length code, DECIMAL(p, s) for prices, BOOLEAN for active/inactive, TIMESTAMPTZ for a created-at time. Don't use FLOAT for money: 1.10 + 2.20 becomes 3.3000000000000003. Store it in DECIMAL or as whole cents. SQLite treats a type as a suggestion only ('$5' goes into an INTEGER column as text) unless the table is STRICT, while MySQL and PostgreSQL reject it.
⚡ One column, one fitting type
Write:
CREATE TABLE products (
id BIGINT PRIMARY KEY,
name VARCHAR(100) NOT NULL, -- product name
description TEXT, -- long description
country_code CHAR(2) NOT NULL, -- where the beans come from: 'CO', 'BR'
price DECIMAL(12, 2) NOT NULL, -- price, an exact number
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
Meaning: The data type decides what kind of value may go in. VARCHAR(n) for names, TEXT for long writing, CHAR(n) for a fixed-length code, BOOLEAN for active/inactive, TIMESTAMPTZ for a created-at time.
In the exercise, return the type name exactly: upper case, without a length, for example "VARCHAR".
⚡ No FLOAT for money
Write:
SELECT SUM(price_usd) AS total, SUM(price_usd) = 3.30 AS exact FROM export_items;
Guess first: price_usd is a REAL holding 1.10 and 2.20. Does exact come out as 1 or 0?
It comes out as 0. The total is 3.3000000000000003, slightly off, so it doesn't equal 3.30.
Meaning: A price goes in DECIMAL(p, s), an exact decimal number, or is stored as a whole number of cents.
⚡ SQLite treats a type as a suggestion
Write:
INSERT INTO products (name, price) VALUES ('Toast', '$5');
Meaning: The price column is an INTEGER, yet '$5' still goes in as text, with no error. Add STRICT at the end of CREATE TABLE and SQLite rejects it, like MySQL and PostgreSQL do.