Choosing the Right Data Type — Database

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…

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()
);

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

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

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:

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

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.

What you will learn